How to fix errors when installing varbase with Composer? I'm using Drupal 8 and I'm trying to install the varbase distribution from the command line, on Windows with Acquia Dev Desktop.

The steps I did are:

Disable opcache
Check composer -V  >>> result
Run composer create-project Vardot/varbase-build:^8.4.06 %1 --no-dev --ignore-platform-reqs

This is causing the following error:

  Installing vardot/varbase (8.4.06): Downloading (100%)
  Writing lock file
  Generating autoload files
  PHP Parse error:  syntax error, unexpected 'class' (T_CLASS), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in C:\www\tmp_var\vendor\drupal-composer\drupal-scaffold\src\PrestissimoFileFetcher.php on line 34
  Parse error: syntax error, unexpected 'class' (T_CLASS), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in C:\www\tmp_var\vendor\drupal-composer\drupal-scaffold\src\PrestissimoFileFetcher.php on line 34

I installed composor on windows Url:
https://getcomposer.org/download/

(This is besided the compososer which is included in Acuia Desktop Version 2)

C:\www>composer self-update
You are already using composer version 1.5.1 (stable channel).

Then I exectuted commando:

composer create-project Vardot/varbase-project:^8.4.07 varbaseyellowbird --no-dev >> installlog.txt

After running it my project drupal folder was not looking good so I runned it again.

Drupal 8 requires PHP 5.5.9 or greater. The error is informing you that you have a lower version than that installed; specifically that the functionality for obtaining class name using ::class, which was added in 5.5, is missing.

The solution is to upgrade PHP to a version that Drupal supports.


AJAX event returns same data always So, this is a simple form, and what the ajax call back does here is that it returns the value of a field that's being changed.

The problem is that, only the value of the first change is returned. If i change the value a second time, the returned value is the same as first.
I'm not sure what is happening here, it needs a better pair of eyes.

Here's the code

<?php

    //Create raffle form
    function raffle_create_form($form, &$form_state)
    {
        dpm($form_state);
        //Basic raffle info
        $form['raf_raffle_name'] = array(
            '#type' => "textfield",
            "#prefix" => "
Raffle information

",
            "#title" => "Raffle Name:",
            "#required" => TRUE
        );

        $form['raf_allowed_number'] = array(
            '#type' => "textfield",
            "#title" => "Number of allowed members",
            "#required" => TRUE,
            '#element_validate' => array('element_validate_number')
        );

        $form['raf_start_now'] = array(
            "#type" => "checkbox",
            "#title" => "Start raffle now?"
        );

        $form['raf_end_date'] = array(
            "#type" => "date",
            "#title" => "When to close this raffle?",
            "#required" => TRUE
        );

        $form['raf_prize_type'] = array(
            '#type' => "select",
            "#options" => array('gift' => 'Steam Gift', 'hardware' => 'Gaming peripherals'),
            "#title" => "Prize type",
            "#required" => TRUE,
            "#ajax" => array(
                'callback' => 'raffle_create_form_type_steam',
                'wrapper' => 'steam_options',
                'event' => 'change',
                'method' => 'replace',
            ),
        );

        $form['raf_prize_name'] = array(
            '#type' => "textfield",
            "#title" => "Prize name",
            "#prefix" => "

",
            "#required" => TRUE
        );

        $form['raf_prize_about'] = array(
            '#type' => "textarea",
            "#resizeable" => true,
            "#title" => "Prize description"
        );

        $form['raf_prize_thumb'] = array(
            '#type' => "file",
            "#title" => "Prize thumbnail"
        );

        $form['raf_prize_link'] = array(
            '#type' => 'textfield',
            '#title' => "Link to product"
        );

        $form['raf_raffle_create'] = array(
            '#type' => 'submit',
            '#value' => "Create Raffle",
        );

        $form['#submit'][] = 'raffle_create_form_submit';

        return $form;
    }

    function raffle_create_form_validate($form, &$form_state)
    {
        dpm($form_state);
    }

    function raffle_create_form_submit($form, &$form_state)
    {

    }

    function raffle_create_form_type_steam($form, &$form_state)
    {
        return $form_state['values']['raf_prize_type'];
    }**

Whatever data is returned must be encapsulated in a div element of the same id as the wrapper.

This fixed the problem for me :)

function raffle_create_form_type_steam($form, &$form_state)
{
    if($form_state['values']['raf_prize_type'] == 'hardware')
    {
        return "

";
    }
    else
    {
        return  $form['raf_steam_option_game_append'] = array(
                '#type' => 'checkbox',
                '#title' => 'Check if Steamer has game in library',
                '#description' => 'Does not allow gamer to join raffle if said gift already exists within gamer\'s steam library',
                "#prefix" => "
",
                "#suffix" => "
"
            );
    }

}


How to use Font Awesome with Bootstrap LESS theme? I have created a sub-theme, using the LESS Starterkit, of the Bootstrap theme. I would like to self host the Font Awesome icons and make them available to a custom module.

I have downloaded the Font Awesome project to: sites\all\themes\MYBOOTSTRAPTHEME\font-awesome.

Following these instructions, I have added the following (last four) lines to: sites\all\themes\MYBOOTSTRAPTHEME\less\variables-overrides.less:

//== Iconography
//
//## Specify custom location and filename of the included Glyphicons icon font. Useful for those including Bootstrap via Bower.

//** Load fonts from this directory.
@icon-font-path:          "../fonts/";
//** File name for all font files.
@icon-font-name:          "glyphicons-halflings-regular";
//** Element ID within SVG icon file.
@icon-font-svg-id:        "glyphicons_halflingsregular";

//** Load Font Awesome fonts from this directory.
@fa-font-path:            "../../font-awesome/fonts/";
//** File name for all Font Awesome font files.
@fa-font-name:            "fontawesome-webfont";

I have added the following line to my custom module:

<button type="button" class="btn btn-default btn-lg">
   Camera
</button>';

After recompiling my LESS: nothing. What am I missing. Thanks.

Figured it out. Add:

@import "../font-awesome/less/font-awesome.less";

to sites\all\themes\MYBOOTSTRAPTHEME\font-awesome\less\font-awesome.less.


How to create a views listing of all groups including a join link in OG 7.2x The 7.2x version of OG leverages the Entity Reference module to create the relationship between the group node and entity. There about 8 possible OG Entity Relationships to choose from in views that upon review seem pretty ambiguous. I just need to figure out which one(s) are required to create a join link when listing all of the groups on the site.

Add a field to your view of the type Content: Group - set the formatter to OG subscribe link - screenshots in this thread on drupal.org:

http://drupal.org/node/1816096


Build a blog archive block with code I want to build a "Blog Archive" block with a custom module. How do I do it?

create a new folder in /sites/default/modules
create a custom_blocks.info file inside that folder
add this content in the file:

name = Custom blocks
description = "A short description of your module"
package = My modules
files[] = custom_blocks.module
core = 7.x

create another file: custom_blocks.module (note that you've specified this in the info file)
add this PHP code:

<?php
  function custom_blocks_block_info() {
    $blocks = array();

    $blocks['unique_id_for_your_block'] = array(
      'info' => t('block info'),
      'cache' => DRUPAL_NO_CACHE,
    );

    // You can add more blocks here.

    return $blocks;
  }

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

    switch ($delta) {
      case 'unique_id_for_your_block':

        // Put your logic here and generate the HTML you want to display in your block.
        $block['subject'] = t('block title');
        $block['content'] = 'Put here the HTML generated above';
        break;

      // Add more case statements here if you defined more than one block.

    }

    return $block;
  }

go to your module page, activate the module, go to the block configuration page and activate your new block
read more here:

Writing a Drupal 7 module
Drupal 7 Block API


user register hook form alter not reaching I am trying to request more information from users when they register for my site.  I put a set-message in and it's not eve appearing nor any changes in the user register form.

I cant seem to find anything online to work, any help would be greatly appreciated.  Thanks!

 <?php
       function hook_form_alter(&$form, &$form_state, $form_id){

         drupal_set_messge($form_id);

         if ($form_id == "user_register_form") {
              $form['account']['name']['#title'] = t('Full name');

              $form['city'] = array(
                '#type' => 'textfield',
                '#title' => t('City'),
                '#size' => 15,
                '#required' => TRUE,
              );

              $form['state'] = array(
                '#type' => 'textfield',
                '#title' => t('State'),
                '#size' => 15,
                '#required' => TRUE,
               );

               $form['#submit'][] = 'hook_from_alter_submit';

          }

     }

    function hook_form_alter_submit($form, &$form_state) {

       $city = $form_state['values']['city'];
       $state = $form_state['values']['state'];
    }

 ?>

The naming convention for hooks is:

MODULENAME_hook_name()

So to implement hook_form_alter() in a module called MYMODULE, your function would be defined as:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  // ...
}

Have a look at What is the basic concept behind hooks? for a more detailed explanation.


Cancel email in hook_mail In hook_mail() I might discover that some part of the email couldn't be generated (maybe when trying to load a variable from an external system it fails).

How can I cancel the sending? I don't want to send an email with an error message in it.

Example code:

function mymodule_mail($key, &$message, $params) {
  switch ($key) {
    case 'some_email':
      $foo = Something::fetchSomething($params['bar']);
      if (!$foo) {
        // I don't want to send this email any more
      }
      else {
        $message['body'][] = t('Important information about @foo.' ['@foo' => $foo]);
      }
      break;
  }
}

Does that make sense? Or should all parameters be loaded and processed before hook_mail() and in hook_mail() you assume to always have those params available?

You can do the access check from hook_mail_alter instead of hook_mail (let it prepare the default message based on parameters, and alter it later) by something like:

function HOOK_mail_alter(&$message) {
  // can add additional check for particular mails here,
  // by checking the value in $message['id']
  if (TRUE) {
    $message['send'] = FALSE;
  }
}

Note: You should clear the cache in order to make the changes effective.


Simulate remote drupal user I am looking for a way to use an authenticated user session to remotely create content on my Drupal site.

My challenge is a somewhat complex one so please bear with me.

Using the Poster Firefox addon I am able to simulate creating and logging a user onto a Drupal website. The issue now is how to enable a persistent connection. So, using Chrome I login and I detect the session cookie details. I then try to use those cookie details in the Firefox Poster addon interface to remotely create a new node(page) on my drupal site.
The objective is for Drupal to report the new remotely created node(page) as authored by my logged-in user on the Chrome browser.

Ultimately, I am trying to figure out the recipe to translate to a program that will serve as the remote client while Drupal is used as a server.

I hope someone can shed some light on this issue for me.
Thanks for your time.

PS: The following images show how I am setting the http post header containing the cookie information and the variables Drupal uses to create my remotely created node.

I suggest you look into the Services Module. The entire concept is based upon 'programmatic remote users' logging into a Drupal site and accessing whatever portion of the 'out of the box' site API you enabled for your remote users to access. Additionally, Services offers a well designed means of creating your own API routines that your selectively expose to different remote users.

The out of the box API calls enable you to create users, nodes, comments, and so on. Most of the basic operations a user can do are available.

Check out: http://drupal.org/node/1070066


Error running a PHPUnit test only under run-tests.sh I'm working on an 8.x module that uses PHPUnit tests.  I've been running these from the command line using the embedded phpunit script that's installed with Drupal 8:

../vendor/bin/phpunit PATH/TO/MY/FILE.php

Both of my tests work w/o any problems under both PHP 5.5 and PHP 5.6.

But the Drupal testbot is failing both of my tests with the error

Fatal error: Trait 'Drupal\Tests\my_module\MockSessionTrait' not found in /var/www/.../PATH/TO/MY/FILETest.php

Using phpunit from the command line, this same trait is found w/o any trouble.

If I run the tests myself from the command line, but this time using run-tests.sh, I get the same error the testbot gets:

php scripts/run-tests.sh --url http://192.168.88.42/drupal --class 'Drupal\Tests\my_module\Unit\FILETest'

The stack trace looks like this:

PHP Stack trace:
PHP   1. {main}() /var/www/drupal/core/scripts/run-tests.sh:0
PHP   2. simpletest_script_get_test_list() /var/www/drupal/core/scripts/run-tests.sh:76
PHP   3. class_exists() /var/www/drupal/core/scripts/run-tests.sh:807
PHP   4. spl_autoload_call() /var/www/drupal/core/scripts/run-tests.sh:807
PHP   5. Symfony\Component\ClassLoader\ApcClassLoader->loadClass() /var/www/drupal/core/scripts/run-tests.sh:0
PHP   6. require() /var/www/drupal/vendor/symfony/class-loader/ApcClassLoader.php:114

I'm guessing that I need to help run-tests.sh to find my files, somehow.

Any advice from anyone as to why run-tests.sh behaves differently here from stock phpunit?

@Berdir is completely correct here:

  I'm not sure but you might not be able to have a non-test class in the tests/src location, try moving that to module/src/... and change the namespace accordingly (Drupal\module...

While PHPUnit doesn't mind if a test class uses a trait that's in a Drupal\Tests namespace, the simpletest test runner run-tests.sh will be unable to find the trait if you do this.

So don't do that.

Even if a trait is used only with your test classes, if you want your code to get past the Drupal testbot, the trait needs to live somewhere in your Drupal\your_module\ namespace. Do this, and both phpunit and run-tests.sh will be happy.


Send mail to selected users I want to send mail on webform submission to selected users. Suppose I'm user and admin must select users from my account that if I submit webform, then how many user's can get that notifications of my webform submission via mail?

Use simplenews module

Simplenews

  Simplenews publishes and sends newsletters to lists of subscribers.
  Both anonymous and authenticated users can opt-in to different mailing
  lists. HTML email can be sent by adding Mime Mail module.

  Simplenews 7.x-1.0 has finally been released which includes a number
  of other important bugfixes, especially in the upgrade path.

  Features Sending nodes as newsletters to subscribers Multiple
  newsletter categories with separate settings Per category and
  multi-signup Blocks and Pages Subscriber management including
  mass-subscription and export Optional E-mail confirmations for
  anonymous users Customizable newsletter templates Support for HTML
  (including text alternative) newsletter when used in combination with
  a supported mail system module Views and Rules integration Support for
  multi-language newsletters


How do I skip validation for node form element? I have a content type having 10 fields that are all required. How do I skip validation for some fields? Is there any hook/function that allow me to do this?

I consider that by

  How do I skip validation

you mean "make the fields not compulsory" (UI level)

If that is the case then you can use hook_form_alter and change the
['#required']
setting, for any form element, to
FALSE.

Keep in mind that hook_form_alter is a generic hook invoked by any form in your site (performance issue) alternative you may use hook_form_FORM_ID_alter to "to talk" to a specific form. Hope that helps.

If you want to make the validation on a different level, you have to write your own validation handlers (['#validate']) or override Drupal's, like node_form_validate


Drupal Commerce - Retrieve cart value I'm trying to create a popup notification on a route that shows the current cart value (subtotal) and notifies users to add $X.XX to receive free shipping.

I have extended a route to add new functionality but I'm unsure whether a hook or service would be best/appropriate.  I can't seem to find any documentation on cart value--I can see some functions for retrieving quantity of items and seemingly could calculate the price by retrieving the prices for each individual item but research isn't bringing up much.

I see information regarding Order Totals but one would seemingly have to finish the order process in order to retrieve that data.  I'm trying to grab cart value when a user goes to the /cart page.

I'm not asking for anything specific, just a pointer in the right direction.  Thank you.

If you know the store id and order type then

$store_id = 1;
$order_type = 'default';
$cart_manager = \Drupal::service('commerce_cart.cart_manager');
$cart_provider = \Drupal::service('commerce_cart.cart_provider');
$entity_manager = \Drupal::entityManager();
$store = $entity_manager->getStorage('commerce_store')->load($store_id);
$cart = $cart_provider->getCart($order_type, $store);
$cart->get('total_price')->getValue()[0]['number'];


AJAX callback function never called I'm having trouble with something incredibly simple:
When I select an element in a multiselect-form element, I want a textfield to become enabled. The problem I'm having is that Drupal never manages to get in the callback-function I specified.

Here I create my multiselect-element:

$form['foocat'] = array(
  '#type' => 'fieldset',
  '#title' => t('Manage subcategories'),
  '#prefix' => '
',
  '#suffix' => '
',
);
$form['foocat']['subcategories'] = array(
  '#type' => 'select',
  '#default_value' => '',
  '#title' => $foocategory,
  '#options' => $options,
  '#ajax' => array(
    'callback' => 'edit_displayname_callback',
    'wrapper' => 'displayname',
  ),
  '#attributes' => array('id' => 'foocats',),
  '#prefix' => '
',
  '#suffix' => '
',
  '#size' => 9,
);

A little bit further in the code I create my textfield:

$form['foocat']['subcat_displayname'] = array(
  '#type' => 'textfield',
  '#title' => t('Name'),
  '#default_value' => $entity->foocategory,
  '#size' => 25,
  '#maxlength' => 31,
  '#prefix' => '
',
  '#suffix' => '
',
  '#disabled' => TRUE,
);

if(!empty($form_state['subcategories'])) {
  $form['foocat']['subcat_displayname']['#disabled'] = FALSE;
  //Code for setting the textfield, dependent on what's been selected in the multiselect
}

And this is my callback function:

function edit_displayname_callback($form, &$form_state) {
  watchdog("Test", "Testing callback..", array(), WATCHDOG_ALERT);
  return $form['foocat']['subcat_displayname'];
}

The callback is never even called, and I have no idea why. I use AJAX in another part of the same form, and there it does work, so I'm guessing it's not a form problem.

Can anyone spot the problem?

I guess you are changing the id with '#attributes' => array('id' => 'foocats',),
And now the callback is not executed because the id is changed.

if you change your code it will work ( tested this in my own install )

$form['foocat']['subcategories'] = array(
  '#type' => 'select',
  '#default_value' => '',
  '#title' => $foocategory,
  '#options' => $options,
  '#ajax' => array(
    'callback' => 'edit_displayname_callback',
    'wrapper' => 'displayname',
  ),
  //'#attributes' => array('id' => 'foocats',),
  '#prefix' => '
',
  '#suffix' => '
',
  '#size' => 9,
);


As @lenni rightly says it's a serialized PHP variable. But data is a property of the user entity type so you don't actually need to unserialize it yourself.

When the user object is loaded from the database it's automatically populated with the unserialized version of the data column. So all you need to do to access your 'user tokens' field (if such a field exists, it doesn't appear to from your screenshot) is this:

global $user;
$user_tokens = $user->data['user tokens'];


Question about Managing JavaScript in Drupal 7 If you go to  https://www.drupal.org/node/756722#behaviors    at Behaviors section you will see:

  (function ($) {
     Drupal.behaviors.exampleModule = {
     attach: function (context, settings) {
     $('.example', context).click(function () {
     $(this).next('ul').toggle('show');
  });
 }

};

})(jQuery);

I think 'example' should be the name of a class like:

<?php echo click here?> <?p>

so when clicking on "Click here", the toggle will work. Am I right? And also what is 'ul' in $(this).next('ul').toggle('show');?

So if I have :

 for($b=1;$b<$number;$b++)
   {  ?>

<?php echo "Commentsfor Paragraph $b:" ."
" . "
" ; ?>

    <?php
      print render($p[$b]);
      ?>

 <?php

      }

and what I want to hide or show is the in , then can I write:

or can I mention the class or id of div  in $(this).next('div').toggle('show'); , so that the data in that part will hide or show? I hope I am clear.

Those examples are not complete working code examples.

They are just to illustrate that in Drupal 6 you did this:

Drupal.behaviors.exampleModule = function (context) {
  // Your code goes here.
}

And in Drupal 7 you would generally do this:

Drupal.behaviors.exampleModule = {
  attach: function (context, settings) {
    // Your code goes here.
  }
};

The rest of the code in those examples is not relevant.

However:

Yes, it means that if you click an element with the class "example" it will run the code in your click handler. Your example code is buggy though, it should be like this: <p class="example"><?php echo 'click here'; ?> </p>
The "ul" is referring to an unordered list element. So it will get the next ul from the element you clicked and toggle it.

[EDIT]

To answer your additional question about the example code:

  or can I mention the class or id of div in $(this).next('div').toggle('show'); , so that the data in that part will hide or show?

Yes you can specify any selector you want, for example:

$('.comment').toggle('show');


Using Views Slideshow to display images with specific url links I'm new to Drupal and I'm using version 7. I have created a Banner content type, to which I have added an Image field and a Link field (using the Link module). I have allowed theupload of multiple images, and adding of multiple links in this content type.

I then used Image Link Formatter module, which adds a formatter to display an image with a link. This works fine when I add a Banner content type and preview it. However, I want this Banner to be displayed by the Views Slideshow.

Unfortunately, I can't get things to display correctly when setting up a view block. If I choose to display the content, then it renders all the banners in a single slide (as might be expected). If I select the banner image field only, and choose the Image Link Formatter, it displays the banner images but not the links. I tried adding the link field as a hidden item too, however this has no effect.

As an alternative solution, I tried following this tutorial - here, it says to use the Rewrite Results option 'Output this field as a link' for the banner image, which I did and set to the link field. This didn't work as expected either though - the mapping multiplied the amount of banners, and output each banner with each link. For example:

Banner 1 - Link 1
Banner 2 - Link 1
Banner 1 - Link 2
Banner 2 - Link 2

What am I doing wrong here with the 2 approaches I tried, and what would be the recommended way to accomplish what I require?

As pointed out by @Clive and @loolooyyyy in the comments, the problem here is that there were multiple images on a single node.  Best practice (and problems like this one) dictate that there should be one node per slide.

Answered to remove this post from 'unanswered' list, all credit goes to the commenters who were here long before me.


I would like to be able to trap when a particular message is sent via drupal_set_message I would like to be able to trap when a particular message is sent via drupal_set_message like:
"•Article john mitchell article800 has been reverted back to the revision from Tue, 05/28/2013 - 10:03."
After the message is sent that matches my criteria then I would like to send an email.
I know how to send emails within hooks/php but I need to know how to trap for a particular message so that I know to send this email.
Are their any hooks that could use to trap for this occurrence?

In Drupal 6, messages are themed for display via...

function theme_status_messages($display = NULL) {
  $output = '';
  foreach (drupal_get_messages($display) as $type => $messages) {
    $output .= "
\n";
    if (count($messages) > 1) {
      $output .= "
\n";
      foreach ($messages as $message) {
        $output .= '
'. $message ."
\n";
      }
      $output .= "
\n";
    }
    else {
      $output .= $messages[0];
    }
    $output .= "
\n";
  }
  return $output;
}

In Drupal 7, they are themed similarly via...

function theme_status_messages($variables) {
  $display = $variables['display'];
  $output = '';

  $status_heading = array(
    'status' => t('Status message'),
    'error' => t('Error message'),
    'warning' => t('Warning message'),
  );
  foreach (drupal_get_messages($display) as $type => $messages) {
    $output .= "
\n";
    if (!empty($status_heading[$type])) {
      $output .= '
' . $status_heading[$type] . "
\n";
    }
    if (count($messages) > 1) {
      $output .= "
\n";
      foreach ($messages as $message) {
        $output .= '
' . $message . "
\n";
      }
      $output .= "
\n";
    }
    else {
      $output .= $messages[0];
    }
    $output .= "
\n";
  }
  return $output;
}

so I'd imagine copying the appropriate function into your theme's template.php and naming it YOURTHEME_status_messages(...) along with some suitable regexing or strposing inside would do the trick pretty directly.


Content is not filter with conceptual filter in views I am using two view one view as a page with exposed filter and  another view as a block and filter the content by getting Value from url in  contextual filter.

Exp:http://exp.com/?field_project_catagory_tid=112&field_nd_portfolio_tid=92

If we use one conceptual filter this http://exp.com/field_project_catagory_tid=112

and  get the value with use the PHP code in conceptual filter

$path=drupal_get_path_alias($_GET["field_project_catagory_tid"]);
return $path;

Its working fine and listed the value in both the views

If  we pass one more filter then we have url Like this
 http://exp.com/?field_project_catagory_tid=112&field_nd_portfolio_tid=92
and it works collectively fine.

but if user filter with one filter it is not working.

Then how we can use the value in contextual filter for individually also. Please help

Use all instead of id in any one parameter if you want to consider only one parameter.
e.g. like

http://exp.com/?field_project_catagory_tid=112&field_nd_portfolio_tid=all

or

http://exp.com/?field_project_catagory_tid=all&field_nd_portfolio_tid=112


How do I pre-configure default blocks for my drupal 7 theme I'm open-sourcing a custom drupal theme, and I'm looking to provide a good out-of-the-box experience to those who use it. However, when the theme is enabled for the first time, many of the default drupal blocks (search, user login, "powered by drupal," etc.) are all jammed in the first block-region (pre-header), which pushes everything down and makes the page look broken.

I'd like to do one of the following things:

Unassign all blocks by default for the theme, to give users a
clean slate
Pre-position the blocks into more appropriate regions

I don't want to do it in an install profile or a module, to keep things simple for end-users. Any ideas?

You can't control this from the theme at the time it's being enabled.

Drupal will try to assign each block enabled for the default theme to the same region in your theme, if available. If there's no region with a coincident name, it will drop the block to the default region, that is the first region defined in your theme's .info.

So there're two things you can do:

use more standard region names (sidebar_first, sidebar_second, footer)
in theme's .info, declare in the first place the more suitable region for orphaned blocks


view with nested relationships I have 3 node types. A, B and C.

A has an entity reference to B. B has an entity reference to C.

A has a list field. One of the values is "4". I need to display all node of type C where the top parent of type A has the value 4 in this list field.

I created a 'relationship referencing entity:field_in_type_a_reference_to_type_b'. And I created a context filter 'provide default value:4' with the relationship.

This part works. Only nodes of type B with parent nodes with list value '4' are displayed.

But I need the filter for one reference level deeper, for nodes of type C. I created one more relationship referencing entity:field_in_type_b_reference_to_type_c with the relationship. I tried this relationship with and without the other relationship.

But with no success. Nodes of type C aren't displayed.

How can I get the relationship from C to A?

It sounds like you're starting with node type B, whereas you should be starting with node type C.

Create your view with appropriate filters so that you only see nodes of type C
Add a "Entity Reference: Referencing entity" (not "Referenced entity) relationship for the B->C entity reference field, give it an identifier of something like "Entity B", tick "Require this relationship
Add another "Entity Reference: Referencing entity" relationship for the A->B entity reference field, use relationship "Entity B", give it an identifier of "Entity A", tick "Require this relationship
Add a filter (a regular filter, not a contextual one) requiring that your field has a value of "4", use relationship "Entity A"


Image not showing in Drupal 7 Site is hosted in fasthosts wherein <IfModule>  is not supported so they advice me to edit .htaccess to something like this.

Comment,
Order allow,deny
</FilesMatch>
Options –Indexes
Options +FollowSymLinks
DirectoryIndex index.php
Enable expirations
ExpiresActive On
ExpiresDefault A1209600
ExpiresByType text/html A1

Sample:

#<FilesMatch
#"\.(engine|inc|info|install|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl|svn-base)$|^(code-style\.pl|Entries.*|Repository|Root|Ta
#g|Template|all-wcprops|entries|format)$">
# Order allow,deny
#</FilesMatch>

It solved my first issue, 500 error.

This time, another error is showing, images are not correctly showing and css.
Instead of the path to be site.com/drupal installation/ image of path, image address become site.com/image of path.

By the way, I am installing drupal in a sub folder. site.com/dupalHere

Add line

RewriteBase /dupalHere

to your .htaccess file.


How do I troubleshoot 'Theme key "" not found'? How do I troubleshoot the error Theme key "" not found?

I found dozens of search results regarding specific keys, but nothing useful for debugging an empty key ("").

Here is the full entry from syslog:

Sep 12 09:45:47 core drupal: http://www.example.com|1347457547|theme|192.168.1.10|http://www.example.com/|http://www.example.com/admin/config/development/logging|1||Theme key "" not found.

What exactly triggers this error and how should I go about debugging it?

This warning message comes from theme() function in includes/theme.inc. For temporary debug you could just add ddebug_backtrace() there (if you're using Devel module) to see where the call comes from (and see what are the params). If not using Devel, just check output of debug_backrace(). And then it all depends what you are going to find out...


How to redirect to www without editing .htaccess file? What alternative methods are there for redirecting all page requests to the www version of a domain?

I know how to eidt the root .htaccess file but find that this method does not survive core updates.

Is there another way? Perhaps with a module?

It's always going to be better to do this with .htaccess, or in other web server config, but if you need to do it in php, put this at the top of settings.php:

if ($_SERVER['HTTP_HOST'] == 'example.com') {
  header('Location:http://www.example.com' . $_SERVER['REQUEST_URI']);
  exit();
}


Caching mysql results in cache table to be retrieved later How can i fetch records from mysql results stored in cache table ?

$cached_res_obj = cache_get("expensive_sql", MY_CACHE_TABLE);
$res            = $cached_res_obj->data;
while ($row = db_fetch_array($res)) {
    print_r($row);
}
die(__FUNCTION__);

I dont get any results. If i run the actual query through drupal I get results.
What should be done here ?

You can't store the query result resource directly in the cache table as it can't be serialised. Instead you should loop through that resource when you first run the expensive query, and cache an array of results, like so:

$q = db_query('expensive sql here');
$data = array();
while ($row = db_fetch_object($q)) {
  $data[] = $row;
}

cache_set('expensive_sql', $data, MY_CACHE_TABLE);

Then when you pick it up at the other end you can just loop through that array:

$cached_res_obj = cache_get("expensive_sql", MY_CACHE_TABLE);
$res            = $cached_res_obj->data;

foreach ($res as $row) {
  print_r($row);
}


How to assign blocks to particular regions on theme install? Drupal 8 provides some blocks by default. Eg. Site Branding, Main Navigation, Powered by Drupal, Search etc.

I have created a theme that has Site branding & Main Navigation named regions in which corresponding blocks can be placed.

When I enable my theme, Site Branding & Main Navigation blocks are placed in Header & First Sidebar region of my theme by default respectively.

How can I place Site Branding & Main Navigation blocks to their respective regions by default on theme install?

First of all, you should change each desired block region you want manually at Administration>Structure>Block layout Tab and then go to the config export function at:
Administration>Configuration>Development>Configuration synchronization>Export Tab>Single item to export each the block settings for your theme.
Then you should take a look at to the generated YAML files and placed that in a new folder within your theme at /config/install. you then uninstalled the theme and then reinstalled it as the default.

Summary:
1. Install MY_THEME
2. Place the blocks in the desired regions
3. Export config files and remove from them uuid and core config hash
for example Site Branding block block.block.MY_THEME_branding.yml file

langcode: en
status: true
dependencies:
  module:
    - system
  theme:
    - DEPENDENT_THEME
id: MY_THEME_branding
theme: MY_THEME
region: site_branding
weight: 0
provider: null
plugin: system_branding_block
settings:
  id: system_branding_block
  label: 'Site branding'
  provider: system
  label_display: '0'
  use_site_logo: true
  use_site_name: true
  use_site_slogan: true
visibility: {  }

Place config files to MY_THEME/config/optional or MY_THEME/config/install directory (if you're absolutely sure all dependencies are met)
Uninstall MY_THEME and clear all caches
Reinstall MY_THEME again


Load an iFrame to Drupal with JavaScript Because of Google Analytics I would need to use JavaScipt to load iFrame to my Drupal template. I use this only just on one custom content type template.

Can I put the JavaScript straight to the template?

At the moment the JavaScript in my node template is like this:

<script type="text/javascript">
var iframe = document.getElementById('myIFrame');
iframe.src = pageTracker._getLinkerUrl('http://mydomain.com/iframepage/');

</script>

<iframe id="myIFrame" height="500px" width="350"></iframe>

But it doesn't load anything to the iFrame. I followed this http://code.google.com/intl/fi/apis/analytics/docs/tracking/gaTrackingSite.html#trackingIFrames

Any idea where the problem is?

EDIT: noticed that I get error: "Uncaught ReferenceError: pageTracker is not defined"

Your code is missing some important stuff. The original code from the Google page you linked yourself:

_gaq.push(function() {
  var pageTracker = _gat._getTrackerByName();
  var iframe = document.getElementById('myIFrame');
  iframe.src = pageTracker._getLinkerUrl('http://www.my-example-iframecontent.com/');
});

So you would end up with something like the following.

<script type="text/javascript">_gaq.push(function () {
  document.getElementById('myIFrame').src = _gat._getTrackerByName()._getLinkerUrl('http://www.my-example-iframecontent.com/');
});</script>
<iframe id="myIFrame" height="500px" width="350"></iframe>


Services 7.3 - Simple Resource Example works only with GET not with POST from Poster I created a very simple test service here is the code, for some reason only GET works with it in Firefox Poster, but POST returns a 404 Controller not found. Any tips?
Here is what works
http://mysite.com/services/myendpoint/mytest/retrieve/

with parameter of
id = 1

<?php

/**
 * Implementation of hook_services_resources().
 */
function mytest_services_resources() {
  return array(
   'mytest' => array(
     'retrieve' => array(
       'help' => 'Retrievs a test',
       'callback' => '_mytest_retrieve',
       'args' => array(
         array(
           'name' => 'id',
           'type' => 'int',
           'description' => 'The id of the test to get',
           'source' => array('path' => '0'),
           'optional' => FALSE,
         ),
       ),
     ),
   ),
  );
}

/**
 * Callback for creating  resources.
 *
 * @param object $data
 * @return object
 */
function _mytest_retrieve($id) {
  return "READY TESTING";
}

?>

You need separate callbacks for each of the CRUD operations. You've only implemented 'retrieve', which is the GET callback, you need to implement a 'create' callback for POST to function.

Reading the docs really helps:
https://drupal.org/node/783460


How to add a custom vertical tab to node edit form? How can I add a block with some HTML to the Node Add/Edit form? I've tried adding a new #markup field but I couldn't position it where I need by using weight.

See image below for desired location: just below the vertical tabs displayed to the right in the Seven theme.

If you're looking insert renderable elements into the form array in the same manner as the grouped vertical tabs, you can hook_form_alter() your way to this via adding a details form element:

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

  // @TODO: Add your own logic for filtering relevant node forms
  if (in_array($form_id, array('node_page_form', 'node_page_edit_form'))) {
    $form['example'] = array(
      '#type' => 'details',
      '#title' => t(''),
      '#description' => t(''),
      '#group' => 'advanced',
      '#open' => TRUE,
      'markup' => array(
        '#markup' => '
Random Markup
',
      ),
      '#weight' => 1000,
    );
  }
}

If you're looking to add markup that's not relevant to your node forms, you might be better off subtheming Seven and adding your own node-edit-form.html.twig template to your subtheme with your own markup additions:

    {{ form|without('advanced', 'actions') }}

    {{ form.advanced }}

Random Markup

    {{ form.actions }}


EntityFieldQuery select entity if at least one tid is in the array? This seems like it would be a common need but I don't see how it can be done with the operators available. I have a taxonomy reference field that allows multiple values. I would like to construct an EntityFieldQuery that selects the entity if at least one of the tid's is in the given array.

$query->fieldCondition('field_tags', 'tid', $tid_array, 'CONTAINS_ONE');

All you need is:

$query->fieldCondition('field_tags', 'tid', $tid_array);

From EntityFieldQuery::addFieldCondition():
"The operator can be omitted, and will default to 'IN' if the value is an array, or to '=' otherwise."


What are the required fields to create user through social media login? I want to integrate Social Media Login (which is not a module name, I am going to integrate the HybridAuth Social Login module) in my website. So that I just want to know the required (by our website Drupal signup) fields in social sign up process.

I guess that username and email are required, but is the password required?

For Social Media Login Password field is not required. Only Username, Email-ID is required. After register with with social media login, Your account is pending for approval by the site administrator. You will receive an email once your account has been approved and you can then login with your Google account.


Hook_preprocess - disable CSS caching with drupal_add_css I'm wondering how to disable css caching when you use the function drupal_add_css. In hook_preprocess I have some dynamic css loading with this function and by default it generates a cached version of the css file (f.e. style.css?ow65jm) and I couldn't find any information on how to disable this. It gives an issue with some third party applications how rebuild a page view (f.e. Hotjar) who expect a single version of an certain file.

I've checked the performance settings (admin/config/development/performance) and CSS and JS merge/compression is disabled.

Adding the CSS files directly into the tpl files can fixes this but can this also be accomplished with in the preprocess hook and with the drupal_add_css function.

Update - Added template.php and .tpl code:

template.php:

function mytheme_preprocess(&$vars, $hook) {
...
if (!(path_is_admin(current_path())) || (arg(0) == 'user' && arg(2) == 'edit')) {
      drupal_add_css('https://fonts.googleapis.com/css?family=Merriweather:700', array('type' => 'external'));
      drupal_add_css( $path_odisee . '/css/normalize.css', array('group' => CSS_THEME, 'every_page' => TRUE, 'weight' => -10));
      drupal_add_css( $path_odisee . '/css/odisee.css', array('group' => CSS_THEME, 'every_page' => TRUE, 'weight' => 0));
      drupal_add_css( $path_odisee . '/css/override.css', array('group' => CSS_THEME, 'every_page' => TRUE, 'weight' => 0));
    }
...
}

html.tpl.php:

...
<head>
  <?php print $head; ?>
  <title><?php print $head_title; ?></title>
  <meta name="viewport" content="width=device-width,initial-scale=1">

  <?php print $styles; ?> <!-- here the preprocessed CSS gets loaded -->

</head>
...

Additional information:
The people over at Hotjar suggested to keep the cached versions of the css files on the server. Any suggestion on how to force this?

You can try using AdvAgg. Not sure it'll fix your issue because the source of the problem hasn't been identified. https://www.drupal.org/project/advagg


Cant find any info on this method being removed in webform or how to fix I am writing a patch for a module that used an old beta or even alpha of webform for drupal 8.

There is a line WebformEntityReferenceItem::getEntityWebformFieldName($node); in the module that errors out saying getEntityWebformFieldName() does not exist and sure enough in Drupal\webform\Plugin\Field\FieldType\WebformEntityReferenceItem the method does not exist.

I checked an older release and the method was there at some point. I've been searching since yesterday but cannot find a workaround or even an answer as to why it was removed. Any ideas?

EDIT

So I managed to get it working, but this certainly seems like the incorrect way to do it.

$node->get('webform')->getValue()[0]['target_id'];

So it seems WebformEntityReferenceItem::getEntityWebformFieldName($node); just gets the webform on the webform node and then grabs its 'target_id' value.

$webform_field_name = WebformEntityReferenceItem::getEntityWebformFieldName($node);
$webform_id = $node->$webform_field_name->target_id;

What I posted in my edit, I do not believe is the correct solution, albeit it is now working. Any suggestions would be appreciated.

The WebformEntityReferenceItem::getEntityWebformFieldName() static method was not removed but it was refactored and moved to the 'webform.entity_reference_manager'service.

Here is an example of showing how to use the service.

/** @var \Drupal\webform\WebformEntityReferenceManagerInterface $entity_reference_manager */
$entity_reference_manager = \Drupal::service('webform.entity_reference_manager');
$field_name = $entity_reference_manager->getFieldName($node);
...

@see \Drupal\webform\WebformEntityReferenceManager

@see \Drupal\webform\WebformEntityReferenceManagerInterface


Add content to drupalgap drop down I have recently started working with D7. I made a test page and installed drupal gap to run it with mobile-application. I wants to assigned more nodes to the drop down menu under contents, taxonomy and users but I don't know how get this. I have added a screen shot to make it more clear.

This is the Main Menu section as I see.

You need to made changes "settings.js" file present inside mobile-application\app folder.

Example:

// Main Menu
drupalgap.settings.menus['main_menu'] = {
  options: menu_popup_get_default_options(),
  links: [
    /*
    {
      title:'Content',
      path:'node',
      options:{
        attributes: {
          'data-icon': 'star',
          'class': 'ui-btn ui-btn-icon-right'
        }
      }
    },
    {
      title:'Taxonomy',
      path:'taxonomy/vocabularies',
      options:{
        attributes:{
          'data-icon':'grid'
        }
      }
    },
    {
      title:'Users',
      path:'user-listing',
      options:{
        attributes:{
          'data-icon':'info'
        }
      }
    }
    */
    {
      title:'Home',
      path:'home',
      options:{
        attributes: {
          'data-icon': 'home',
          'class': 'ui-btn ui-btn-icon-right'
        }
      }
    },
    {
      title:'Services',
      path:'websolution',
      options:{
        attributes:{
          'data-icon':'star'
        }
      }
    },
    {
      title:'Our Work',
      path:'ourwork',
      options:{
        attributes:{
          'data-icon':'star'
        }
      }
    },
    {
      title:'About Us',
      path:'articles',
      options:{
        attributes:{
          'data-icon':'star'
        }
      }
    },
    {
      title:'Testimonials',
      path:'testimonial',
      options:{
        attributes:{
          'data-icon':'star'
        }
      }
    },
    {
      title:'Contact',
      path:'node/58',
      options:{
        attributes:{
          'data-icon':'action'
        }
      }
    }

  ]
};

You will get details http://docs.drupalgap.org/7/Menus


How do I enable private messages for normal users, and not just administrators? Only Administrators can see the "Messages" link when logged in. Non-administrator users cannot. What can I do to alleviate this?

I've tested by looking at the site when logged in as Bobby, who is normally non-administrator user. No "Messages" link. However, if Bobby is ticked off as an administrator and I log back in as Bobby, I can see the "Messages" link between "My Account" and "Log out" in the upper right corner of the screen. I even get a notification that I have "1 new message".

I've looked through the Private Messages module configuration and can't seem to find setting that corresponds to what I'm experiencing.

I'm using Drupal 7.22 and Privatemsg 7.x-1.4.

The Private Message module is enabled, and all users have a tick in their "Enable private messages " setting.

You need to set up permissions to use Privatemsg.

Go to example.org/admin/people/permissions (Home > Administration > People, Permissions tab) and check privatmsg boxes for Authenticated User role.

It might be also convenient to create "Messenger" role with these permissions, and grant it to all users by default. That way, you will be able to ban someone from messaging by simply taking role away from him.


What is the proper function for multi dimensional localized menu? What is the proper function to get multi dimensional localized menu in Drupal 7?
after searching, I found i18n_menu_localize_tree(), but I didn't get it as tree menu.
Should I use i18n_menu_translated_tree(), or did I miss something?

menu_tree($menu_name) Seems to do that. It runs the items through  _menu_item_localize.

It works if your menu is translatable. In my setup menu items were not assigned to language, but translated with 18n_menu from site default language.

This atleast gets translated menu. Localized menu might imply also to version where certain items are only shown with specific language active(in that case this answer migth not work).


How can I notify an admin when a user is contacted? On my Drupal 7 site, I have a user contact form.  How can I alter the form so that an admin is notified when the form is submitted?

In a custom module

hook_form_alter() yourForm.

Add custom submit handler, it will run alongside with your defaut submit

$form['#submit'][] = 'yourSubmitFunction';

Inside your custom submit handler use drupal_mail() or any other result you need

function yourSubmitFunction($form, &$form_state) {
  drupal_mail()
  ....
}

Note: the form_state array contains all the submited values.


Tera Wurfl for Drupal Has anybody added or know how to add tera wurfl to their drupal 7 site? I have tried to implement it on my test site with no success. For those of you who don't know, it is a mobile detection program. I'm also open to a good alternative. Doesn't seem like there is too much info on this topic in the forum. Any help would be great. Thanks

WURFL underwent licensing changes a little while back, and I stopped using it.

I either use Mobile Tools if I need all of the features it provides (mainly Panels integration) or I use get_browser directly (make sure you have a recent browscap.ini).

I don't think Mobile Tools has a stable Drupal 7 release, though.

There is also the Drupal Browscap module, which purports to be better than the native version, though, I just manually keep my browscap.ini up-to-date.


Why do I get a notice after migrating the site to a new server? I am getting this error after migrating the site to a new server:

  Notice: unserialize() [function.unserialize]: Error at offset 2 of 23 bytes in includes/bootstrap.inc on line 478

I'm sure somewhere a setting has been corrupted; however, the site does appear to be functioning correctly. This error does return inconsistently, for anonymous users, so I do need to take care of it.
The error does not occur on the old server.

I have full control of the server, both the new and the old are Amazon EC2 VMs. The only major difference in the infrastructure is that the old server used a MySQL DB in the same VM, while the new server is using a MySQL Server in RBS.

I've read somewhere that this issue could be caused by the SQL export/import process, and something regarding UTF8. I wasn't able to garner anything I could mold into instructions to follow, but I have a feeling that's a path I need to take; I'm not really sure where to start.

The problem might be the error handling settings have changed on the new server. You probably have a corrupt variable in the variable table that can't be unsterilized. Try using the variable check module.


Dynamic view per taxonomy term I'm really stuck on a problem that I'm seeking assistance on. I currently have 3 content-types (Article, Photo and Video) and all of them use the same Taxonomy Vocab I've called Category. I've configured the PathAuto module:

for Category terms: [term:name] --> CCK Field created and shared across content-types called: field_category
for Articles: [node:field_category]/articles/[node:title]
for Photos: [node:field_category]/photos/[node:title]
for Videos: [node:field_category]/videos/[node:title]

The problem I'm experiencing is having to create a dynamic View page for each term. Basically, if from the root I navigate to a particular category (eg: /politics), I expect to see a page with all content under that term, plus allow me to then filter by content-type.

Similarly, if I navigate to articles under a particular category (eg: /politics/photos), I expect to see a page showing me all photos under that category.

I don't know if I've chosen a very elaborate (and unnecessary!) organisation of content, but this makes sense to me. I'm probably going to kick myself, for I feel that there is a simple solution to this! This is my first time using Views-3 UI, having only minor experience with Views-2 in D6. I'm currently using Views 7x-3.5.

I thank you much in advance for any assistance you can provide!

EDIT: I'm going through whatever online documentation I can find for Views-3, and so far it's quite overwhelming. I do know that I need to use contextual filters and view page paths with %.

Okay, I have figured out a solution, although its a bit crude. Before I continue, I should mention that my aim was to also to create hackable URLs.

Installed the Taxonomy_Display module. Created a Content View, and immediately added a contextual filter Content: Has taxonomy term ID with the following configuration:

WHEN THE FILTER VALUE IS NOT IN THE URL:

Provide default value
    --> Type = Taxonomy term ID from URL
    --> Load default filter from node page, that's good for related taxonomy blocks
    --> Vocabularies = Category

WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED

Specify validation criteria
    --> Validator = Taxonomy Term
    --> Vocabularies = Category
    --> Filter value type = Term Name converted to term ID (got this from the Taxonomy_Display module)
    --> Transform dashes in URL to spaces in term name filter values = Checked
    --> Action to take if filter value does not validate = Show "page not Found"

I then added a relationship: 'Content: Taxonomy terms on nodeon my vocabulary, to give me access to the Taxonomy filters, and added a field filter onTerm = Category` through the relationship created.

Finally, I cloned 3 pages based off the above config, with a page path to categories\%\articles, categories\%\photos, and categories\%\videos, and on each of these added a further filter by the respective content-type.

Well, it does what I want it to, but it somehow still doesn't strike me as an ideal solution ... I think it could be simpler, whilst also allowing for dynamically identifying the content-type from the URL. Therefore, I won't mark this yet as the answer, until someone can critique my approach. :)


How to set checkbox if validation fails? I am creating a form which has checkbox, and options for checkbox are coming dynamically. In submit function I am rebuilding form if validation fails. all values are rendering but previously checked checkbox is not checking.

below is the code:

function modulename_form(){
      $header = array();
      $rows = array();
      $conditions = '';
      $orderby = array( 'pass_lname' => 'ASC');
      $unmapped_data = capcup_get_unmapped_passengers_data($conditions , $orderby);

      foreach ($unmapped_data as $key => $value) {
        $user = user_load($value->pass_uid);
        $insertion = !empty($value->pass_insertion)? $value->pass_insertion . ' ': '';
        if (empty($buttons)) {
          $row['name'] = 'mail . '">' . check_plain($value->pass_lname . ' ' . $insertion . $value->pass_fname) . '';
        }
        else {
          $row['name'] = 'passenger_uid . '">' . check_plain($value->passenger_lname . ' ' . $insertion . $value->passenger_fname) . '';
        }
        $row['phone'] = $value->pass_tel;
        $row['practicecode'] = $value->pass_practcode;
          $form['active'] =  array(
          '#type' => 'checkbox',
          '#return_value' => $value->pass_uid,
          '#attributes' => array(
              'name' => array('nodes[' . $value->pass_uid . ']'),
            )
          );
          $row['active'] =  drupal_render($form['active']);
        $rows[$value->pass_uid] = $row;
      }

      $form['nodes'] = array(
        '#theme' => 'table',
        '#header' => $header,
        '#rows' => $rows,
        '#empty' => t('No passenger available.'),
      );
return $form;
}

submit function:

function modulename_submit($form, $form_state) {
  if (in_array('boat', $account->roles)) {
      $form_state['rebuild'] = TRUE;
      form_set_error('boat_user_info][emailaddress', 'Dit e-mailadres is al in gebruik.');
      return FALSE;
    }
}

I am writing form function like above because to get structure like below image:

When form will rebuilt all fields will remembered there previous value but checkbox is not remembered its value. I tried by adding default_value and all but not worked. Please suggest me how can I achieve that.

All form validations should be done in form validate function and not in submit function. Read this article

Hope it helps. :)


In views how to merge two columns? I am using Views to display submitted contents as table and I need to merge two columns ("Uploaded covering letter" and "Uploaded e-book") into one.

How can I achieve this?

You first need to add one more field in your view i.e Global Custom Text.

After that you need to merge your two fields result in this field output using Replacement patterns

As in attached screenshot, I am merging nid and first name field in global custom text field output.

You also need to exclude "Uploaded covering letter" and "Uploaded e-book" field from output using Exclude from display attribute. You need to checked this check box for both the fields.


Explicitly passing argument to local action for access check I'm using the group module, and in a custom module I'm trying to create a local task that will bring you directly to the create page for a particular group content type. My goal is to skip the create page where you select the content type.

I've defined a local task:

entity.group_content.create_form:
  route_name: entity.group_content.create_form
  title: 'Add new service'
  defaults:
    plugin_id: group_node:service
  appears_on:
    - 'view.group_services.page_1'

It doesn't complain about passing the $group for the access check, which I'm assuming is being successfully passed due to query magic. Where it breaks down is on $plugin_id on the access check with the error.

  RuntimeException: Callable "Drupal\group\Access\GroupContentCreateEntityAccessCheck::access" requires a value for the "$plugin_id" argument. in Drupal\Component\Utility\ArgumentsResolver->handleUnresolvedArgument() (line 142 of core/lib/Drupal/Component/Utility/ArgumentsResolver.php).

As an example, the route I'm trying to provide would end up being:

/group/{group}/content/create/{plugin_id}

aka

/group/1/content/create/group_node%3Aservice

What am I missing here?

Answered my own question. The key is that we are working with route parameters,  not route options which are akin to l() in Drupal 7.

This article goes into more detail. Here is the important part:

# yaml file to define one or more local task(s).
#
# Definitions can contain any of the following:
# title: (required) The untranslated title of the menu link.
# description: The untranslated description of the link.
# route_name: (optional) The route name to be used to build the path. Either a
#   route_name or a link_path must be provided.
# base_route: Used to group together related tabs.
# parent_id: Use the parent_id to relate a tab to a parent tab for multiple
#   levels of tabs.
# route_parameters: (optional) The route parameters to build the path. An array.
# link_path: (optional) If you have an external link use link_path instead of
#   providing a route_name.
# weight: (optional) An integer that determines the relative position of items
#   in the menu; higher-weighted items sink. Defaults to 0.
#   Menu items with the same weight are ordered alphabetically.
# options: (optional) An array of options to be passed to l() when generating
#   a link from this menu item.

So my action routing file is updated:

entity.group_content.create_form:
  route_name: entity.group_content.create_form
  title: 'Add new service'
  route_parameters:
    plugin_id: group_node:service
#  defaults:
#    plugin_id: group_node:service
  appears_on:
    - 'view.group_services.page_1'

Flush caches.


Turn text or link field in image Users can enter links in separate fields that lead to their facebook, youtube pages.

On output i would like to use images for those fields instead of showing ugly links.

Is there a module to acomplish this ?

The best way to implement this is to implement a custom display formatter for the link field. You can either do it directly in a custom module by implementing hook_field_formatter_info.

Or without try out Custom Formatters module if you want to avoid custom code:

  The Custom Formatters module allows users to easily create custom Field Formatters without the need to write a custom module. Custom Formatters can then be exported as CTools Exportables, Features or Drupal API Field Formatters.


REST request through Actions and Triggers In Drupal, I can define a Advanced Action in Administration>Actions , but the available options do not have a Send REST request option, how do I achieve what I want?

In my case, I want my remote service to know about a new node is being created, so I need to send the nid to my service.

I've thought of one dirty hack though, which is to use Redirect to URL and send my request through URL:

My server will receive the data it needs(which is the nid), and redirect the user back to their content using [node:id].

But like I said, this is more of a hack, is there a proper way of doing this?

I think the Rules HTTP Client module will suit you:

  This module adds an action wrapping of drupal_http_request to use
  Rules for making http requests. It has many general uses, because the
  Hypertext Transfer Protocol is the foundation of web data
  communication.


How can I store the user agent string and referrer for Webform 4.x submissions? In Webform 3.x, I have a "Give me feedback" webform that I embed in various places throughout my site using Panels.  This form contains two hidden fields:

Referer / Default value: %server[HTTP_REFERER]

User agent / Default value: %server[HTTP_USER_AGENT]

This is extremely helpful because I can get the details of users' machines without having to ask them as well as get the page the user came from (because the webform is embedded on a number of pages throughout my site with Panels).  However, %server\[\] tokens apparently no longer work in Webform 4.x:

  Most tokens will be upgraded for you, however some tokens do not have
  equivalents and no longer work. These include %post, %request,
  %cookie, and %session. The %get token (which maps to PHP's $_GET
  variable) has the equivalent token [current-page:query:key].

Is there an alternate way to somehow include the user agent string and referer in a 4.x webform?

This issue is Closed (won't fix) on Drupal.org

If you want them back, you basically need to create a module that implements hook_tokens() and hook_token_info(), as described in the API. I don't think anyone did it already.

Here is how I'd do it:

function yourmodule_token_info() {
  $type = array(
    'name' => t('Server'),
    'description' => t('Tokens related to $_SERVER superglobal.'),
  );
  $tokens = array();
  foreach($_SERVER as $key => $val) { //discard $val now
    $tokens[$key] = array(
      'name' => $key,
      'description' => "\$_SERVER['$key']",
    );
  }
  return array(
    'types' => array('server' => $type),
    'tokens' => array('server' => $tokens),
  );
}

function yourmodule_tokens($type, $tokens, array $data = array(), array $options = array()) {
  if($type == 'server') {
    $replacements = array();
    foreach ($tokens as $name => $original) {
        $replacements[$original] = (string)$_SERVER[$name];
    }
    return $replacements;
  }
}

Of course code above is not production ready, it ignores proper type handling, security issues and so on. It's meant to set you on the right track, but you need to apply your own sanity before deploying it. I take no responsibility for abuse. Read about the reasons it was removed in the first place before you decide to add it back, and be careful to restore only what you really need.


Working with views, better use various displays or create more views? The main task is:

Create a couple of pages with terms of a specific list of taxonomy vocabulary. (Its about 20+ pages).

So, its simple, create a view with a particular route, and set to display taxonomy terms, set the right vocabulary to display, set exposed filters and so on.

Now comes the question, speaking in perfomance, its better create a view to each page (with almost the same config, only vocabulary terms is different), or create just one view and create a display for each page?

Both scenarios work's great, using just one view for all pages and using a view for each page, but which one can be the best alternative for this case?

Looking in Working with Views in Drupal 8, there is nothing about perfomance and best practice. Any advice are welcome.

In the book "Mastering Drupal 8 Views" Greg Marshall suggests that there is no strong reason to prefer one or the other. He suggests using separate views most of the time, for the simple reason that it's very easy to make a mistake in the UI and apply a change to all displays when that wasn't what you wanted.

I would suggest that you think carefully about in what circumstances you are going to want to modify a view. If changes are likely to affect all displays, or be only applicable to one display of a certain type, then having a single view is fine.

If changes would likely be to multiple characteristics that could apply to all displays but you would want to be different on each display, then isolating them as separate views reduces the risk of getting in a mess.


List organic group members from the current user group on his profile page I am new to organic groups, I ran into a problem, I am a member of some organic group, I need to list other members of same group on my profile page, Trying to display it using views but no luck :(,  I am working on drupal 7 with Organic group 7.x-2.9

I forgot to answer you last time.! Sorry. You said your were happy with some code so here it is.

Step 1: The custom module.

function CUSTOM_MODULE_views_pre_view(&$view, &$display_id, &$args){
// Select our view
    if($view->name == 'VIEW_NAME' and $display_id == 'DISPLAY_NAME') {
    // Get User ID from url
        $view_user = user_load(arg(1));
        $user_groups = array();
        // Get Group IDs
            $items = field_get_items('user', $view_user, 'og_user_node');
                foreach($items as $item) {
                    $user_groups[] = $item['target_id'];
                 }
    // Join like 4+78+345 for Views
        $user_groups_args = implode("+", $user_groups);
    // Send IDs to view
        $args[0] = $user_groups_args;
    }
}

Create a module and change what's in caps. Be aware that that module doesn't do any checking.. Only use it for user/* or node/* etc. where the second argument is an integer.

Step 2: The View

In your View, add the OG membership: Group ID contextual filter
(make sure it's first in the list).
Under its settings under More, check Allow multiple values.
Because some users may be in more than one group, go to Query settings under Other and check Distinct.

That should be it.


Drupal 7 is ready for big sites? I know to right now Drupal 7 is stable since almost a year but the truth is Drupal needs third party modules for satisfy the requirements of almost any site

Yesterday i tried jump to drupal 7 but the first thing to i see is to many of modules are betas, releases candidates and a lot  haven't a version for D7.

and many of this modules are essentials, modules like Ctools, panels,  references,  context, all of these modules are pretty useful and none of them have a stable version for drupal 7

So my question is,  Drupal 7 is  ready for a bigger site than a blog?  how many of you use drupal 7 with unstable modules for a client's sites?

How risky is use non stable modules in drupal 7?

Q: "How risky is use non stable modules in Drupal 7?"
A: "Depends."

Without wanting to be obtuse, in late 2011 this is a question only you can answer, based on your abilities, needs and experience.
The simple answer is: Betas are usually fine, Alphas should usually be avoided, RCs are almost certainly OK.
If you're happy to hit a bug and help fix it or apply patches, you'll be mostly fine and able to really help the Drupal community. If not, the risk for you is higher and could become a show-stopper.
If you're using one of the 'biggies' with tens of thousands of users (CTools, Panels, Views etc) you can probably use alphas/betas without hitting many major issues -- or you'll be one of thousands with the same problem which means it'll get fixed quicker... But if you're using less common (but still complex) modules, or it's critical you have complete reliability in your site, then you'll need to think twice - and maybe stick with D6 for a while.
A safer approach if you're worried and don't have the expertise to get your hands dirty in code or patches is probably: use Drupal 6 but choose your modules carefully so there's always a D7 upgrade path. Upgrade when you're happy it's right for you.
Ultimately you might have to use Drupal 7 because it provides certain features you cannot get in D6.
To close I would say that, for the most part, Drupal 7 and its ecosystem of modules is ready for most people/sites/projects. But things are changing by the day, so if you don't feel comfortable now you might in do a month or two.
Do your research and if you have doubts or hit snags, Drupal 6 is generally still an excellent choice and will be for many more months.
Good luck!


I am getting an error "Notice: Undefined index: distribution_name in drupal_install_profile_distribution_name() ". How do I fix this? I am using Drupal 7.69. I log in and go to my modules page and get the following error:

  Notice: Undefined index: distribution_name in drupal_install_profile_distribution_name() (line 207 of /var/www/html/includes/install.inc).

According to this page: https://www.drupal.org/project/drupal/issues/1170362, you're supposed to run the following update SQL statement to set the correct status: UPDATE system SET status=1 WHERE name='standard';

My problem is in my system table I don't have any record with name equal to "standard". How do I add it?

After seeing the results of drupal_get_profile() and querying for that value in the system table, the result of the query showed that the profile's files were (supposed to be) in:

/var/www/html/profiles/[profile name]/

However, that folder path did not exist. Since Drupal could not find the profile's files in that folder path, it could not set a distribution_name.

I found the correct profile files in my original download from way back in the day, re-uploaded them to the correct directory on my server and cleared the cache. The message disappeared.


How to change template file name and destination for some blocks? For example: I want to change default login block template.

My current template file is — /sites/all/themes/{theme_name}/templates/block--user--login.tpl.php

But I want — /sites/all/themes/{theme_name}/templates/system_blocks/login-block.tpl.php

How can I do that?

Check out template_preprocess_block. You can do this with the following code in your theme's template.php file:

function MYTHEME_preprocess_block(&$variables) {
  // Perform a check based on any parameter, e.g. block ID.
  if ($variables['block_html_id'] == 'block-system-main') {
    // This will lookup for block--system-main-block.tpl.php file in your
    // theme.
    $variables['theme_hook_suggestions'] = 'block__system_main_block';
  }
}

However, Drupal already looks for various template names, before it settles down for the default block.tpl.php. Here is the list:

block--block--[block-id].tpl.php
block--[module]--[delta].tpl.php
block--[module].tpl.php
block--[region].tpl.php
block.tpl.php

See this page for more information.


Separate page for payment methods selection in drupal commerce is there a way to have a separate page for payment method selection, to allow clients to select the payment method they want to use instead of the current way drupal commerce use (integrating payment selection in the review order page)?

Thanks in advance for your support.

Sure! You can use a module like Commerce Checkout Pages to create a new page via the UI or you could implement hook_commerce_checkout_page_info() in your module and create a new page. Then just move your Payment pane onto your new page and you'll be all set:

/**
 * Implements hook_commerce_checkout_page_info().
 */
function MYMODULE_commerce_checkout_page_info() {
  $checkout_pages = array();

  $checkout_pages['payment'] = array(
    'name' => t('Payment'),
    'title' => t('Payment'),
    'weight' => 3,
  );

  return $checkout_pages;
}

Then, implement hook_commerce_checkout_pane_info_alter() to add your payment pane to your new page:

/**
 * Implements hook_commerce_checkout_pane_info_alter().
 */
function MYMODULE_commerce_checkout_pane_info_alter(&$checkout_panes) {
  // Payment selection on the new 'payment' page.
  $checkout_panes['commerce_payment']['page'] = 'payment';
}


Change site logo for different languages I do believe that should be popular issue but I can't find any questions here about this: is there any way to make site's logo different for different languages? I've found some threads regarding this thing in drupal.org forums, but these solutions are not working for me...

p.s. I am using D7 and currently working on Fusion subtheme Acquia Marina (if it helps)

The Internationalization module, after installing and enabling the modules, you can activate it at admin/config/regional/i18n/variable, look for 'theme settings'


How to delete a path when uninstall a module? this is for Drupal 8:

in my hook_install function, i have following code:

MenuLinkContent::create([
        'title' => 'Location',
        'link' => ['uri' => 'route:locator.filters'],
        'menu_name' => 'main',
    ])->save();

when I have uninstalled my module, how do remove above defined link?

You can use hook_uninstall and MenuLinkManager::removeDefinition

  Removes a single link definition from the menu tree storage. This is
  used for plugins not found through discovery to remove definitions.


Generate a cookie when user closes a webform block I have been tasked with having to setup a cookie that records when an anonymous user closes a newsletter signup webform block so that it no longer appears when reloading the current page or navigating to another page on a website.

Can anyone please advise if there is module that performs this function?

Or can someone please point me in the right direction in terms of the correct code snippet I can use to make this work?

Many thanks!

First you need to create a custom module and add javascript user identificator on your page with web form(to find out user anonymous or not)
Here is example

Next use jquery library and do the next thing:

// its just an example you need to put your #id or .class
$("#subform_close").on('click', function() {
      if(Drupal.settings.user_js_uid == 0)
           {
              // set cookie for whatever you want
              $.cookie("dont_show_web_form", 1, { expires : 1 });
          }
})

and in your php code
check for that cookie

$_COOKIE["dont_show_web_form"]

and hide your webform.


Drupal 7 Site: Targeted for spam Okay, I'm not sure if this question should be here, but it's more of a general question. So I'm hoping if anyone can relate to this, perhaps you can suggest something to get around this. So I worked on this particular site. Using drupal 7. It's a kind of article site and content is about anything out there, nothing specific, it's more on the fun side. Since we've allowed sign ups, we've been getting a lot of sign ups of users, but most of them seem to be a group of spammers or trolls. No matter how much I try to contain it, they just keep coming and sign up. I have enabled captcha to prevent bot signups, as well as on the commenting sections so we don't get tons of spam more than we can handle. I also enabled sign up approval so I could see who signed up, and for sure everyone of them have tell tale signs of spammers. Imagine usernames that don't make sense. Randomly generated or whatever. Should we ban the ips, or the email domain names? No room for just one question, it may be all general but it concerns the whole site in itself. Not sure what the work around is, but I sure appreciate any suggestions from those who got around this. Thanks. Cheers.

One module you can make use of in this situation is the honeypot module. The Honeypot method basically inserts a hidden form field to Drupal (or other). End users don't see the field, so they don't fill it out. But spam bots (usually using prewritten scripts) do see the field, and always fill it. The Honeypot module detects this and blocks the form submission if there's something in the field.

EXTRA OPTIONS YOU COULD ADD

Another Simple thing you can do according to this site is hooking into the Drupal user registration process and using a php snippet like this:

flood_register_event('reg');
if (!flood_is_allowed('reg', 4)) {
header ('HTTP/1.1 403 Forbidden');
die();
}

Using the flood_register_event() method to register a possible flood event. The method records every registration when used in this context. Next, using the flood_is_allowed() check if the current user has triggered the flood register event more than 4 or XX times. If the user has tried to access the form 4 times they get another lovely 403 and all output is killed. You could use this logic either when rendering the Drupal registration page or upon every new submission.


Problem changing the parent group for a node I am trying to programmatically update the parent group of a bunch of nodes. But I am not having much luck. Below is what I have tried. What am I doing wrong here?

foreach ($groups AS $group)
{
  $node = node_load($group->nid);
  $node->og_parent = 23; //I also tried "$node->og_parent = array('nid' => 23);"
  node_save($node);
  unset($node);
}

One thing to note is that all of these groups already have a parent group set. Also this is on Drupal 6.

Thanks!

Ok, I figured this out. Here is what I had to do.

I had to address this slightly differently. I just had to change $node->og_parent = 23; to $node->og_parent->nid = 23;.

I just had to address the specific node id and that fixed it.


Drupal 7 computed field value in view I'm really stuck displaying content type's computed field in view. Computed field value calculated properly and stored in database (value is a generated HTML code), but in view I get HTML just printed out as text. Looking through the page source code I found that HTML tags are encoded and looks like that &lt;a href=&quot;LINK_HERE&quot;&gt; So I'm wondering how to display custom field's HTML in view (seems to me that was a some custom module for this purpose?)?

In Views, try this:

add the field as normal, exclude from display
create a new field, Global:Custom Text
add the field name as a Replacement Pattern

It's likely that for security reasons it is psuedo-sanitizing the html. Global: Custom Text should display it as is, but I haven't tried it under these circumstances, so it may not.


Ubercart - Sale approval required before payment Durpal  6, Ubertcart 6.x-2

We are selling table space to vendors at an upcoming convention. We want to let them apply but wait for admin approval before they can pay. I've been searching for several days but cannot find a solution.

Is there a way to require admin approval of a sale before moving to the payment process?

Edit: I have no way of telling that they are vendors until they purchase a vendor table.

There's many ways to go about this but I would use Rules & custom Role called Vendor. You can specify on Drupal load if a user doesn't have a Vendor role & is loading the cart/checkout page. That you can redirect them to your application form with a message prompting them to apply before checkout.

Here's an example rule:

{ "rules_check_vendor" : {
    "LABEL" : "Check Vendor",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "test" ],
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "cart\/checkout",
          "operation" : "starts"
        }
      },
      { "NOT user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "3" : "3" } }
        }
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "In order to become a vendor. Please contact us." } },
      { "redirect" : { "url" : "contact" } }
    ]
  }
}


Why doesn't my date get rendered? In Drupal 8, I have a Flag entity with a date field attached.
My code looks like this:
function MYMODULE_flagging_presave(FlaggingInterface $flagging) {
    if ($score == 0 || $score == 1) {
      $flagging->field_date_review = date("Y-m-d", strtotime('today'));
    }
    else {
      $date = date("Y-m-d", strtotime("+$interval days"));
      $flagging->field_date_review = $date;
    }

I checked and the dates get stored in the database like 2020-07-02.
I have a custom view that shows these flaggings, and I added a filter for nodes with a date field value of less than +1 days; this behaves as expected, so the Views module seems to understand the dates as I stored them.
But, when I try to add the date field, I get an empty display in Views.
Further debugging
When I render the flagging entity, the date field doesn't show a value, either.
Other fields set in ``hook_flagging_presave()` are displayed correctly; it's only the date field that doesn't have a value.
Configuration
On the flagging entity's Manage display screen, I have set my date field to use the Plain format with no timezone offset. I also tried the Default format and several others, but nothing let me display the value.
There are no errors in the recent log messages.
To sum up: the date field has data in the database, which Views can see and use for filters.  But, this date field cannot be displayed in Views or on the rendered flagging entity.
What do I need to do to get the date to be displayed?

I found it-- the Date field can store dates or datetimes, and you have to change your code for each case.
When you add a Date field to an entity, you can choose Date (date) or Date and time (datetime) as the Date type.
More information in this blog post, but the basic idea is:
$node->set('field_date', date('Y-m-d', time()));
$node->set('field_datetime', date('Y-m-d\TH:i:s', time()));


How can I set a node reference programmatically? I'm trying to write a custom PHP action in Rules module.  Each time after creation of a certain type of content, it should create an additional node with a reference to the created node.( Field by Node reference module )

I've tried to pass the values of nid and/or title of the main node to this field using tokens and it didn't work.

If the field is a text field it passes the variables correctly.

What value should be passed to the node reference field to set it in code?

First, I"ll answer your question, then suggest another way.

Assuming that this is a monolingual site, use

$additional_node->field_created_node[LANGUAGE_NONE][0]['nid'] = $created_node->nid;

However, Rules already has actions that can change values on a node, and when you create a node using Rules, it creates a new variable containing the created node. If I were you, I'd just add actions that use that data and not write custom PHP code to do it. I just created one to assign populate a user reference field on a created node (within the same rule) the other day, and it worked fine.


How to add extra fields to user profile? I'd like to add additional fields to the user profile. I'd like user to be able to edit almost all the information I store in the database about him.
I have some ideas: maybe it's possible to do using form api.

I found the page hard to find, but at /admin/config/people/accounts/fields you can add fields to users.


Progress Bar to prevent repeated WebForm Submissions? I'm getting duplicate webform submissions from what I call "Happy Clickers". I would like to implement a progress bar when someone submits a webform to prevent them from clicking multiple times. I tried the pgbar module, but it's not the solution that I am looking for.

Can anyone recommend a Drupal module to accomplish this? I'm using Drupal 7.

Thanks-in-Advance,

John

If you just want to limit Happy Clickers, in the webform go to Form settings and there are options for Total submissions limit & Per user submission limit. I would suggest changing the Per user submission limit to once every minute.


Two modules trying to extend NodeForm I have two modules that both extend NodeForm the usual way:

function MY_MODULE_entity_type_alter(array &$entity_info) {
  $entity_info['node']->setFormClass('default', 'Drupal\MY_MODULE\Form\MyModuleNodeForm');
  $entity_info['node']->setFormClass('edit', 'Drupal\MY_MODULE\Form\MyModuleNodeForm');
}

As far as I can tell (both from actually looking into what setFormClass() does and simply trying out) this is a race condition that only one of them can win. Although they both want to deal with different content types and what they do would not conflict at all, they can't coexist. With the old, 7-style alter and submit functions, this could be solved but what would be the proper 8-ish way to do it? Both modules are mine, I can combine them if necessary but that wouldn't be really elegant.

You have two options. Either go back to using _form_alter() hooks to handle it, or you can extend twice:

module 1 node for extends module 2 node form which extends node form. Then make sure to call the parent::validateForm and parent::submitForm from your validate and submit handlers.


Concatenate and minify css with Gulp still necessary? I'm using Gulp as part of my theming workflow and was wondering if it was necessary to add the concatenate and minify tasks into Gulp if Drupal already does that when I check the option under Performance.

No, it's not necessary, unless you decide there's an appreciable performance benefit by using the gulp method as well (possible but unlikely).

You'll just be minifying twice otherwise, wasted CPU cycles.


how rename series legend in chart created by views I created a chart page by using Views. But the legend is always Series 1, Series 2. Not using the label data.

I tried to find the option to replace the label "Series" with the label from the data, but I could not find it.
Anyone can help me how to use the label of the data instead of "Series"

Finally I can find the answer, after keep on trying:
I have to switch to custom label. Just change to custom label in the field.


How do I detect spam from among published comments? My spam prevention modules had to be disabled while I was fixing a problem. Meanwhile, I was attacked by numerous spam bots and now have thousands of published spam comments on my site.

Is there a way to detect these comments and unpublish and/or delete them?

I am using drupal 7.

I use a view, that shows me 200 comments at once with their body. So by quickly looking at the list of the comments, I can see which are span and checkmark them to delete.

You can copy this view from the gist here: https://gist.github.com/timonweb/5990901

Make sure you have Views Bulk Operations (https://drupal.org/project/views_bulk_operations) module installed, then import the view from the gist and go to: http://yoursite.com/admin/content/comment/moderate.


No Drupal Site Found when clearing cache I installed drush using composer following the instructions here: http://docs.drush.org/en/master/install/

When trying to run drush cc all I get this error:

  No Drupal site found, only 'drush' cache was cleared.[warning] 'all'
  cache was cleared. [success]

I added this line:

export PATH="/Applications/MAMP/bin/php/php5.6.2/bin:$PATH"

to my .bash_profile and restarted bash and MAMP. Still no luck. Any ideas?

This is my drush status:

 Drupal version         :  7.36
 Site URI               :  http://default
 Database driver        :  mysql
 Database hostname      :  localhost
 Database port          :
 Database username      :  root
 Database name          :  srod
 PHP executable         :  /usr/bin/php
 PHP configuration      :
 PHP OS                 :  Darwin
 Drush script           :  /Users/srod/.composer/vendor/drush/drush/drush.php
 Drush version          :  7.0-dev
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /Applications/MAMP/htdocs/srodsite
 Site path              :  sites/default

I'm running it from Drupal project folder.

I figured out that you will need a mysql server installed and included in path, even if you are using mysql from AWS RDS.


Use Condition in Computed Field with Field Collections I have an entity with a field colleciton (fc_details), and in that field collection I have fields amount(field_amount) and Type (field_type)

There are several examples to sum up field colleciton values in computed field like:

$sum = 0;
$wrapper = entity_metadata_wrapper($entity_type, $entity);
  foreach($wrapper->field_fc_details as $collection) {
    $sum += $collection->field_amount->value();
  }

$entity_field[0]['value'] = $sum;

But I want to sum up values, where field_type values = "Z".

I tried variations of "if($wrapper->field_type->value()='Z' " inside foreach, but then site gives 500 error.

Any ideas ? Thanks in advance.

Try the following and let me know how you go.

if($collection->field_type->value() == 'Z') {
  $sum += $collection->field_amount->value();
}


Drupal Yslow Performance Hello  I am using drupal 7  and yslow tool in ff.

it shows me grade B

Grade F on Make fewer HTTP requests

This page has 11 external Javascript scripts. Try combining them into one.
This page has 5 external stylesheets. Try combining them into one.

As i am not able to combine all javascript and  css files.

I also enabled cache . but i don't know how it work.

Grade F on Add Expires headers

There are 75 static components without a far-future expiration date.

i also made changes in .htacess file still not working .. Please let me know

Grade C on Put JavaScript at bottom

i am using iframe in my website . How to include javascript at bottom for this?

Anybody have idea please let me know.

Thanks

for Grade F on Make fewer HTTP requests

Locate them at admin > configuration > development > performance. There you'll see two options:

Aggregate and compress css files.
Aggregate Javascript files


Problem with admin_menu and Varnish I'm a beginner with configuring varnish, so my apologies if this is a stupid question. I am trying to make things work on my ubuntu VM (12.04) with Varnish 3.

I am facing a problem, where after I log in, the admin menu (created by admin_menu) just disappears. Looking at the ajax request, it seems that varnish sends the request to drupal, receives a valid answer and then just refuses to serve it. It just outputs a 503 error instead.

I have captured the varnish logs, but I'm not sure what to make of them. Anyone has any ideas?

    11 ReqStart     c 192.168.1.20 50807 2144510792
   11 RxRequest    c GET
   11 RxURL        c /js/admin_menu/cache/a4270b058219f623d092552467a5cde0
   11 RxProtocol   c HTTP/1.1
   11 RxHeader     c Host: www.giftmonkey.ubuntu
   11 RxHeader     c User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:24.0) Gecko/20100101 Firefox/24.0
   11 RxHeader     c Accept: text/plain, */*; q=0.01
   11 RxHeader     c Accept-Language: en-US,en;q=0.5
   11 RxHeader     c Accept-Encoding: gzip, deflate
   11 RxHeader     c X-Requested-With: XMLHttpRequest
   11 RxHeader     c Referer: http://www.giftmonkey.ubuntu/
   11 RxHeader     c Cookie: __utma=94903434.1646672653.1383344251.1383344251.1383390432.2; __utmz=94903434.1383344251.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); has_js=1; pmcwidth=1920; __utmc=94903434; SESS9433506a0f068ea0ad220f58b963eef8=6FfRyBpNYYBlufL7y6AoBa5eqBP
   11 RxHeader     c Connection: keep-alive
   11 VCL_call     c recv pass
   11 VCL_call     c hash
   11 Hash         c /js/admin_menu/cache/a4270b058219f623d092552467a5cde0
   11 Hash         c www.giftmonkey.ubuntu
   11 VCL_return   c hash
   11 VCL_call     c pass pass
   11 Backend      c 17 default default
   11 TTL          c 2144510792 RFC 31536000 -1 -1 1383409657 0 1383409657 0 31536000
   11 VCL_call     c fetch
   11 TTL          c 2144510792 VCL 120 -1 -1 1383409657 -0
   11 VCL_return   c hit_for_pass
   11 ObjProtocol  c HTTP/1.1
   11 ObjResponse  c OK
   11 ObjHeader    c Date: Sat, 02 Nov 2013 16:27:37 GMT
   11 ObjHeader    c Server: Apache/2.2.22 (Ubuntu)
   11 ObjHeader    c X-Powered-By: PHP/5.3.10-1ubuntu3.8
   11 ObjHeader    c Expires: Sun, 02 Nov 2014 11:17:03 +0000
   11 ObjHeader    c Last-Modified: Sat, 02 Nov 2013 11:17:04 +0000
   11 ObjHeader    c Cache-Control: private, max-age=31536000
   11 ObjHeader    c ETag: "1383391024-1"
   11 ObjHeader    c X-Drupal-Cache: HIT
   11 ObjHeader    c Content-Language: ro
   11 ObjHeader    c Vary: Cookie,Accept-Encoding
   11 ObjHeader    c Content-Encoding: gzip
   11 ObjHeader    c Content-Length: 6705
   11 ObjHeader    c Content-Type: text/html; charset=utf-8
   11 FetchError   c Junk after gzip data
   11 Gzip         c u F - 6611 59085 80 80 52818
   11 VCL_call     c error deliver
   11 VCL_call     c deliver deliver
   11 TxProtocol   c HTTP/1.1
   11 TxStatus     c 503
   11 TxResponse   c Service Unavailable
   11 TxHeader     c Server: Varnish
   11 TxHeader     c Content-Type: text/html; charset=utf-8
   11 TxHeader     c Retry-After: 5
   11 TxHeader     c Content-Length: 436
   11 TxHeader     c Accept-Ranges: bytes
   11 TxHeader     c Date: Sat, 02 Nov 2013 16:27:37 GMT
   11 TxHeader     c X-Varnish: 2144510792
   11 TxHeader     c Age: 0
   11 TxHeader     c Via: 1.1 varnish
   11 TxHeader     c Connection: close
   11 TxHeader     c X-Cache: MISS
   11 Length       c 436
   11 ReqEnd       c 2144510792 1383409657.339800358 1383409657.400331020 0.511597395 0.060457230 0.000073433
   11 SessionClose c error
   11 StatSess     c 192.168.1.20 50807 2 1 5 0 5 4 1760 6926

The error see to be on some cache file of drupal's admin_menu. The js aggregated file browser is requesting is being refused by Drupal by 503. You may get some pointers to this issue here https://groups.drupal.org/node/28604

Try clearing all the Drupal caches using "drush cc all" command. Are you using any js aggregation on Drupal side? Try changing to https://drupal.org/project/advagg?


Is the rules event "Before saving a user account" applied every time a user edits their account? I would like to apply a rule that allows existing users whose email addresses come from a certain domain to continue using their existing accounts, but to prevent the creation of future accounts from these domains.

I have configured my rule to react on the After saving a new user account event, but I'm unsure as to whether to have it react also on Before saving a user account.

Does saving here refer to only to account creation, or also to account updates such as a password change?

Before saving a user account will react before you make a change in the user account.

And After saving a new user account will react After you create the user account.

But if you have the 2 events once you create a new user account you will trigger first the Before saving a user account event and after the After saving a new user account event.

If you go to create or update a user account always you need to call the user_save() function. The difference is in the first param. See this question with an example:

Create a user programmatically and give they a role


Show content only if user is an owner of this content (node) How do I show a node "only if a user is an owner of the node" with Panels/Page Manager' Variants and its Visibility Rules (right icon on each content)?

If possible then create your own permission which should be visible under
**Variants » Basic » Selection rules ** section. For creating panel permission, check following steps:
1. Create folder structure like module -> plugins -> access -> filename.inc
2. Add following function and hooks under that file:

/**
 * @file
 * Plugin to provide access control based upon role membership.
 */

/**
 * Plugins are described by creating a $plugin array which will be used
 * by the system that includes this file.
 */
$plugin = array(
  'title' => t("Community: Access"),
  'description' => t('Control access by community.'),
  'callback' => 'dc_visibility_ctools_access_check',
  'default' => array('community' => array()),
  'settings form' => 'dc_visibility_ctools_access_settings',
  'settings form submit' => 'dc_visibility_ctools_access_settings_submit',
  'summary' => 'dc_visibility_ctools_access_summary',
  'all contexts' => TRUE,
);

/**
 * Settings form for the 'by role' access plugin
 */
function dc_visibility_ctools_access_settings($form, &$form_state, $conf) {

  return $form;
}

/**
 * Compress the community allowed to the minimum.
 */
function dc_visibility_ctools_access_settings_submit($form, &$form_state) {
  $form_state['values']['settings']['community'] = array_keys(array_filter($form_state['values']['settings']['community']));
}

/**
 * Check for access.
 */
function dc_visibility_ctools_access_check($conf, $context) {

}

function dc_visibility_ctools_access_summary($conf, $context){

}


Why are my fields are out of order when viewing? I have a content type called 'article'.  I create custom fields and drag-n-drop them in the order I want.  My user fills out the fields in the order that I prefer.  User then clicks SAVE.  Now the fields are out of order when this content type 'article' is being viewed.  When user clicks EDIT, then everything is back in order, just not when viewing.  Why is this and how do I fix it?

Reordering the fields for the content type only affects the edit/add form. To change the order of how they display (and other things, such as label display/placement) you need to go to Structure -> Content Types -> [Your content type name] -> Manage Display -> Default.