Pre-select language (instead of "Language neutral") when creating a node? With core's Locale module you can enable Multilingual support for a content type. When creating/editing a node, this gives you a Language select list with all enabled languages and "Language neutral" as options.

The default (resp. first) value for this select list is always "Language neutral".

Is it possible to have a certain language as default value instead?

At best it would be a per-content-type setting, but I'm fine with a global one, too (e.g. always using the site-wide default language as default value).

The option for it is available in admin/config/regional/entity_translation

The Entity Translation configuration page provide an interface to select default language for all content types separately


Select an image from a directory How do I select an image from a directory of images uploaded with the image field, in the same way done in Joomla?

Your best option would be to use the combination of Filefield Sources and IMCE, but unfortunately, the first isn't ready for D7 yet.


How to properly call entity form? I have created a wrapper in form of a "page" controller for my entity's form because I needed to do some tasks before it was rendered.

I ended up with this:

<?php
  class MyEntityController extends ControllerBase {
    public function mymethod(AnotherEntity $anotherEntity) {
      $myentity = $this->entityManager()->getStorageController('myentity')->create(array());
      $form = $this->entityManager()->getFormController('myentity', 'default');
      $form->setEntity($myentity);
      $form->setParentEntity($anotherEntity);
      $form->setRedirectRoute(array(
        'route_name' => 'some.route',
        'route_parameters' => array('somearugment' => $anotherEntity->id()
      ));
      return $this->formBuilder()->getForm($form);
    }
  }
?>

Is this the recommended way in regard of the entity form itself(ie. manually setting the form's entity object)?

<?php
class MyEntityController extends ControllerBase {
  public function mymethod(AnotherEntity $anotherEntity) {
    // @todo The methods don't exist in core, so it's not clear what object they
    //   should be called on.
    //$form->setParentEntity($anotherEntity);
    //$form->setRedirectRoute(array(
    //  'route_name' => 'some.route',
    //  'route_parameters' => array('somearugment' => $anotherEntity->id()
    //));

    $myentity = $this->entityManager()->getStorageController('myentity')->create(array());
    return $this->entityFormBuilder()->getForm($myentity, 'default');
  }
}
?>


How to set a checkbox using POST request with Services Module? I am trying to set a checkbox in a display using a post request by setting the value of the mark field to 1, specifically field_mark_as_discounted. But I can't seem to be able to achieve that. Note: The checkbox functions well when set manually. If anyone has come across this issue of setting a checkbox using post request please share.

This probably is the JSON you need for that field when POSTing:

field_foo: { und: [ { value: 1 } ] }

Remember, the Services module is dependent on which widget you have selected on the Manage Fields page for your entity/bundle.


How to display an "Out of Page" (PopUp) ad from Google DFP on a Drupal 6 site? Been beating my head on this for a while now. We've recently set up Google DFP for small publishers to use with a Drupal 6 site. We use the google admanager module to display the ads properly throughout the site using blocks.

I'm trying to create an out-of-page (ie. popup) for the front page.

In the past with OpenX I accomplished this by putting popup code in a block on the page. But this hasn't seemed to work yet with DFP.

Admittedly I'm still learning the in's and out's of the system, but have tried a few different ways now to no effect.

I've tried this: https://support.google.com/dfp_sb/answer/3370474?hl=en but haven't gotten it working yet, and not sure it will even be suitable for general use by staff who submit ads.

Would love to hear how others are making this work.

Looks like I solved it. Below is how ...

Finally got the process of creating a pop up on DFP figured out, now onto the Drupal part of it. https://productforums.google.com/forum/#!category-topic/dfp/inventory-management/dfp-small-business/e4vUwjgd4lk

UPDATE:

Got it working this way...

OK. Looks I mostly have it.

Just bypassed the Google Admanager module and generated a tag from the ad unit page. Then I put it in my theme page.tpl.php header enclosed in this (to make sure it is only front page):

<?php if ($is_front) { ?>
<script>......</script>
<?php } ?>

And then put the rest in the block with php enabled. I also made sure to remove the adslot generated other than the popup.

Hackish but it does the trick.

But if anyone knows how to make it work with Google Admanager, would love to look at it.


Guideline for users to view I have a website coming up soon and the editors for this website dosen't know how to use Drupal. I have made a content guideline for users to follow(guideline for like uploading content and such), now I want this guideline to appear on the website for only certain roles to view. In my example the role editor has the only permission to view this content and no one else.

Do you guys got any clue of how to fix this and also where I should place it? On their account page or just in the navbar?

Thanks for any tips and advice

One approach can be using content access module.So basically while creating content type you will get option to share content type with user role you want to.

  This module allows you to manage permissions for content types by role
  and author. It allows you to specifiy custom view, edit and delete
  permissions for each content type. Optionally you can enable per
  content access settings, so you can customize the access for each
  content node.

Other approach does not require any module, and will be simple and out of the box.

Create a content type, lets say editor_guide.
While creating the content type opt to keep the nodes unpublished.
Now create nodes,which can be single node(copying the complete guide to one node),multiple node(dividing the guide content into chunks as separate nodes),you can also keep the guide as file field on node.
Create a view of display type page with path say editor-guide.
In views you will get option to set permission for the page, set the permission for editor, in the views filter remember to change status for content for unpublished.
Now in you nav-bar menu block add a menu item, link it to editor-guide(or whatever).

This link will be automatically visible to editor role only.


How to disable SASS in Omega 4? I tried to set up SASS as part of an Omega 4 theme on a VPS server, but I'm now drowning in Ruby permissions and versioning issues. It's causing far more sysadmin type work than a CSS generator is worth for this project.

The Omega 4 docs repeatedly state that SASS is helpful but not essential to Omega 4 and that you can simply write CSS the old-fashioned way, which is what I intend to do - but they don't say anything about how to stop Omega trying (and failing) to apply SASS all the time.

How can I completely disable the SASS element of Omega 4?

I can't find anything relevant in the theme settings. I've tried simply removing / renaming the sass folder in my subtheme and clearing caches, but I'm still getting Ruby / SASS related errors that look like this:

  Error: File to import not found or unreadable: singularitygs.

I want it to completely stop trying to do anything related to SASS.

From reading around, it sounds like it's common to have a Drupal production server run Omega 4 with no SASS, and for people to have SASS on their development server then upload the CSS output to production when they're happy with it. Sounds sensible. But how what I can't find is, how do they stop the production server from trying to run SASS and access all that Ruby stuff all the time?

But how what I can't find is, how do they stop the production server from trying to run SASS and access all that Ruby stuff all the time?

There seems to be a major misunderstanding here.

Compilation of SASS is invoked by you, it's not an automatic action that a server will just take upon itself to perform. Your remote VPS will not be set up to try to auto-compile SASS into CSS unless you, or someone else with access to the server, has set it up like that. The very fact that you've had to setup and install ruby on the remote serve should hopefully make that obvious.

Having that stuff on your production server is wrong anyway, you should prepare your distribution locally (read: compile SASS, minify/uglify js, etc), and sync that. That way you can never have any problems.

Your comment below the question is correct: if you don't want to compile SASS, then simply don't run bundle exec guard, compass compile, or whatever other method you're using to instigate the compilation.

If you haven't told any process to watch/compile your SASS files, then no process will be able to do so. The power is yours.


How to create a view type of Entity reference display? I have an entity which contains a field collection of entity references and can edit the entity references with the Entity selection mode is Simple (with optional filter by bundle), but only Entity Field Name x shows in the list.

I also created a view which displays information from the referenced entity, but when I switch the Entity selection mode to Views I get the message:

  No eligible views were found. Create a view with an Entity Reference
  display, or add such a display to an existing view

.

After that I created a number of views of the Entity Reference display type, which display the same information but error message still comes up.

Can someone show me the steps to creating Entity Reference display views?
PS. I think what I am doing my be tricker than usual because the entity reference is a multivalued element in a field collection, but I am able t create views on it though>

Create a node view with the appropriate filters etc. you need to get the results you want to have in the reference field.

Then in the top left under the heading "Displays", Click "Add" and then select "Entity reference".

Then that display will be available to your field.

Edit: It doesn't have to be a node view, if you are referencing other entity types.


After core update: Access denied after submitting form We’re running on Drupal 7.73 and WebForm 7.x-3.30 – for a while now since the 7.75 to 7.77 Drupal release, we’ve been unable to update Drupal successfully.
As every time a user submits a form on the site, we’re getting an “Access Denied” message.
If you’re logged in as Admin it works. I believe it could have something to do with the “success message” that’s being displayed and that in theory, a redirect to a success page could fix it.
However, as we have many forms across several sites, it is not practical to go this route.
For two years we have had no problem updating Drupal to latest and no issues with WebForm so this is a new issue.
Can you please assist in providing a solution for this as we are unable to update to implement latest security fixes?

Thanks Beebee. Doing a fresh install is not practical at the moment. But I will do it once I've run out of potential fixes to try.
For now, I'll be attempting to implement this patch. Hopefully it works.
https://www.drupal.org/project/webform_service/issues/2048343#comment-9331515


Programmatically create a user and assign a role I'm programmatically creating a user with the following code.

$newUser = array(
  'name' => $mail,
  'pass' => 'password',  // note: do not md5 the password
  'mail' => $mail,
  'status' => 1,
  'init' => $mail,
  'roles' => array(5)
);
$user = user_save(null, $newUser);

I have got a role with the role ID equal to 5; when I create the user, in the table "users_roles" there is only a row with the value 0 for the role ID, but if I print the user object with var_dump(), it looks like the roles are created.

What am I doing wrong?

This code worked for me:

$new_user = array(
  'name' => $name,
  'pass' => $sifra, // note: do not md5 the password
  'mail' => $email,
  'status' => 1,
  'init' => $email,
  'roles' => array(
    DRUPAL_AUTHENTICATED_RID => 'authenticated user',
    3 => 'custom role',
  ),
);

// The first parameter is sent blank so a new user is created.
user_save('', $new_user);


How do I render a node queue as custom JSON? What would be the most sensible way to render a nodequeue queue in a custom JSON format (using Drupal 6)

We have a nodequeue that is both included in the UI in various places and served in a RSS feed.

I've found that I can use drupal_json() to convert a PHP data structure to JSON so now I'm mostly after what would be the right place for this?

As a hack, I tried to use RSS feed and to have a custom template for the feed. My problem there is that a) it feels pretty hackish and b) in the "general template" available I don't have the content available.

(As background, I'm pretty new with Drupal so the answer here is probably pretty straight-forward)

Where to continue?

There are some Views JSON modules if you look around, but I typically do this outside of views itself.  And you are correct, you are halfway there.

You want to wire up a hook_menu() to create a custom path in a module.  See our canonical question on this topic for more information.

Then in the menu callback, you do use views_embed_view().  Something like this:

function MYMODULE_the_callback() {
  $output = views_embed_view('nodequeue_1', 'the_display');

  print drupal_json($output);
  exit;
}

You can also use the $view object directly:

function MYMODULE_the_callback() {
  $view = views_get_view('nodequeue_1');
  $view->set_display('the_display');
  $view->pre_execute();
  $view->execute();

  $output = $view->render();

  print drupal_json($output);
  exit;
}

Using the later form, you can poke through the $view object and tailor your JSON accordingly.

This should give you a head start.

Keep in mind as you research this, that the plumbing is a little different for rendering JSON in Drupal 6 vs 7.  In 7, you would use drupal_json_output() and drupal_exit();


Include OR Group With Exposed Filters in View I have a view where I need to include an OR group for example (a + b) OR (C) as well as using Exposed Filters that will apply to both groups, giving something like (Ex1 + Ex2 + ((a + b) or c))). Is there any way I can make the exposed filters apply to both groups at the same time?

I thought it may be possible using nested or sub groups but I know it is not possible to create nested or sub groups in filters through the UI.

I think you can achieve it by adding new filter group from views UI.

Edit:
If your case is more special then you can achieve it using hook_views_query_alter.

if (!$new_feed) {
  $query->where[0]['conditions'][1]['field'] = 'node.nid';
  $query->where[0]['conditions'][1]['value'] = array();
  $query->where[0]['conditions'][1]['operator'] = 'IN (' 3, 4 5')';
}
else {
  $query->where[2]['conditions'][1]['field'] = 'node.nid';
  $query->where[2]['conditions'][1]['value'] = array();
  $query->where[2]['conditions'][1]['operator'] = 'IN (1, 2, 3);
}

You can unset where condition as per your use case.


Overriding nodes of a certain type with a view I'm using a single view to display some nodes on my site, and I can't figure out how to get it to only override the three content types I want (retreat, location, and teacher) but not all of them. In the contextual filter I specified validation by those types but it seems that's just making it do nothing on nodes of other content types so their content doesn't get shown at all.

I suspect the problem is either in the contextual filter settings and/or the fact that I specified the view's path as /node/% so as to override the normal display.

Attached are my view and the full contextual filter settings. Thanks for any advice!

You cannot do this because your view has now taken over the path "node/%", which is all node pages.

This means that hitting any node page will load your view, not the default Drupal node page and when your view loads, the contextual filter will either show the node if it is one of your 3 selected types, or it will display no results found for any other node type.

You can only override like this if you want to override the same for all nodes.

There are alternatives though, like (in no particular order - an there are almost certainly more ways not listed here):

The panels module to override the node display.
Custom code in your theme to print the view in your node template. You could use views_embed_view() for this.
Custom code in a module to override the display of the node.
Display suite - Using dynamic fields or block fields and changing your node display to show your view field and hide all other fields.


presidency of drupal template file I am new to drupal themeing, I have tried to find the presidency of template files(.tpl.php).. So my question is for a particular scenario if I have html.tpl.php, page.tpl.php, block.tpl.php, node.tpl.php, taxonomy-term.tpl.php, template.php,

which file going to run first?
if I want to make change some variable's value for page.tpl.php/html.tpl.php then I need to write a function XXX_preprocess_page()/XXX_preprocess_html() according to this listed presidency (https://api.drupal.org/api/drupal/includes!theme.inc/function/theme/7) ?

Answer 1:-template.php file will runs first.you can check it by using die() on top of all files.

answer2 :-For changing some variable's value for page.tpl.php/html.tpl.php use function function XXX_preprocess_page().

html.tpl.php -> Handles meta info, body classes

page.tpl.php -> Handles content body display

node.tpl.php -> Handles content display

field.tpl.php ->Handles per field display

Template.php provide display alteration  for all these files.


Total number of likes on views images and social networking? I have a view that displays 8 images (which links to their particular node) uploaded by the all users. Now I want to display a counter which counts total number of likes on that post either by facebook or on the site.

Can I link the image like with the facebook likes of that particular image post?

To count how many times users have liked a particular node maybe checkout the Like Button module.


How can I set page specific user view access by user role? I need to be able to restrict access to specific pages based on user role, I heard that nodeaccess could do that, but I haven't been able to figure out how to do that with it, can you set page specific role access with nodeaccess? if not is there a module that can do that?

First of all, you can install nodeaccess module and then configure it. It works for specific pages to restrict based on user access.


String Field as Link to Content (replacing node title field) I dislike the fact that the Node Title is not truly a field because it prevents me from being able to control its display order, etc.,  like I can with all of the other fields. I tried using the exclude_node_title module which did as it claimed and I added a new field called Post Title of type Text.

How can I make that new custom title field into a link to the Content?

If you are a Drupal module developer, the easiest way to do this would be to define a custom field formatter that would specifically do this (i.e. linking field value to the URL of the node)  for the text field and content type that you want.

If you are looking for a UI solution, I'd suggest installing the custom_formatters module. Once you have done that, import the formatter below.

$formatter = new stdClass();
$formatter->disabled = FALSE; /* Edit this to true to make a default formatter disabled initially */
$formatter->api_version = 2;
$formatter->name = 'string_to_link';
$formatter->label = 'string_to_link';
$formatter->description = 'Converts string from a text field attached to a node to a link';
$formatter->mode = 'token';
$formatter->field_types = 'text';
$formatter->code = '[node:title]';
$formatter->fapi = '';

Now, go to the "Manage Display" page of the content type where you have your Node title field, and set the formatter to *Custom: (string_to_link)*. The value of the field is immaterial now. It'll be linked to the node always.

However, linking to the node from the node view itself is not really of much use, right? So, I'm guessing you'd want this in a node listing. (A set of nodes). In that case, you might want to use the Views module where you can explicitly link the node title to its URL for a view.


How to relate nodes by field, not title? I'm using Feeds to import content from XML. The content is films and their showtimes, like this:

<film id=av1>
  <title>Avatar</title>
  <showtimes total="2">
    <showtime show_id="1" id="av1" date="1/1/2012" price="10" />
    <showtime show_id="2" id="av1" date="2/1/2012" price="15" />
  <showtimes>
<film>

Right now, I've created two content types (Film and Showtime) and using Node Reference (References module) to relate Showtime to Film. Then I have various views that use the relationship to show listings, date listings etc.

This works ok, but Node Reference can only link on node title, so if someone updates the film title in the source feed we get problems. It would be better to link using the ID field, which never changes.

The problem is that I'm using Feeds to import to two content types, so running two Feeds importers, and they have to use title from the source to sync. So say the Film title is changed in Drupal, then more Showtimes get added to the XML. On import, the new Showtime nodes are created but can't find their Film node. Using the ID field from the source would keep things joined up. Maybe using Field Collection instead of referenced content types is better?

Possible solutions:

Use a taxonomy vocabulary and create a new term 'id' for each film. Then tag showtimes with the same term. I'm not sure this is a good use of taxonomy, creating single-connections in this way?
See if Relation module provides linking by field. Probably won't work with Feeds yet.
Create a single content type for films, and use Field Collection to store the showtimes. Then everything is connected in a single node. Not sure how feasible this is.

Any guidance or suggestions welcomed!

You are mistaken. Node reference uses the node id - the primary key for nodes to create the reference. The form element where you need to enter the node you want to reference, uses autocomplete to make it easier to find the node you want to reference, but the value stored is the node id. So there is actually no problem in using node reference and changing the title.

Code from the node reference module to illustrate this, can be found where the schema is defined for the field type it uses to create these reference:

/**
 * Implements hook_field_schema().
 */
function node_reference_field_schema($field) {
  $columns = array(
    'nid' => array(
      'type'     => 'int',
      'unsigned' => TRUE,
      'not null' => FALSE,
    ),
  );
  return array(
    'columns' => $columns,
    'indexes' => array('nid' => array('nid')),
    'foreign keys' => array(
      'nid' => array(
        'table' => 'node',
        'columns' => array('nid' => 'nid'),
      ),
    ),
  );
}


Drupal AJAX fires only once In Drupal 7, I have a form where I would like to do the following:

Display a list of options in a simple two column table
Selecting an action from a drop down list fires AJAX and replaces options in the table

I have code written and Drupal only posts values to the AJAX on the first time you pick a select. Does this just not work on form 'item' types? Note, there are also other forms on the page, but the form IDs are unique as are the form fields.

$form['new_date'] = array(
            '#type' => 'select',
            '#title' => 'Delivery Date',
            '#options' => $date,
            '#ajax' => array(
                'callback' => 'delivery_date_weekends',
                'wrapper' => 'dates-ajax',
                'method' => 'replace',
                'effect' => 'fade',
            ),
        );

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

Then in the AJAX callback, data is returned with #markup set to theme('table') of the results. It only works the first time around, I see the POST data in the Firebug console. Pick another drop down option, my table does not update.

Did I do something wrong here?

Edit: seems like the POST is making it, but the response is empty, but should not be.

Edit 2: Ajax Callback:

function delivery_date_weekends($form, $form_state) {

    $query = new EntityFieldQuery();
    $result = $query->entityCondition('entity_type', 'field_collection_item')
        ->propertyCondition('item_id', $form_state['values']['rates'])
        ->fieldCondition('field_delivery_basis', 'value', 'Weekly', '=');

    $startmonth = strtotime(date('m', $form_state['values']['new_date']).'/01/'.date('Y'));
    $endmonth = strtotime('+1 month', $startmonth);

    $query->fieldCondition('field_delivery_date_period', 'value', $startmonth, '>=')
                ->fieldCondition('field_delivery_date_period', 'value', $endmonth, '<=');

    $result = $query->execute();

    if ($result) {
        $headers = array(
            array('data' => 'Weekend', 'class' => 'tableHeader-processed'),
            array('data' => '', 'class' => 'tableHeader-processed'),
        );

        $rates = entity_load('field_collection_item', array_keys($result['field_collection_item']));

        foreach ($rates as $key => $rate) {
            if ($rate->field_delivery_available['und'][0]['value']) {
                $rows[] = array('data' => array(date('M j, Y', $rate->field_delivery_date_period['und'][0]['value']), array('data' => 'delivery link', 'class' => array('fee'))));
            } else {
                $rows[] = array('data' => array(date('M j, Y', $rate->field_delivery_date_period['und'][0]['value']), array('data' => 'Not Available!')));
            }
        }

        $form['booking_weekend']['#markup'] = theme('table', array('header' => $headers, 'rows' => $rows, 'sticky' => FALSE));
    } else {
        $form['booking_weekend']['#markup'] = 'No delivery weekends exist for this month. Please select another date.';
    }

    return $form['booking_weekend'];
}

Basically when a month/year is selected, I am querying for dates (inside a field collection).

It's hard to say without actually running those queries but I think the problem is just because of a disparity in the names of your form elements.

In your form the element is defined as $form['date_weekend'] but in your callback you set an element called $form['booking_weekend'].

This would probably be fine except that $form['booking_weekend'] doesn't have the #prefix and #suffix that $form['date_weekend'] does. Drupal replaces the entire wrapper element when it does an AJAX replace so if the new element doesn't have a wrapper with the same ID around it the next AJAX call won't work (as no element would exist with the correct ID).

I'd recommend changing the element names to match as this should solve the problem, but if you really need it to be a different element just add the wrapper around the new element in your callback:

// The rest of delivery_date_weekends() comes before this as normal...

  $form['booking_weekend']['#markup'] = theme('table', array('header' => $headers, 'rows' => $rows, 'sticky' => FALSE));
} else {
    $form['booking_weekend']['#markup'] = 'No delivery weekends exist for this month. Please select another date.';
}

$form['booking_weekend']['#prefix'] = '
';
$form['booking_weekend']['#suffix'] = '
';

return $form['booking_weekend'];


Create a view of users to show their profile visits I need to track the IP address in order to have a good idea on how many users visit each profile. This report will be available only to the admin.

I have used User Visits Advanced module

The problem is that even user can also see his profile visits by using this module.I was also trying to figuring out how to create view of recent visitors using this module but finally unsuccessful.

I just want to create view report of users and their respective profile visits .

You can achieve this by simply creating a rule for profile clicks and add an action i.e. a counter that accepts +1 everytime the event occurs (Rules module).
To create a profile click action, all you need is the uid (user ID) which can be like this example.com/user?q=uid.
create a field in my accounts which stores this value and keep it hidden with display suite. In views, show the profile as fields and choose the uid and your recent field to display profile visits. Style it with css. sorry for bad english I am spanish


How do I add a custom script on a specific page? I wanted to add custom JavaScript code on certain nodes.
I have written this code in the html.tpl.php template, but this doesn't work. (donate is the path alias for a node.)
<?php if(arg(0) == 'DONATE'): ?>
  <script>
    (function() {
      // ...
    );
  </script>
<?php endif; ?>

You could do this:

<?php
$node = menu_get_object();
if ($node && $node->nid == DONATE_NODE_ID):
?>
<script></script>
<?php endif; ?>

But a better way would be to:

Wrap your script in Drupal.behaviors:

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

Call drupal_add_js() in hook_preprocess_page(). This code would go to template.php:

function YOUR_THEME_preprocess_page(&$variables) {
  $node = menu_get_object();
  if ($node && $node->nid == DONATE_NODE_ID) {
    drupal_add_js(drupal_get_path('theme', 'YOUR_THEME') . '/path/to/js.js');
  }
}


Display all terms from a specific vocabulary in my template I have a page where I want to display the terms for the vocabulary named "Services" in an unordered list. The Page is in no way associated with the vocabulary, I just want to display the terms at the end of the article. What should I type in my file?

I wouldn't type anything in a file.

Instead, use the Views module and create a block view that lists all of the terms in that vocabulary, then display that block immediately after the main content on the specific page that you're talking about.


How to create menu and submenu using taxonomy collection in drupal commerce kickstart? I am using Drupal Commerce Kickstart for ecoomerce site. I created menu using taxonomy collection. I want to create submenu also using taxonomy collection. Is it is possble? I want to menu like this Image.

I am creating taxonomy vocabulary as 'collection'.i created 'computers'. then i can add the products in computers. If i want to add the products in computers->printers. How can i create computers->printers using taxonmoy?

There is module Taxonomy Menu. You should use this module.


Add "Request new Password" link to user logIn page I am using the Logintoboggan module to redirect users to the login page when they try to visit a page for which they don't have the permission to visit.

How do I add a Request new Password or Forgot Password? link to this page?

This should be already there as a link.
if it is a custom login page, you can add a link with "/user/password" href


Interfacing Data back and forth: JSapp  Drupal I want to create custom products for every single one of my customers, and to add a thumbnail and custom order data from a JSAPP.

Seen on #2 My JS application must get the unique id from the user.
regardless if they are logged in or not (i dont know how which is the exact data or variable in the db i should send, and how do i send it?)

in #3 i must recieve custom information generated on the jsapp, i can send this as a  Json , XML or URLstring from the jsapp to drupal commerce; im unsure how could i somehow, inject this information or update a variation of my product.
or maybe there's a more easy way to do this.

Does anyone have some pointers on how to address this communication problem?

Once your step one runs, you've actually created a unique order with a unique line item that references a product.
The ID in #2 should probably just be your line-item id.

I would consider creating a rule on the event "After adding a product to cart" and a custom action (this is an answer where I provided the code to make a custom action) that takes a line item id (something the rule will easily have access to) and sends that to the three.js app.

You really just want to add the custom data to the line item (which is unique to each line item on the order). In fact, using Customizable Products you can easily create a bundle specifically for adding as many fields as you would need to track your data (and display/hide it in views or display modes).

To do this, I would create a menu item that somehow recieves the full json object. Perhaps this blog article will help? Regardless, once you have your data, you will want to update the line item with your data and the best way to do this is with entity meta data wrappers if you are using fields to store the data.

<?php

$line_item_id = 1;
$line_item = commerce_line_item_load($line_item_id);
$line_item_wrapper = entity_metadata("commerce_line_item",$line_item);
dpm($line_item_wrapper->getPropertyInfo());

// ... mess with fields

$line_item_wrapper->save();

?>

If you are using the fields on a line item to store your data, the cart will already be up-to-date because it simply references all the line items.


How to display a taxonomy term's immediate children on its page? In Drupal 8, how can I display a taxonomy term's immediate children on its page?

For example, I have a hierarchical taxonomy vocabulary like this (simplified):

Animals
--Fishes
----Blennies
------Yellow Blenny
------Green Blenny
----Gobies
------Blue Goby
------Red Goby

On the page for the taxonomy term "Fishes" (e.g. drupal/fishes) I would like Blennies and Gobies (but not their children) to appear.

I have tried configuring Contextual Filters in Structure>Views>Advanced but not been able to do this.

Given your additional information, this short step-by-step guide, that should give you the desired results:

Duplicate/disable the original Taxonomy view / alter it as follows.
In "Advanced/Contextual filters" remove "Content: Has taxonomy term ID"
Add a new Contextual filter "Content: Has taxonomy term ID (with depth)":

Depth: 1 (will show content for the next level child terms as well)
When the filter value is NOT in the URL:

Provide default value
Type: Taxonomy term ID from URL
Load default filter from term page: checked

When the filter value IS in the URL or a default is provided:

Override title: checked, use the variable {{ arguments.term_node_tid_depth }} (this will make sure the term name will be shown in the page title)
(Optionally, but strongly suggested) Specify validation criteria: checked
Validator: Taxonomy term ID
Vocabulary: (your vocabulary name checked)
(Optionally) Validate user has access to the taxonomy term: checked

As you'd like to show an image, you may also wish to change the Format of the view from Content to Fields and add the image field of your tagged content.

Please note, that the depth modifier may lead to duplicates. So within the Advanced / Other section's Query settings, you should enable the "Distinct" option.

You can further improve your view results by adding relations to the actual terms, the term name and adding grouping. But this seems out of scope for your initial question.

I did the above steps on a clean D8 test instance with auto-generated content and vocabularies, and it was working fine.

EDIT:

According to your comments, you actually like to show fields of the child taxonomy terms only. So here is how to do that:

disable the default taxonomy view
create a new view
in View settings / Show choose "Taxonomy term"
"of Type" is your vocabulary
in "Page settings" check "Create a page" and provide the URL "taxonomy/term/%"
click "Save and edit"
in Advanced / Contextual filter add the filter "Taxonomy term: Parent"
apply the same settings as in my above solution to the contextual filter, except for the title variable, which should now be '{{ arguments.tid }}'

As result, you should see the first level children of the taxonomy term in the view.

If you like to see some of their properties only, switch the type of the view to fields and add the field you like to display.


An AJAX HTTP error occurred. HTTP Result Code: 200 I'm trying to Run the Test from Administrative User, and it bring me below Error message:

  An AJAX HTTP error occurred. HTTP Result Code: 200 Debugging
  information follows. Path:
  /drupal7.50/batch?render=overlay&id=18&op=do StatusText: OK
  ResponseText: Fatal error: Maximum execution time of 30 seconds
  exceeded in C:\xampp\htdocs\drupal7.50\includes\database\database.inc
  on line 2204

How can I fix that?

Increase your PHP max_execution time in php.ini


Write a boolean function in template that determines if the logged user is either the node author or admin How do I write a function to determine if the user is either the node author or admin?

if ( logged user is author || admin ) {
  // …
}

It is for the node template.

Put this to template.php file of your theme:

function YOUR_THEME_NAME_preprocess_node(&$variables) {
  global $user;

  if(in_array('administrator', $user->roles) || $variables['node']->uid == $user->uid) {
    $variables['is_admin_or_author'] = TRUE;
  }
  else {
    $variables['is_admin_or_author'] = FALSE;
  }
}

then in your node.tpl.php or node--your-content-type.tpl.php you'll have a variable $is_admin_or_author with either TRUE or FALSE value.


Trying to create a block plugin module I am trying to write a custom block module in Drupal 8 that will allow me to place this block into my pages using the block layout screen.

I'm very new to Drupal, so this is very much a "hello world" project (initially) to figure out how this works.  To this end, I have been following Youtube video instructions as well as reading through whatever documentation I can find on Internet and also a couple of books, but to no avail [yet].

What I have done is creating a walker directory in the modules folder, where I have created the Walker.info.yml file, whose content is the following.

name: Walker
description: A filewalker
core: 8.x
package: Custom
type: module

In the same directory, I have created the Walker.module file.

/**
 * @file
 * Code for the walker module.
 */

I have then created the module/walker/src/Plugin/Block/ directory and the WalkerBlock.php file with the following content.

/**
 * @file
 * Code for the walker block.
 */

namespace Drupal\walker\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a walker block
 *
 * @Block(
 *   id = "walker",
 *   admin_label = @Translation("The walker block"),
 *   category = @Translation("Blocks")
 * )
 */

class WalkerBlock extends BlockBase {
  public function build() {
    return array('#markup' => 'Walker block');
  }
}

If I run the command "find . -type f | grep Walker" from my root Drupal directory, I get the following output.

./modules/Walker/Walker.module
./modules/Walker/src/Plugin/Block/WalkerBlock.php
./modules/Walker/Walker.info.yml

Yet, though the documentation and videos I have read suggest that this should be all I require, the Walker block does not appear in the block layout screen as an option that I can place in one of the block regions.

Can anyone see what I'm doing wrong?

I cleared the cache from /admin/config/development/performance.

Ok can you go to drupal8/admin/modules

and see :

Your:

walker.info.yml is correct
your Walker.module id fine (however i would use (walker as the dir and walker.module aka non caps)
your block looks fine

Thinking Rename all to
./modules/walker/walker.module
./modules/walker/src/Plugin/Block/WalkerBlock.php
./modules/walker/walker.info.yml

as could be Name space issue as "Drupal\walker\Plugin\Block" vs "Drupal\Walker\Plugin\Block" ?

but really every thing looks fine
When you install the module you should be able to place the block in
admin/structure/block


What is the benefits of Panels for a themer? I've never thought much of Panels, as I have always been comfortable with writing my own themes.

However, I have seen a lot of articles advocating the virtues of Panels (from Lullabot & Active Lamp), so I thought it would be time to revisit it, especially as Panels is going to be in Drupal 8.

I've played around with it extensively and I've even watched this helpful screen cast series.
But I can't see what the benefits are.

I usually build websites where non-technical people can edit the nodes.
Usually each node form will have several fields where the user can add all the content for that page.

To get the most out of Panels, it seems you have to split your pages into separate nodes that hold 1 piece of content and then use the Panels to bring the separate nodes together. This might be fine if you are creating a site that is only to be edited by a web designer.

However, it creates an issue when you give the site to a non technical person to add content. Most non-technical people would like to do all their page creation on a single screen. If they have to create lots of different nodes and then let Panels bring them altogether, it seems to be confusing for them.

I know Panels has better performance and better support for context compared to Blocks. However, it seems to add a lot of complexity and abstraction.

I can see how it would be incredibly useful for a non-themer, but I can't see what the benefits are for someone who can theme.

Could someone enlighten me. Thanks!

One large advantage of Panels is that you can have wildly different layouts for pages, depending on your needs.  In this context, layouts can mean both content and styling.

On the content end, you can have your main node-being-viewed piece, and add in different things.  For example, you can add in views into sidebar areas that show/link to related content.  You can also add in blocks, and have a lot more flexibility than what come stock with Drupal (though D7 really improves things).

On the styling end, the biggest advantage is being able to choose different layout templates for each page and variant.  Other modules, like Context can do similar things, but I find it much easier to do with Panels.

With the sites we build, all pages are Panel pages (no exceptions).  From the client's perspective, having adequate training and inline help greatly helps with them being able to keep the site alive (and nearly all of our clients are non-technical).

A side effect of using Panels is that you get a lot of features that cTools provides, which can be a huge benefit when you need to retrofit a site.  In a lot of ways, we have found using Panels pages for everything really aids with future proofing a site.


How to have nodes online but not as a separate node number? I have several content types let say : fooCT1,fooCT2, fooCT3 ... fooCT20.
fooCT1 has several entities to the other content types.

If I publish fooCT1 I run a rule which also publish all relevant nodes (fooCT2.. fooCt20) in order to see this information in a panel page for a anonymous user.

But using this means also that the different nodes are available under there separate names url aliases like:

/node/xx

where xx is the node nummer

How to disable this easily?

You can't disable the node entity's canonical path easily, but you can serve a 403/4 for requests to the pages instead.
The simplest method for that is probably the Rabbit Hole module

Rabbit Hole is a module that adds the ability to control what should happen when an entity is being viewed at its own page.
Perhaps you have a content type that never should be displayed on its own page, like an image content type that's displayed in a carousel. Rabbit Hole can prevent this node from being accessible on its own page, through node/xxx.


How to add css and js to a views-view-table--viewname.tpl.php I am theming a  particular view "test" so my theme file is "views-view-table--test.tpl.php".
Its working fine.

I want to add css and javascript to the "views-view-table--test.tpl.php" file
Used the below code to add css and javascript. but its not working:

drupal_add_css("themes/bartik/style-test.css", $type = 'file', $media = 'all', $preprocess = FALSE);
drupal_add_js("jquery.min.js", $type = 'file', $media = 'all', $preprocess = FALSE);

How to add css and js to views-view-table--viewname.tpl.php file.

You could do this by using a process function at theme level...

function YOURTHEME_preprocess_views_view(&$vars) {
    if (isset($vars['view']->name) && $vars['view']->name == 'YOURVIEW') {
        drupal_add_css("themes/bartik/style-test.css", $type = 'file', $media = 'all', $preprocess = FALSE);
        drupal_add_js("jquery.min.js", $type = 'file', $media = 'all', $preprocess = FALSE);
    }
}

Change 'YOURTHEME' to the theme you are using so if 'bartik' then
you want bartik_preprocess_views_view().
Change 'YOURVIEW' to the name of your view. You can get this by
printing $vars['view']->name from the function.
Clear caches after adding function.


Create New User After Subscribing with Simplenews I want new Subscribers to a single Newsletter using SimpleNews to automatically be set a Role so that they are already then registered on a site. I have already tried a custom Rules Set but the Role creation doesn't appear to happen and I'm wondering what I'm doing  wrong in my approach to the Rule.

The frontend process is i) Anonymous user subscribes via the Simplenews Subs Block ii) send them they are now subscribed.

The backend is something like:

i) User Subscribes as an Anonymous user (i.e. not logged in)

ii) Subscribe to Newsletter type

iii) Set Role from initial 'Anonymous' to 'Subscriber' Role and assign to a Profile type.

Also, I'd like to reduce the 'confirm' email process which currently needs to be given by the end user to confirm a subscription.

I appreciate that some 'hacking' my be needed in the Simplenews core to reduce certain features and would appreciate any advice on this.

I'm sure this is easy to do and I'm merely missing something in my efforts, would someone like to share what I'm doing wrong in the above Rules structure?

Thanks.

I changed tact. The above probably has security issues, but I only needed a simple temporary solution for a new project launch. I dropped the use of a frontend 'Subscriber' option and instead reverted back to a standard registration page and commented out the $vars tabs option in the theme template.php page.


View poll *results* as anonymous user doesn't allow access Has anyone come across this problem before? When an anonymous user tries to view the current poll results (from the current poll block) they get an ACCESS DENIED error. However, if they view the poll (not the results) they can see it just fine.

For example:

http://cypress.supportedns.com/~actionin/node/11/results
(Access denied)

http://cypress.supportedns.com/~actionin/node/11/
(No problem)

In the permissions administrative page, I gave the Anonymous User access to view results, so I'm not sure what's going on. Any ideas? Thanks in advance.

Stumbled upon the same problem when I wanted to redirect some anonymous users to see only the results of a poll depending on what email address pattern they entered in a form before. So I thought sending them to node/%nid/results would be fine and somehow it also worked AS LONG AS for testing purpose I didn't vote before (as other anonymous user with allowed email address pattern). Then the IP got stored somehow and when accessing the poll node you automatically get the results view presented WHILE AT THE SAME TIME the node/%nid/results URL gets unavailable.


How can I add all the existing content types into a dropdown list? In Drupal 8, I am using the Config Pages module to set up a configuration page for a custom module. How can I add all the existing content types into a dropdown list?

In your custom form, in add $options to your content type list field.
the following snippet get list of all the content type names for you;

   $node_types = \Drupal\node\Entity\NodeType::loadMultiple();
    // If you need to display them in a drop down:
    $options = [];
    foreach ($node_types as $node_type) {
      $options[$node_type->id()] = $node_type->label();
    }


What does exacly mean by Entity CRUD API? Here in the documentation comment for entity_export() says:

  Note: Currently, this only works for entity types provided with the entity CRUD API.

So, what does it actually mean?

Background info:
We are going to create two modules. One for defining an entity type using hook_entity_info() and other providing UI for adding, editing, managing etc. There will be two drupal 7 installations. One will be installed with both of above modules and other only with first module defining entity type.

On first drupal installation, we will be creating/editing entities of type what we defined. And exported to second installation. So, we are checking for the capabilities of entity_export() and entity_import() functions for integration of entity export/import functionality.

The CRUD API is the set of functions that allows an entity to be Created, Readed, Updated and Deleted.

An entity has a CRUD API when its entity controller implementes de EntityAPIControllerInterface. The EntityAPIController class, the default Entity API entity controller class implements this interface.

So you only have to define your entity using the Entity API contrib module and use that class as controller (or your custom subclass of that class).

If you read the entity_export code you can see:

 if (in_array('EntityAPIControllerInterface', class_implements($info['controller class']))) {
    return entity_get_controller($entity_type)->export($entity, $prefix);
  }

The function checks if the entity controller implements EntityAPIControllerInterface interface; if yes the export method is called.


Aggregating CSS breaks with Internet Explorer Selecting the option to aggregate and compress css files breaks display in internet explorer 11. It displays fine with other browsers, or fine in ie11 if I deselect that option. The site in question is wowforfun.org

Thanks in advance.

Edit: Here's a part of the css as served to ie:

‹      µYér¤8þ?OÁŽ£#Ú³M•¶!öÇ>Á>ƒ
T 1 F»Üï¾™:@ªÚîÙí—Ë:Ryç§Ô
é%ÏxÝVTÒáÈENE²oÏAÇ+–§ü•ŠSÅß’’å9mÒ–wL2Þ$äzIÓ!krzNöq<Þ¸Ä‚¾*ÖÉ°“ïMÞÐtþ;d5)ÌhMDÁš$N[’ç¬)ŸRÅ†#É^

Looks like it wasn't uncompressed at all.

Edit 2:

My .htaccess section related to compression:

<IfModule mod_headers.c>
# Serve gzip compressed CSS files if they exist and the client accepts gzip.
RewriteCond %{HTTP:Accept-encoding} gzip
RewriteCond %{REQUEST_FILENAME}\.gz -s
RewriteRule ^(.*)\.css $1\.css\.gz [QSA]

# Serve gzip compressed JS files if they exist and the client accepts gzip.
RewriteCond %{HTTP:Accept-encoding} gzip
RewriteCond %{REQUEST_FILENAME}\.gz -s
RewriteRule ^(.*)\.js $1\.js\.gz [QSA]

# Serve correct content types, and prevent mod_deflate double gzip.
RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1]
RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1]

<FilesMatch "(\.js\.gz|\.css\.gz)$">
  # Serve correct encoding type.
  Header set Content-Encoding gzip
  # Force proxies to cache gzipped & non-gzipped css/js files separately.
  Header append Vary Accept-Encoding
</FilesMatch>

And here's the settings.php section:

# $conf['css_gzip_compression'] = FALSE;
# $conf['js_gzip_compression'] = FALSE;

I've tried those two lines both commented and uncommented, didn't make a difference.

The Advanced CSS/JS Aggregation Module might make it work correctly. If not, the advagg validator sub module might help identify the CSS that is breaking in IE.


Duplicate URLs for same node Yesterday I found that one article from my website is indexed more than once in Google, and I discovered that the URLs are like like the following ones.

http://www.techiestuffs.com/gadgets/best-racing-games-available-android?page=1
http://www.techiestuffs.com/gadgets/best-racing-games-available-android?page=2
http://www.techiestuffs.com/gadgets/best-racing-games-available-android?page=3

The same node is generated many times.

The original link is http://www.techiestuffs.com/gadgets/best-racing-games-available-android.

This doesn't happen for just a node; all other nodes are also indexed more than once.

I am afraid Google will penalize us for this.

Do you know of any solution to avoid this?
For which reason does Google generate this type of URLs?

You should be ok with regards to Google penalizing you because you've got a canonical link statement in each page which will tell Google that the page is really just a duplicate of the main page.

<link rel="canonical" href="/gadgets/best-racing-games-available-android">

Google canonical link info


How to disable front page view programmatically? I have another view that uses the same path as the front page view which is "/node" and I will like to disable the front page view programmatically.

How can I do that from a hook_install?

Views are entities, so:

Load the View:

$view_id = 'content'; // Replace with the ID of the view you wish to disable.
$view = \Drupal::entityTypeManager()->getStorage('view')->load($view_id);

Update the status:

$view->setStatus(FALSE);

And save it:

$view->save();

Or all in one go:

\Drupal::entityTypeManager()->getStorage('view')
  ->load($view_id)
  ->setStatus(FALSE)
  ->save();


Use panel url for Solr result I am using Apache Solr on my website and the search form block is configured to use Apache Solr. I also use the Apache Solr panels module to panelize my page.

I create a panel on search/my-search/!query, when I use it manually all works fine but when I search via the form search block, I am redirected on the default Apache Solr result page (search/site/!query).

How can I change this behavior ?

EDIT :
Okay, I found the solution by searching a little bit more !

I just disabled the default search block form and put the "Search form (Apache Solr Panels)" in the section I wanted. I only have to restyling my input.

I will put it in a separate answer tomorrow (because of my reputation, I can't answer in the next 8hrs after posting my question)

use

function hook_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == "search_block_form") {
    $form['#submit'] = array('custom_search_redirect');
  }
}

function custom_search_redirect($form, &$form_state) {
  $search_data = $form_state['values']['search_block_form'];
  $form_state['redirect'] = "search/my-search".$search_data;
}


Display a node counter, by specific content type? How can I display a counter e.g. Total News: 999, Total Blog posts: 123, etc. ?
(looking for d6 solution actually)

Use the Count Nodes module.

  The Count Nodes Module counts total number of nodes created(published
  and unpublished both) in each content type. It provide a total number
  of blocks equals to the total number of content types created such
  that administrator can use one block for each content type.


How to filter with all outputs when using Rewrite results option in Views In my view using the "Rewrite Result" option, I combined two fields "first name" and "Surname" to display as one field with label "Full name".

I then added an exposed filter to allow users search through the Full names.

My challenge is that it only filters using the surname and not both. How do I get users to be able to filter using both first name and surname.

Thanks.

To filter on both the Firstname and Lastname, when you want to add a filter, select  Global: Combine fields filter, and then click add. The next step tells you to select the fields to filter. Select your firstname and Lastname field


Customise Mollom status messages I had a look around and couldn't see if this had been asked before so decided to create a new question. Please delete this if this is a duplicate.

I'd like to customise the status messages that appear to users when they trigger the captcha and profanity filter, as the default messages are quite long winded. My experience with Drupal is VERY limited and am not sure if there is a module specific hook for overriding such settings, or if this is relating to core/a core hook.

I've had a look at the mollom.module code and notice that the message is being set  at line 2220

form_set_error('mollom', t('Your submission has triggered the profanity filter and will not be accepted until the inappropriate language is removed.'));

My question being - is there a simple hook I can use to access this? Perhaps in my preprocessor functions? What is the 'Drupal way' of modifying this message?

If it is of any relevance I am using the Entityform module for my form. Please let me know if you need me to provide additional information.

Thanks for your help in advance.

If you look in the settings.php for your site, there should be a template for overriding strings in the interface (anything in the t() function).

You would add something like this to the settings.php file:

$conf['locale_custom_strings_en'][''] = array(
  'Old string'      => 'New string',
);

I haven't used it, but there's a module that makes this easier: String overrides.


Display all comments of node without pager (300+ comments) I have a content type with threading comments. The max number of comments per page is set to 300 (that is the absolute max). If there is more than 300 comments - they get paged.

How do I show all comments of the node without the pager (300+ comments)?

This is a desired function knowing the negative impact on UX.

I couldn't find any theme functions/ hooks that can be used for setting a new max for comment pagers. Please, do not suggest to render comments via Views.

It's stored in a variable per content type, you can override it like so:

variable_set('comment_default_per_page_CONTENT_TYPE', 500);

Where CONTENT_TYPE is the machine name of the content type.

If you want to change the options in the UI, you can do it through a form alter:

function MYMODULE_form_node_type_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#node_type'] == 'foo') {
    $new_options = drupal_map_assoc(array(10, 30, 50, 70, 90, 150, 200, 250, 300, 500, 1000));
    $form['comment']['comment_default_per_page']['#options'] = $new_options;
  }
}


Update custom fields on hook_user_login I have implemented hook_user_login(&$edit, $account) and some of custom fields from $account should be updated. I am doing this with user_save(). These changes are not visible in Simpletest. I have tried user_load() in Simpletest before login and after, no changes. The Values are being saved to the db but are not visible in Simpletest. Any Idea?

Simpletest assertions are working on user created in Simpletest with $this->drupalCreateUser().


entity_load not fetching the updated column I've a custom entity {my_table} and added a new field in schema file as follows

/**
 * Add {new_column} field to {my_table} table.
 */
function MY_MODULE_update_7100() {
    $table = 'my_table';
  $spec = array(
    'type' => 'int',
    'description' => "blah blah",
    'size'=> 'tiny',
    'default' => NULL,
  );
  db_add_field($table, 'new_column', $spec);
}

When I ran update.php the database table column got updated.

But the problem is when I run 'entity_load' it's not fetching the added column to the object.

$get_entity = entity_load('{my_table}', array(184));
dpm($get_entity) // showing all columns, except the new_column

I've cleared the cache but no luck.
Any suggestions would be much appreciated.

If I have understood you correctly, as well as updating the table you must provide an updated schema definition for the entity. Drupal uses this definition to determine the names and properties of the columns in the entity.

Note you do not need to do an 'update' action for the schema definition: just change it to match the current code. You (only) need the update hook for databases that enabled the earlier version of the module. Also, importantly, the update hook must both add the column to the database, but set the new property value for any rows appropriately. Often this can be done by the database default value, but not always.


WSOD afte uninstalling the Memcache module and deleting it's folder I've uninstalled the Memcache API and integration module from my site and then deleted it's folder from sites/all modules.

Then, my site was down, and a WSOD appeared instead.

I went to Drush and typed drush cc all, and then this came up:

Afterwards I restored the deleted memcache folder at sites/all/modules, and again typed drush cc all... Then the site came to work, but now when I run Drush I still so something wired:

Why I have a WSOD when I remove the module's folder if the module itself doesn't even enabled?...
How can totally delete the module?

Update for user - Les Lim:

One of the steps to install Memcache module is to add a line in your settings.php file that specifies a module file as a cache backend.

To uninstall the Memcache module, you will also need to remove that line in settings.php.  Until then, Drupal will be attempting to load a cache backend from a file that is no longer there.


Drush update for the first time hosed my website Running latest versions of Drupal, etc.
Localhost - dev site
Maintenance mode

While trying to install Commerce_kickstart and running Drush for first time to update modules,  Drupal got completely hosed.

Can not find problem in database
Repaired all databases but get Drupal white screen, no error messages
Phpmyadmin won't work

Can anyone offer a series of steps to attempt recovery or at least find out what went wrong?

Thanks in advance.  I need ASAP.

Probably one of the updates of your modules is messing up. Most recently I had this problem with updating Rules which broke my site the same way it did yours (WSOD).

Reverting and updating one by one can show you what went wrong.

If you use drush you can do: drush up modulename (e.g. drush up rules) to update one by one, instead of drush up which updates everything. drush up drupal only updates core.


Links not working on migrated site I moved a site from a hosted server to my local machine and none of the links that point to internal pages work even though they look correct. I'm getting odd behaviour as described below. This is true even for the admin toolbar provided by the module (People, Modules, Configuration, etc.)

My process was as usual, I copied all the files down, exported/dumped the database, created a local db and then imported the dump.

(I'm putting in lh instead of localhost bec stackexchange won't allow links with localhost)
I was able to login via lh/myidols5/?q=user but not lh/myidols5/user which gives 'access denied'. From lh/myidols5/?q=user, if I click on any link say the home button in the admin toolbar I go to the right page but am logged out. The address bar says lh/myidols5/ which is correct so I'm at a loss as to why I'm logged out.

Anyone know what the issue is?

Thanks

I feel you're missing .htaccess file. Usually its a hidden file, so make sure to show all files (including hidden files) and copy it and paste it into your local drupal folder.

Also, make sure you local server has mod_rewrite enabled to support clean URLs, if its not enabled then check this answer: How to enable mod_rewrite in Apache?.

Another suggestion is; to turn off Clean URL from settings.php by adding the following code:

$conf['clean_url'] = 0;


How do I sort by day? Hi I have a bunch of items which occur on a given day of the week. So i have a text field called Day, and it's populated by the words 'Monday', 'Tuesday', 'Wednesday' etc. Is there a way to sort this in views that will list items in Weekday order. I can only find options for alphabetical order.

This could be working for example if you'd use a taxonomy term reference instead of a text field. Just create a taxonomy with your workdays as terms.

use these tags on your content
in views add a field to show the term your content is tagged with
in the format options choose 'group by' and select your taxonomy field

Now the content should be grouped by the workdays. To achieve the correct sorting order you can either rely on the term-ID (which is created in chronological order) or just arrange your terms with drag and drop (in the terms dialog).


How to migrate D6 node reference to D7 organic group membership? I have created migrations for most of my D6 site to a new D7 site.  In the D6 site I have users with profile nodes.  Those profile nodes are linked to another type of node via node reference.  In D7 the other node will be an organic group.

I would like to be able to transfer the node reference relationship in D6 to organic group membership in D7.  Has anyone done this?

Thanks in advance for any help given.

I ended up using the advanced method as described in the semi-official documentation (https://drupal.org/node/2023273).  It all came down to modifying the query to get the nid and new group nid.

class MemberCompanyMembershipMigration extends DrupalMigration {
    /**
     * Construct a migration.
     *
     * @param array $args
     *   Constructor arguments passed at migration-registration time.
     */
    public function __construct($args) {

        parent::__construct($args);

        // Set the fields we want; document in the UI.

        $this->sourceFields += array(
                'nid' => t('Group node ID.'),
                'is_active' => t('User status in the group.'),
                'is_admin' => t('Group admin or not.'),
                'uid' => t('User ID.'),
        );
        $this->sourceOptions['map_joinable'] = FALSE;
        // Set the query as the migration source.
        $this->source = new MigrateSourceSQL(
                $this->query(), $this->sourceFields, NULL, $this->sourceOptions
        );
        // Map source rows to destination rows with uid+gid.
        $this->map = new MigrateSQLMap($this->machineName,
                array(
                        'field_contact_member_company_nid' => array(
                                'type' => 'int',
                                'not null' => TRUE,
                                'description' => 'ID of the group.',
                        ),
                        'uid' => array(
                                'type' => 'int',
                                'not null' => TRUE,
                                'description' => 'ID of the user.',
                        ),
                ),
                MigrateDestinationOGMembership::getKeySchema()
        );
        // Destination is group membership.
        $this->destination = new MigrateDestinationOGMembership();
        // Field mappings.
        $this->addFieldMapping('group_type')
        ->defaultValue('node');
        $this->addFieldMapping('entity_type')
        ->defaultValue('user');
        // Let the user migration map the uids.
        $this->addFieldMapping('etid', 'uid')
        ->sourceMigration('ClickUser');
        $this->addFieldMapping('state', 'is_active');
        $this->addFieldMapping('is_admin', 'is_admin');
        // Group migration maps the gid via the OG Node migration.
        $this->addFieldMapping('gid', 'field_contact_member_company_nid')
        ->sourceMigration('MemberCompany');
        // Minimal source config means we just set a default
        // instead of looking for roles to map.
        $this->addFieldMapping('group_roles')
        ->defaultValue(array(OG_ADMINISTRATOR_ROLE));
        // Accept defaults for these destination fields.
        $no_input = array(
                'created',
        );
        $this->addUnmigratedDestinations($no_input, t('Do Not Migrate'));
    }
    /**
     * Query for the source group data.
     *
     * @return QueryConditionInterface
     *   Provides a connection and query for getting OGMembership records.
     */
    protected function query() {
        $query = Database::getConnection('click2', $this->sourceConnection)
        ->select('content_type_contact_content','p')
        ->fields('p', array('field_contact_member_company_nid'));
        $query->join('node','n','n.vid = p.vid');
        $query->addField('n', 'uid');
        $query->isNotNull('field_contact_member_company_nid');
        return $query;
    }
    public function prepareRow($row) {
        if (parent::prepareRow($row) === FALSE) {
            return FALSE;
        }
    }
}


How to use a relative path for a theme's favicon I'm trying to ship a favicon with my custom Drupal 8 theme, but I can't figure out how to specify its location relative to my theme's installation location.

Following this answer I've created a config/install/MY_THEME.settings.yml file containing

favicon:
  use_default: false
  path: '/themes/MY_THEME/static/favicon.png'

(I'm keeping all my theme's static files in a static subdirectory of my theme directory)

This works, but contains a hard-coded reference to the installation location of my theme. Hence, if a user decides to install the theme in themes/contrib or themes/custom instead of in themes the favicon won't be found.

Therefore I would like to specify a path relative to my theme's root directory or relative to the MY_THEME.settings.yml file. However, it seems that Drupal uses the server root (/) as a base when I specify a relative path, so static/favicon.ico ends up as /static/favicon.ico which obviously doesn't work.

another idea for a workaround would be to overwrite the href property on runtime with hook_page_attachments_alter, somethng like this:

function MYTHEME_page_attachments_alter(array &$page) {
     foreach($page['#attached']['html_head_link'] as $k => $v) {
          if (array_key_exists('rel', $v[0]) && $v[0]['rel'] == 'shortcut icon') {
                  $page['#attached']['html_head_link'][$k][0]['href'] = drupal_get_path('theme', 'MYTHEME') . 'static/favicon.png';
          }
     }
}

or use the default favicon path (MY_THEME/favicon.ico), it will be taken, see this source:

// Generate the path to the favicon.
      if ($cache[$theme]->get('features.favicon')) {
        $favicon_path = $cache[$theme]->get('favicon.path');
        if ($cache[$theme]->get('favicon.use_default')) {
          if (file_exists($favicon = $theme_object->getPath() . '/favicon.ico')) {
            $cache[$theme]->set('favicon.url', file_url_transform_relative(file_create_url($favicon)));
          }
          else {
            $cache[$theme]->set('favicon.url', file_url_transform_relative(file_create_url('core/misc/favicon.ico')));
          }
        }
        elseif ($favicon_path) {
          $cache[$theme]->set('favicon.url', file_url_transform_relative(file_create_url($favicon_path)));
        }
        else {
          $cache[$theme]->set('features.favicon', FALSE);
        }
      }


How to change DB active config storage of an installed site to config file storage? The default.settings.php says

/**
 * Active configuration settings.
 *
 * By default, the active configuration is stored in the database in the
 * {config} table. To use a different storage mechanism for the active
 * configuration, do the following prior to installing:
 * - Override the 'bootstrap_config_storage' setting here. It must be set to a
 *   callable that returns an object that implements
 *   \Drupal\Core\Config\StorageInterface.
 * - Override the service definition 'config.storage.active'. Put this
 *   override in a services.yml file in the same directory as settings.php
 *   (definitions in this file will override service definition defaults).
 */
# $settings['bootstrap_config_storage'] = array('Drupal\Core\Config\BootstrapConfigStorageFactory', 'getFileStorage');

I have added above code to my settings.php and this is the piece of code I have added in services.yml before install.

services:
  config.storage.active:
    class: Drupal\Core\Config\FileStorage
    factory_class: Drupal\Core\Config\FileStorageFactory
    factory_method: getActive
    public: false

How can I change the DB config storage to file config storage after site install? We have config_db.module to change it form file storage to DB storage. Do we have a module to change it from DB storage to file storage?

Here are the steps I followed:

1) Export settings to your current $config_directories['sync'] directory (by default it is defined in settings.php and it is something like 'sites/default/files/config_VerYlonGkEY0123/sync')

$ drush cex

2) Create these directories (should be writable):

config/
  active/
  staging/
  sync/

3) Copy/paste all files from $config_directories['sync'] to config/active/

4) Add the new settings to settings.php

$config_directories = array(
  CONFIG_ACTIVE_DIRECTORY => DRUPAL_ROOT . '/config/active',
  CONFIG_STAGING_DIRECTORY => DRUPAL_ROOT . '/config/staging',
  CONFIG_SYNC_DIRECTORY => DRUPAL_ROOT . '/config/sync',
);

$settings['bootstrap_config_storage'] = array('Drupal\Core\Config\BootstrapConfigStorageFactory', 'getFileStorage');

5) Add this to service.yml (in the same directory as the settings.php):

services:
  config.storage:
    class: Drupal\Core\Config\CachedStorage
    arguments: ['@config.storage.active', '@cache.config']
  config.storage.active:
    class: Drupal\Core\Config\FileStorage
    factory: Drupal\Core\Config\FileStorageFactory::getActive

6) Export the settings to sync:

$ drush cex sync

Than you should have the settings in config/sync :)


How can I make my Drupal website automatically reflect the changes when the DB values change? In performance I have caching turned off, yet if I update a value in the DB  directly I have to flush the cache to see changes on my site. Why is that?
(ex: using phpmyadmin and changing a value)

I'm inserting/updating values to my DB externally from another server that is not using Drupal. (using mysql)

How can I make my Drupal website automatically reflect the changes when the DB values change?

The settings you are referring just tell Drupal to use the cache_page table.
See drupal_page_footer() that contains the following code.

  if (variable_get('cache', 0) && ($cache = drupal_page_set_cache())) {
    drupal_serve_page_from_cache($cache);
  }
  else {
    ob_flush();
  }

For the fields, there is the cache_field table (cleared by field_cache_clear()), which is used from the field CRUD API, but also from the field attach API, which includes functions like field_attach_load() or field_attach_update(). If you are writing a field table without using one of the field API functions, such as in your case, then you need to clear the field cache; if you look at the code of field_attach_update() you can understand exactly which cache ID you should pass, to avoid clear all the cache for no reason.


drush perm-grant gives "The drush command 'perm-grant' could not be found" I am using drush -u 15 perm-grant --roles="site administrator" but the command returns:

  The drush command 'perm-grant' could not be found.

any ideas about that? according this documentation the drush perm-grant is an available command. or maybe is some limitation of the user used to run drush?

the drush version is 5.4

thanks.

according @MDP, Permissions API module is required for this, and according its module page is only for Drupal 6, so this command is not available in drupal 7. @greg_1_anderson user recommends to use Drush 8.x-6.x to get this feature working built-in


How to send a custom Solr Distance Query with SearchApi My nodes have a geofield and my search query should find all the nodes within a range.

I've managed to create a search form against my Solr Server with views. But I want to do the request by myself (having my own form and submit method). There's a solution for D7 here: How to send a custom Solr Query using Search API Solr but none of that seems to be usable with the D8 modules.

I believe there must be something like

$result = SolrSearchService('myServer', 'myIndex')->request(['title' => 'Test']);

But I can not find anything.

The views-built search page renders a query against my Solr Server like

path=/select params={q=(phonm_rendered_item:nintendo^1+tm_title:nintendo^8)&json.nl=flat&pt=48.1371079,11.5753822&d=50&omitHeader=true&fl=ss_search_api_id,ss_search_api_language,score,fts_field_geo_koordinaten__distance:geodist()&start=0&fq=%2Bindex_id:default_solr_index+%2Bhash:ozztjn&fq={!geofilt}&rows=10&sfield=locs_field_geo_koordinaten&wt=json}

Apparently there are some parameters responsible for the distance calculation:

pt=48.1371079,11.5753822 - it's where I am
d=50 - it's the max distance
field_geo_koordinaten - it's the geofield in the node
geodist() - the function ?

How can I render such a query with Search API?

Debugging around I found the solution:

$index = Index::load('default_solr_index');
/* @var \Drupal\search_api\Query\Query $query */
$query = $index->query();
$query->keys($form_state->getValue("keys"));
$location_options = (array) $query->getOption('search_api_location', []);

$location_options[] = [
      'field' => "field_geo_koordinaten",
      'lat' => 48.1371079,
      'lon' => 11.5753822,
      'radius' => 50,
    ];

$query->setOption('search_api_location', $location_options);
$results = $query->execute();

Thanks for pointing me in the right direction.


How do I use a submit callback on a Drupal admin settings form? I'm using this code to make my admin form:

function custom_orders_admin(){
  $form = array();

  $form['custom_ignore_terms']['ignore_terms'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Don\'t display these'),
    '#default_value' => variable_get('custom_ignore_terms', array()),
    '#options' => drupal_map_assoc($termTypes),
    '#description' => t("Choose the terms you do not want displayed."),
    '#required' => FALSE,
  );

  return system_settings_form($form);
}

But I notice that if I do this:

function custom_orders_admin_submit($form, &$form_state) {
  exit(var_dump($form_state));
}

I can't exit. I'm guessing this is because system_settings_form() takes care of submitting. How do I get my control back? I need to do some custom processing in that _submit handler...

The default submit handler of $form_id . '_submit' only fires if no other submit handlers have been set.

Because system_settings_form() sets a submit handler, the default handler doesn't fire, so you have to specify it if you want to use it.

You can do so like this:

/**
 * A custom form.
 */
function custom_form() {
  $form = array();

  $form['custom_form_field'] = array(
    '#type' => 'textfield',
    '#title' => t('Custom form field'),
    '#default_value' => variable_get('custom_form_field', ''),
  );

  // Set a submit handler manually because the default submit handler
  // gets overridden by the system_settings_form() submit handler.
  $form['#submit'][] = 'custom_form_submit';

  return system_settings_form($form);
}

/**
 * Submit handler for the custom form.
 */
function custom_form_submit($form, &$form_state) {
  // Submit code here.
}

Adding your submit handler like this means yours will run before the system_settings_form() submit handler.

If you want yours to run after, instead of:

// Set a submit handler manually because the default submit handler
// gets overridden by the system_settings_form() submit handler.
$form['#submit'][] = 'custom_form_submit';

return system_settings_form($form);

Do:

$form = system_settings_form($form);
$form['#submit'][] = 'custom_form_submit';
return $form;

Make sure not to do this though:

$form = system_settings_form($form);
$form['#submit'] = array('custom_form_submit');
return $form;

because that would overwrite the system_sttings_form() submit handler, which would defeat the purpose of using the system_settings_form() function in the first place.


Verify a node with a given node ID exists I created a module that receives the node ID from the form. On form validation, it needs to verify a node with that node ID exists.

How can I verify it?

If you don't want to load the entire node then you can use entity query:

$values = \Drupal::entityQuery('node')->condition('nid', $id)->execute();
$node_exists = !empty($values);

This will be much more efficient because it only asks for the ids and not all the node fields.


How can I get the translated path to the current node? How to get path to current node but of another language?

Available languages:

English (URL prefix: en)
Polish (default, no URL prefix)

Enabled detection methods:

URL (by prefix)
Session (parameter: language)
Browser
Default

I created translation of taxonomy and translations of some basic page nodes. However, none of the following codes work.

drupal_get_path_alias(null, 'en')
drupal_get_normal_path('', 'en')
drupal_get_path_alias('hardcoded-existing-path', 'en')
url(current_path(), array('language'=>'en'))

How to make it work? All internalization modules are enabled.

The problem is the lack of a language string / prefix for polish. By this URL detection is skipped.

Look into locale_language_from_url() line 275

<?php
 case LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX:
   // $_GET['q'] might not be available at this time, because
   // path initialization runs after the language bootstrap phase.
  list($language, $_GET['q']) = language_url_split_prefix(isset($_GET['q']) ? $_GET['q'] : NULL, $languages);
  if ($language !== FALSE) {
    $language_url = $language->language;
  }
 ?>

If there is no language found in the URL is skips. Now the language detection is by session and so on. The only real option is that all languages you use have a prefix. The only real problem that than occurs is that the homepage would always redirect wich is not that nice for bots. But still better than fall back to language detection you don't want.

Besides that you could mode "default" just below "URL (prefix)" so Drupal won't use the session or the browser. But even this is not reliable from my experience.


Commerce - access denied on checkout page When I tried to access the checkout page I get "Access denied"; this happens with every role, all of which have permission to view the cart/make orders/view orders.

This happens even with a complete fresh install of Commerce Kickstart.  There must be something going on with the server configuration?  All other admin and user functions work without any issue.  I am using HHVM instead of standard PHP, but surely I am not the first one to attempt to run Drupal Commerce on HHVM.  I can find no trace of this issue elsewhere except someone with the same question 6 months ago that was unresolved.

Any idea what's going on here?

I found out that there is a difference between how Zend and HHVM interprete the php key() function.

In the Drupal commerce_checkout module there is a function that returns the first key of an array by using the php key() function (commerce_checkout.module, line 480).

/**
 * Returns the page ID of the first checkout page sorted by weight.
 */
function commerce_checkout_first_checkout_page() {
  return key(commerce_checkout_pages());
}

On the default Zend rendering engine this returned the desired result of the first array key. But in HHVM this returned nothing. I believe this is because the pointers of the array were not flushed by HHVM (maybe for performance reasons), and they were flushed in the Zend engine.

I don't think it was a good idea of the creaters of this module to use the key() function to get the first key of the array anyway

I now rewrote this function to this:

/**
 * Returns the page ID of the first checkout page sorted by weight.
 */
function commerce_checkout_first_checkout_page() {
 return reset(array_keys(commerce_checkout_pages()));
}

Getting the keys of the array first and then with reset() rewind the array's internal pointer to the first element and return the value of that first array element.
Of course the key() function did the job on the standard Zend engine, but for HHVM this didn't.

I will report this issue to the maintenance crew of the drupal commerce module, and hopefully it will be commited into the next release. I don't think there is anything wrong with the way HHVM interprets the key function (if I am right in thinking this is the root of the problem). I think the key() function just shouldn't be used like this in this situation.


Recursively pre-populate Webforms I am trying to pre-populate a webform based on the values from a third party service.

I am using form_alter to start the processing and then using a recursive function to traverse the tree. I am passing the sub-form(part of a form of type fieldset) by reference, so that changes do carry forward.

Here is the code :

function my_module_form_alter(&$form, &$form_state, $form_id) {
    $submitted = $form['submitted'];
    prepopulate_form($submitted, $value_array);
}

function prepopulate_form(&$form, $value_array) {
  foreach ($form as $key => $settings) {
    if (is_array($settings) && isset($settings['#type'])) {
      if ($settings['#type'] == 'fieldset') {
        prepopulate_form($form[$key], $value_array);
      }
      $value = 'Some logic to get the value from value arrya';
        dpm($value); // I am getting the expected output here.
        $form[$key]['#default_value'] = $value; // The changes I make here are not being carried to the actual $form array I suppose
    }
  }
}

But the form is not getting pre-populated. I am not sure what I am missing here.

Any insights would help. Thanks !

The main problem is you are not passing the form array by reference so your values are never coming back into the form. Try this (note the ampersand on $form['submitted']):

function my_module_form_alter(&$form, &$form_state, $form_id) {
  $submitted = &$form['submitted'];
  prepopulate_form($submitted, $value_array);
}

Otherwise you are only modifying the $submitted variable and not the actual form.

Alternatively, you could also just pass $form['submitted'] into the prepopulate_form() function instead of using the $submitted variable and that would also work.

Plus, you are using $value_array, which does not exist, so you will need to pass actual values in.


Filter between first and last day of the current month in any year I have a date field in my view and when I try to filter between the first and the last day of the month there is no result in my view preview.

Here is my settings. This filter is because I need to compare the born date from all the registered users and print only those who have the value between first and last day of the month.

Here are the screen shoots of my views settings:

First here is my date field settings:

Then the filter settings:

And finally set the filter option to get the result between first and last day of the month:

This is what I've tried till now without success. Can someone help me in this? I don't want to use a module for this. I only need this filter works.

Long story short: Use Views Partial Date. The image below demos some of its features (click the image if you don't see the animation).

Why it can't be done with Views

Views by itself can only handle Unix timestamps. Even when a relative date is used, Views' date filter uses strotime() internally to convert the relative date to a timestamp before adding the filter condition to the query.

Why it can't be done with Date Views

Date Views is a complex beast that provides a multitude of features surrounding date calculations, including support for multiple DB backends.
Theoretically Date Views could implement incomplete dates, but since it also supports relative dates and various input widgets (like Date Popup), the additional validation and logic would be extremely hard to maintain.

What we can do about it

At this point we've established that either an additional module or custom code of some form is required.
With that in mind I created Views Partial Date and will be expanding this answer in the following days to describe the approach I took.


How to add the view name as body class function THEMENAME_preprocess_views_view(&$variables){
        $view = $variables['view'];
      if($view->name == "YOUR_VIEW_NAME" && $view->current_display == "MACHINE_NAME_OF_VIEW"){
        $variables['attributes']['class'][] = 'page-'.$view->name;
    }

For some reason this does not work. Any ideas?

this one worked:

function THEMENAME_preprocess_html(&$variables) {
  //view name as body class
  $variables['view_title'] = '';
  $route = \Drupal::routeMatch()->getRouteObject();
  if ($route) {
    $view_title = $route->getDefault('_title');
    $variables['attributes']['class'][] = 'view-' . $view_title;
  }
}


Go to previous page (not after form submit) I have a function that is called by hook-menu item an is accesible from different subpages of the site. This function does not return any html, it just do some database inserts and should redirect user back where he came from.

Well, it could be easily done by adding url args as a parameters to this function and then use drupal_goto() with those arguments. But I'm wondering if there is any drupal function for this. I was trying drupal_goto(drupal_get_destination()); but it does nothing.

Create your link this way:

$link = l('Link title', 'your/menu/path', array('query' => drupal_get_destination));

This will add the destination argument to the link URL.

Then, at the end of your page callback, simply call:

drupal_goto();


Are use Drupal\Core\Form\FormStateInterface statements for a Drupal 8 hook required? This may be obvious to expert D8 users, but; If I am implementing hook_form_alter in Drupal 8, the hook definition looks like this:

hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id)

In that there is a direct reference to FormStateInterface, so am I right in saying that it is redundant to also have the use statement in my file:

use Drupal\Core\Form\FormStateInterface; // Still works if I comment this out

/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  ...
}

When generating the code using Drupal Console I get:

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  ...
}

Best practice? It seems neater to me that the hook itself references FormStateInterface, making the use statement redundant.

It is recommended to use the use + short reference. Technically, it makes no difference, but it results in shorter lines and is easier to read.

The reason the hook documentation always uses full namespace is to make it easier to copy it into a module file, as you'd otherwise also have to look up the use statement.


how to know if a form_alter is being invoked through an ajax request? I am altering a node add form using hook_id_form_alter and inside that i am doing a drupal_goto, if query parameter is missing a mandatory token value. Now, in the add node form, there is an image field. When i'm trying to upload that image, which is an ajax request without the token, the form_alter function is invoked and hence fails.

Any help is appreciated!

This is likely an AHAH issue. See Adding dynamic form elements using AHAH. The form is loaded from the cache and then the form alter is called irrespective of whether it is full post request or via Ajax. You might want to change the logic in a way to save the result of checking the token the first time the form_alter is called in a $_SESSION variable (Save the token in the session variable). And change the logic to include an additional check for the presence of the same $_SESSION variable if there is no token value, and if present if that token is valid (for security reasons).


How to add gratuity when a commerce cart is updated? I need to add a gratuity to my site when user add a product to a cart. The function is the same to the ioby.org site. Each time the cart is updated we will update the gratuity on the cart. I have read the solution for this function from newsignature who developed this site but it's hard for me to using rules to do it. Anyone can help me? Thanks so much!

Here is the solution from newsignature:

  Gratuity was at first going to be a tax type in the Commerce system.
  However, one of the requirements was to also give the user the ability
  to remove the gratuity if they felt that they didn’t want to cover the
  costs for it. Since tax isn't usually an optional item in shopping
  carts, the ability to remove it has not been placed in the Commerce
  tax module.  To enable that ability, we place the gratuity into a line
  item that is calculated every time the cart is updated. Once again we
  used the Entity API to generate a new product, and this time the
  gratuity type that has an individual SKU, and a price that is a
  percentage of the order total. Another custom feature we added was to
  show a popup message when a user removes the gratuity, explaining to
  them the importance of gratuity for ioby.  Since the view doesn’t
  discriminate between the different line items, it was necessary to use
  some front end javascript that handles this feature.  And of course,
  with items being added and removed from the cart, it was necessary to
  change the price of the gratuity on the fly, assuming it wasn’t
  removed.

I would use the Rules module for this, with trigger event "add item to cart" and action being "add another product to the cart", where the second product is a gratuity. You might need to use a further rule to set the price of the "gratuity" product as proportional to the original product.

If you don't need to do it separately for each item, like if it's the same percentage for all, you could apply it as if it were a tax, a (negative) discount, or a handling fee, using the relevant modules for those.


Allow users to access only terms that he created Terms from user that created nodes are stored in vocabulary tags. When user creates new content i would like to allow him to only choose from list of terms he created instead of whole vocabulary.
Is that possible ?

There is a module that stores authoring information (author, published date and updated date) for the taxonomy term.

This module is views integrated. Exposes authoring information fields (author, published date and updated date) to views configuration (fields/filters/arguments/sorts/relation).

Taxonomy Term Authoring Information

After installing this module, create a view that filters terms and displays only terms created by the current user then change the field widget to use that view.


Field validation: check for uniqness There is this content type and it has a field (decimal). I want to apply a uniqueness validation on it (no two nodes with the same "National Code" value). Apparently Field Validation module is the way to go. How do I achieve this ?

You can achieve this with Unique Field module. Set the scope to Content Type and you should be good to go.


Remove menu item in template.php drupal 7 After quite a bit of googling I'm asking here which theme_* function I use to remove a menu item.

I already use theme_menu_link to alter 2 of the menu items in this menu but I want this one to dissapear completely.

Wasn't there a field I could add to the array that would hide it or am I thinking of something else?

I think you're looking for:

$element['hidden'] = 1;

Using:
http://api.drupal.org/api/drupal/includes%21menu.inc/function/theme_menu_link/7

check that it's the element you want, and set the "hidden" value to 1.   I have not tested this.


Referencing other nodes created by the same author I have a site where members can sign up and post an article (standard content type) which I'll call STYLE A.
I now need to allow the members to create a different article (another content type) which I'll call STYLE B.

One of the fields within STYLE B will be a drop down list of all the article STYLE A's that this specific user has created. The user can then select one of the STYLE A's from the list.

I've tried using the reference and the entity reference modules but I can't quite get it. I've been able to create the reference field so that there is a dropdown of all STYLE A articles but these are not limited to that specific user.

Could anybody help me out. I've tried reading articles on relationships in views etc but it's not quite making sense.

thanks

some time ago, I created something similar. A drop down box (client profile) for the current user only - i.e. when creating a content type, the user would be able to choose a client profile, but only from a list of client profiles THEY authored.

I accomplished this using the following:

using a custom Node Reference Module, I created a field on the content type that used the node reference as a drop down box
added the following to the .module file, around line 878:

global $user;

if($user->uid != '1') $query->condition('n.uid', $user->uid, '=');

This creates a condition on the sql query that if the user isn't 1 (admin) it references the user id of the node creator, relative to the current logged in user, while Admin can override

If you going to go with this approach, be sure to rename the files and module into a CUSTOM module (I renamed mine custom_node_reference for simplicity).


How can I get bundle of an entity from type and id? I need to identify bundle of an entity from its type and id.

For example, if the type is 'node' and id is 7, I may get 'page' as bundle.

Thanks

Use entity_load to load the entity as mentioned by @Nikhil.

Then use entity_extract_ids, to extract the bundle. Example:

$entity = entity_load('node', array('7'));

list(, , $bundle) = entity_extract_ids('node', $entity);

echo "Bundle name is : " . $bundle;

The function entity_extract_ids returns a numerically indexed array (not a hash table) containing the elements:

0: Primary ID of the entity.
1: Revision ID of the entity, or NULL if $entity_type is not
versioned.
2: Bundle name of the entity, or NULL if $entity_type has no bundles.

where, 0, 1, and 2 are array indices. However, the approach used by core and contrib modules is to use the list() function.