Node not being saved when using Rules redirect I need help with basic setup of Rules. I have read tuts but could not figure this one out.

I have content type A.
A is saved to system as unpublished. It saves personal information and those cant be changed anymore so users after using it get Access Denied message as they dont have permission to view it.

What i want to do with rules after node is being saved,
1. Redirects to some other internal url (any),
2. Get system message "Node creae successful".

Problem is that node after being saved with Rules module does not get saved at all. Nothing in Content, nothing in database. Without Rules everything works as intended.

Rules setup:
1. Events:
"After saving new content"

Conditions:
"Content is of type" - param: Content node, Content types: A
Actions:
Page redirect - url: blog
Show a message on the site: Parameter: Message: devtest

What happens is that redirect works correctly, message does not appear (no big deal, could create node with some text on it instead of system message).
But node A does not get saved anywhere.

You may be redirecting before the pending node_save is called.

Try explicitly adding the action "Save Entity" under the Entities heading just before your redirect rule is evaluated. Make sure the redirect is the last action called.


Use views to prepopulate fields I have a site that generates letters to be sent to schools.

The visitor arrives at the front page where they are presented with a map (leaflet map) with all the local schools marked on it. They then can click on a specific school to view its page (node with school location (addressfield) info).

Here they have the option to 'generate a letter to the school' - I have the form (entityform) set up but it needs the visitor to type in the school address again. How can I dynamically fill the address-field in my form  based on the school the visitor navigated to the form from?

map>school>school-specific-form

There are over a hundred schools, so would prefer not to have to duplicate my form...

Thanks.

If you don't want coding, this is one possibility:

If you only have one form, but hundreds of nodes, another way I would suggest to do it is to use Webform Template for the School content type. You can create one webform template and then reuse it for every school node, but the address field in the webform should have a default value that is a token of the node's address field. All you would need to do is set up your webform template's address field to have a default value of something like [node-field-school-address] and every instance of the webform will have the address of the node it belongs to.

In order to use tokens in a webform, you will need this module: Webform Patched . This is a module that contains the Webform module itself along with token support an therefore the original Webform module should be disabled. I implemented this myself for my site and it worked without any problems.

I never worked with addressfield, but I found this module in case you need it: Addressfield tokens


How can I see a log of emails that Drupal has sent? How can I see a log of emails that Drupal 7 has sent? It would be handy for things like troubleshooting registration issues... to see that registration emails are actually being sent.

Drupal doesn't keep hold of that information, so your server mail logs are the place to look.

Some email operations are recorded to the watchdog, but not all. You can get a look at a few of those ops with a simple query like this

SELECT * FROM watchdog WHERE message LIKE '%email%'

That'll get you false positives, but also should show you what operations are actually recorded (welcome message sent, new password sent, etc.).

For future reference, you can use either of these modules to log outgoing mail:

Mail Log
Email Log


Simplenews - how pass values from own input How I can pass value from added input to database(?) in Simplenews? I want to use this value later in newsletter, e.g. print it in block template.

Below is how I created field

function news_hook_form_alter(&$form, &$form_state, $form_id){
    if($form_id == 'simplenews_block_form_2730'){
        $form['field_name'] = array(
        '#type' => 'textfield',
        '#title' => t('First name'),
        '#required' => TRUE,
        '#size' => 20,
);
}}

function my_module_form_alter(&$form, &$form_state, $form_id){
  if($form_id == 'YOUR_FORM_ID') {
    $form['field_name'] = array(
      '#type' => 'textfield',
      '#title' => t('Name'),
    );
    $form['field_name_submit'] = array(
      '#type' => 'submit',
      '#value' => t('SAVE'),
      '#submit' => array('my_module_name_submit'),
    );
  return $form;
  }
}

function my_module_name_submit($form,&$form_state) {
  if ($form_state['values']['field_name']) {
    variable_set('Name', $form_state['values']['field_name']);
  }
}

variable_set stores textfield value in variable table. You can access/get this value using variable_get as mentioned below

  variable_get('Name')


How to get the template file using hook block view? function tgs_user_block_info() {
  $blocks = array();

  $blocks['user-list'] = array(
    'info' => t('List of Users'),
  );

  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function tgs_user_block_view($delta = '') {
  $block = array();

$variables['logo'] = theme_get_setting('logo');
$variables['module_path'] = drupal_get_path('module', 'tgs_user');
$variables['current_path'] = '/' . current_path() . '/';

switch($delta) {

  case 'user-list':
    $block['content'] = theme('user_list', $variables);
    break;
  }

  return $block;
}

/**
 * Implements hook_theme().
 */
function tgs_user_theme() {
  $theme = array();

  $theme['user_list'] = array(
    'template' => 'templates/users',
  );

  return $theme;
}

This is my code in module. It doesn't call in template that I have been created on my hook_theme.

Try doing it this way, you need to separate your template name from the filepath.

/**
* Implements hook_theme().
*/
function tgs_user_theme() {
  $theme = array();

  $theme['user_list'] = array(
    'path' =>  drupal_get_path('module', 'my_module') . '/templates',
    'template' => 'my_template'
  );

  return $theme;
}


Drupal rules discount matrix - look up by taxonomy term I'm having trouble applying a complex set of discounts to my products through rules.

The discounts are basically a user-category/product-category matrix with a different discount percentage for each cell. User categories and product categories are taxonomy lists. I have added a Field Collection field (with and infinite number of values) to the user category. In this field collection I combine a product category and a discount percentage (as a decimal), and then repeat for all product categories.

So when calculating the product sale price I need to:

Look up the product category (works fine)
Look up the user category and load the discounts list (works fine)
Look up the right discount in the discounts list by product category (having trouble with this)

I've been able to look up the right discount in a custom PHP action like this:

$product_category = $product->field_product_category['und'][0]['tid'];

for($discount_index=0;$discount_index<count($user_discounts);$discount_index++){
    $discount = $user_discounts[$discount_index];
    if($discount->field_discount_product_category['und'][0]['tid'] ==  $product_category){
        return $discount->field_discount_percentage['und'][0]['value'];
    }
}

return 0;

But apparently returning values out of a custom PHP block is not supported.

Next I thought to install the Conditional Rules module.
I could loop through the discounts and check the current loop variable against the product category and apply the discount if it matched. Within the If I can't access my loop variable though.
Can anyone suggest a method that might work? I prefer not to have to write my own module if it can be avoided.

If you want to use rules (and with commerce I think it makes sense), and you are comfortable with PHP, I would recommend writing your own module that defines the custom conditions and actions that you need to look up and apply discounts.

In my experience, the rules interface starts to break down quickly when use cases become even moderately complex. You can spend a lot of frustrating time fiddling with the interface, trying to get it to do what you want.

By writing your own conditions and actions, you keep the complex logic in code, where you can easily debug, access, and compare any information you might need.

In addition, your custom actions and conditions will be nicely exposed in the rules interface, and keep the high-level logic of your commerce solution tidy in one place.

Docs are here: https://drupal.org/node/298486. Drupal commerce itself has many good examples of custom actions and conditions to use as reference.


Add body class if a block is present I need to add a body class if a block or menu is present on the current page on Drupal 8. Probably this should be done on template_preprocess_page() or template_preprocess_html().

A block is visible in a page depending on two conditions:

None of the condition plugins associated to the block marks the block as not visible
The current user has the permission to see the block

Assuming the block is visible at a specific path is wrong because the current user could simply not have the permission to view it. Adding to that the fact that any third-party modules could define new condition plugins, the only way to avoid duplicating in code the block settings done from the user interface is using code similar to the following one.

function mymodule_preprocess_html(&$variables) {
  // Replace 'block_id' with the ID of your block.
  $block = Block::load('block_id');
  if ($block && $block->access('view')) {
    // The block is visible to the current user.
    // Replace 'the-class-to-add' with your CSS class.
    $variables['attributes']['class'][] = 'the-class-to-add';
  }
}

Remember to add the correct use statements on the top of the file containing that code (e.g. use Drupal\block\Entity\Block; to be able to access the block entity class).


How to use token in Global: PHP field In View, there is this field called "Global: PHP". I wonder how I can use token in this field in Drupal 7.  I can easily use token in "Global: Custom text" but not in "Global: PHP"

In a "Global: Custom Text" you will see a number of tokens listed under "Replacement patterns", such as [title], [php] (referring to a "Global: PHP" field), [nothing] (referring to another "Global: Custom Text" field), ...

These tokens (or replacement patterns), are not listed when working with a "Global: PHP" field, you can only see a list of "Available variables", and if you put a token in the "Output code" textarea, it does not get replaced.

However, there is a way to access these tokens in "Global: PHP" fields. For example, if you are trying to access the [nothing] token, put the following code in the "Output code" textarea (not in the "Value code" textarea):

<?php
$static = $view->display_handler->get_handlers('field');
echo $static['nothing']->last_render;
?>

Solution found here: https://www.drupal.org/node/507012#comment-3410296

Except it was for Drupal 6, so they used $this->view. In Drupal 7, you have to use $view.


User name who flagged in Global Node flag I have a global node flag where editors can flag the Node article as famous. There are more than 10 editors, so, I want to display in the node who flagged it and when. I used Views Relationships to get the flag data, I could easily get the flagged time but couldn't get flagged user. I tried with flag users relationship but it results in Anonymous user instead of the user who flagged.

Is there any way I can display the user who flagged it ?

For those who are in similar situation, I'd like to inform that at the time of writing, This is Not Possible with Flag. Flag module is just Boolean true/false.

I changed the flag to Vote using VotingAPI and Plus One modules. The VotingAPI has Views integration and via views Relationship, I could get the User information and Vote Timestamp to display in the page.


How can I update this db_query statement to db_insert for D7? I'm trying to update someone's module to D7, but I'm unsure of how to convert the usage of places and values in the query to use 7's api properly.

$fields = implode(',', array_keys($args));
$places = implode(',', array_fill(0, count($args), "'%s'"));
$values = array_values($args);

$insert_result = db_query(
  'INSERT INTO {bluga_request}(' . $fields . ') VALUES (' . $places . ')', $values
);

The standard way is to use the db_insert() function with an associative array of field names/values:

$fields = array(
  'id' => $id,
  'name' => $name
);

db_insert('bluga_request')->fields($fields)->execute();

It actually looks like in your case the fields are already set up as an associative array in $args so you would just do this:

db_insert('bluga_request')->fields($args)->execute();


Aegir redirect url to actual site I’d like to redirect the: aegir-server.com/a-site-url.com to a-site-url.com without hacking Aegir and based on a pattern so any future site will follow this type of redirect. Is it possible through Aegir?

(Aegir redirects the : aegir-server.com/node/site_id/goto_site to the site, but this is not what I need)

The easiest way would be to edit the .htaccess file of your hostmaster platform and add something like

RewriteRule ^(.*\.com) http://$1 [L,R=301]

Note that you have to reload apache as Aegir integrates the htaccess file into the vhost config.


Function in template.php to override Profile2 How can I make Profile2's overrides (profile2.tpl.php) work? Do I have to include a function "mytheme_preprocess_page" with "theme_hook_suggestions" in template.php?

I have crossed checked the suggested way on my local and I can see it working.Here are some pointers.I copied the profile2.tpl.php present inside profile2 module and paste it inside site default theme templates folder and finally clear the caches.In order to see what profile is working I added some test content on both templates and found content from profile2.tpl.php from my theme is working.

As a side Note:You can make theming experience far more easy using Theme Developer module,

  Firebug for Drupal themeing.Note that this module injects markers into
  the DOM to do its magic. This may cause some themes to behave
  erratically and less capable browsers may make it worse (especially
  IE)/. Enable it when needed, and disable it afterwards.


Jquery for form with multiple save/submit buttons I have created a form using fields with two action buttons; one for the default submit functionality ('Save'), and the other one for custom submit functionality ('Submit').

When the user clicks the submit button a confirm box is displayed asking the user whether he wants to submit the form or not. If the user selects yes, the custom submit callback for the button should execute.

I am using the jquery-alerts plugin to display a customized confirm box on the click event of 'Submit' button. I used the following jquery code for this

$('#recommendation-letter-node-form #edit-save').click(function() {
  jConfirm("Once you submit the application, you will not be able to modify it any further. Are you sure you want to submit?", "Application Confirmation Dialog", function(confirm) {
    if (confirm) {
      $(this).submit();
    }
  });
  return false;
});

the .submit() function doesn't work for buttons other than default form submit button and I need that the other button submit callback should be triggered when the confirm value is true.

One approach I used to achieved this was using the same callback function.  Then within this method, use $form_state['triggering_element']['#id'] or something similar to execute the proper function... i.e.

function my_form_submit($form, &$form_state) {
  $id = $form_state['triggering_element']['#id'];

  switch ($id) {
    case 'edit-submit':
      submit_my_form($form, $form_state);
      break;
    case 'edit-save':
      save_my_form($form, $form_state);
      break;
  }
}


Drupal Commerce order completes but reverts from pending to billing We are having issues where a Commerce Order will complete checkout, but once marked Paid in Full and set as Pending, it bounces back to Billing and Shipping (Shipping checkout page, name changed.)

Edit: We are using Authorize.net, no IPN.

Our checkout settings:

Checkout

Shopping cart contents
Coupons
Account Information

Billing and Shipping (default Shipping page, name changed)

Billing information
Shipping information
Shipping Service

Billing (empty, moved into previous page)
Review and Payment

Review
Payment

Most likely the order processing rules.

Look into whether your payment gateway is firing an IPN / notification which changes the order. If some orders process in a different order (eg some browsers varies in speed and fires checkout rules in a different order to the others) then you can see this sort of inconsistent behaviour.

Your checkout rules can permit EITHER the IPN or customer redirect to provide checkout notification - this can avoid showing some customers "we're awaiting confirmation from payment gateway". Just check order status and don't update an order which is already completed.

Your gateway may refer to IPN under another name. IPN requests can be discerned by the differing origin IP and authentication (if purchase is from a logged in user, but the above image is an anonymous purchase so not discernible there).


How to set default body message for Privatemsg embedded on page? This is the code I used on the node template and block, I just tried it both
module_load_include('pages.inc','privatemsg');
$recipients = array(user_load(arg(1)));
$subject = 'This is just a default that can be changed';
$body = 'Again, this is just a default that can be changed';
print drupal_render(drupal_get_form('privatemsg_new', $recipients, $subject, $body));
The Bold ones are the codes I added from the orginal code I got from here: https://www.drupal.org/node/624528
But I'm getting this message when I added the $body:

You can not reply to this conversation because all recipients are
blocked.

I've looked into the parameter of privatemsg and it says that the $body is the body text of the new message.
I would like to put some default body message on the embedded privatemsg.
I tried to edit the body via custom module, still no luck for me. I'm not sure where I went wrong.. here's the code on the custom module
function sassy_hook_form_privatemsg_new_alter(&$form, &$form_state, $form_id) {
   $form['privatemsg_new']['body'] = array(
    '#type' => 'textarea',
    '#title' => t('Message'),
    '#rows' => 6,
    '#weight' => 0,
    '#default_value' =>  t('Message'),
    '#resizable' => TRUE,   );
}

I also tried $form_state['values']['body'] = 'Hello World';
Is there any way to do this?
What am I missing?

Have a look at the descriptor of the privatemsg_new function in privatemsg.pages.inc:

privatemsg_new($form, &$form_state, $recipients = '', $subject = '')

It doesn't take a $body argument so you will need to alter the form once it has been created.

Make a custom module
Use hook_form_FORM_ID_alter
Set $form_state['values']['body'] to your desired value


Print random part of body I'd like to print (in Views - custom/PHP field) random part of body of a node, as a kind of teaser, different with every print.

Any ideas? Thanks! :]

Szy.

here you go: :)

$length = 50;

// strip html tags from body
$body = strip_tags($data->body);

// check that the body's actually longer than your snippet length
if (strlen($body) <= $length) {
  return $body;
}
else {

  // find a random starting point between the beginning and 50 chars from the end
  $max = strlen($body) - $length;
  $start = rand(0, $max);

  // set ellipsis variables
  $prefix = $start ? '...' : '';
  $suffix = ($start == $max) ? '' : '...';

  return $prefix . substr($body, $start, $length) . $suffix;
}


Need to count field specific value in Views Need to count field specific value in Views.
I have 2 content types "project" and "task" In the task i have reference field for project (assign task to project) And another field "task_status" as a list: closed / open

I want to calculate the closed and total tasks so i can get the results in percentage:
closed_task / total_task * 100
How can i get the count for closed tasks value ?

Sorry for my bad English :)

You first create  a views to show the list of  open or closed task.

create a views with content type  "project" remove all field  then add a relation on task referenced field ,add title field with consider that you select relation field for it (because we want load task title instead of project title) then add  filter   "task_status" equal to close,then enable exaggeration and on title.and finally for better result you can get the title(or nid ) of project with contextual filter . it help you you can get only the list of tasks form specified  project.( and finally create another page in that views with only one change,  status=open ).


Concept of services, tags, and arguments I defined a service using the following code.

services:
  redirect.repository:
    class: Drupal\redirect\RedirectRepository
    arguments: ['@entity.manager', '@database', '@config.factory']
    tags:
      - { name: backend_overridable }

According to my understanding, '@entity.manager' , '@database', and '@config.factory' are classes on which the service is dependent.

Now, the entity.manager service definition is the following.

class: Drupal\Core\Entity\EntityManager
parent: container.trait
tags:
  - { name: plugin_manager_cache_clear }

It has a tag associated with it. Maybe this tag manages all entity specific cache.

What is the responsibility of the redirect.repository services?
Does this service help communicating with the database directly?
What if I don't have any entity and I implemented hook_schema()? Can I mention my custom database table name instead of @entity.manager?
Where do these tags actually get registered?

1. Database

redirect.repository communicates with the database through its usage of the class represented by the database service injected into its initialize method (__construct). However the RedirectRepository class does not itself use PDO to connect to the database.

The redirect module has chosen not to implement an entity to store its data, and is an example of using Drupal's database abstraction layer (DBAL) from the database service.

// Load redirects by hash. A direct query is used to improve performance.
$rid = $this->connection
  ->query('SELECT rid FROM {redirect} WHERE hash IN (:hashes[]) ORDER BY LENGTH(redirect_source__query) DESC', [':hashes[]' => $hashes])
  ->fetchField();

2. Entity Manager

The entity.manager service provides a deprecated helper class to make it easier to get information about entities only. If you do not implement an entity, then you cannot use any of the entity-related services such as entity.manager or entity_type.manager.

3. Dependency Injection Tags

  Dependency Injection Tags are little strings that can be applied to a
  service to "flag" it to be used in some special way. For example, if
  you have a service that you would like to register as a listener to
  one of Symfony's core events, you can flag it with the
  kernel.event_listener tag.

Tags are treated specially so that when the service container is "compiled" certain classes may be able to make a second "compiler pass" and act on services that are tagged.

See the Symfony2 documentation for more details about compiler passes: http://symfony.com/doc/current/components/dependency_injection/compilation.html#components-di-separate-compiler-passes


PDOException: SQLSTATE[42S02] After I clicked to create a new content type, I got this message.

  PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'bis301.cache' doesn't exist: DELETE FROM {cache} WHERE (cid LIKE :db_condition_placeholder_0 ESCAPE '\') ; Array ( [:db_condition_placeholder_0] => entity_info:% ) in cache_clear_all() (line 168 of C:\xampp\htdocs\bis301\includes\cache.inc).

How can I fix this problem?
Help me please.....

Seems that's the problem with the cache table. If you're running localhost. Just drop the existing cache table and recreate it.
Following is the query to create 'cache' table for drupal 7

CREATE TABLE `cache` (
 `cid` varchar(255) NOT NULL DEFAULT '' COMMENT 'Primary Key: Unique cache ID.',
 `data` longblob COMMENT 'A collection of data to cache.',
 `expire` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry should expire, or 0 for never.',
 `created` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry was created.',
 `serialized` smallint(6) NOT NULL DEFAULT '0' COMMENT 'A flag to indicate whether content is serialized (1) or not (0).',
 PRIMARY KEY (`cid`),
 KEY `expire` (`expire`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Generic cache table for caching things not separated out...'


Drupal 7 - Passing Arguments from Page Manager/Panel to embedded view/reference field Drupal 7: I try to pass an argument (eg node:title) from panels/page manager to use as filter criteria in an embedded view.In the view I want to fetch this argument as a filter criteria to a reference field.

In Panels I can define pass arguments, but how can I fetch and compare them in the view?

It sounds like you want to pass contexts from panels to a view. If that's the case, see my answer on Send a context from a panel page to a view integrated in it?

If you want to pass arguments (dynamically added by changing the URL to your panels page) to a view, then in the view panes settings, make sure to check Send arguments. You can then access the arguments in the view using Contextual Filters as if it were a regular views page.


How to print fields in node.tpl.php? I need to print individual fields from the $content variable in node.tpl.php file in separate div tags. How do I do that and how do I find out what the field's names are?

Try this

<?php print render($content['your_field_name']); ?> this will print that field value .


Leaflet: how to display a unique marker per map Normally people want to add multiple markers to a single map. In my case I'm attempting almost the opposite - create two maps from the same content type and using Leaflet assign each a unique marker to each. Try as I might I can't figure out how to do this. Instead, what happens is that both markers are displayed on either map (rather than one per map).

My current setup it like so -

Content type

Has a geofield set to output Lat/ Long coordinates

Page

Two pages based on the above content type (let's call them Page Map A and Page Map B) each have a unique set of coordinates.

View

Individual View block for Page Map A and also for Page Map B. These are set
to output the geofield data

(I originally had one View block and I was hoping that splitting them in two would solve the issue. It didn't.)

Block

In blocks the View for Map A and the View for Map B is set to display only on their respective pages

Both of the Views are ordered by sort date (which might be the source of the problem) and only show 1 item. However, if only one item is set to show then it's always the marker for Page Map B that's displayed. Furthermore, if I increase the display to show 2 or more items then the popup text for both markers will only appear on Page Map B, and there are no popups for Page Map A.

I would use a contextual filter (Advanced settings column) based on the content NID (node identifier). You will get a settings window where you choose "Provide default value" and Type : Content ID from URL (the nid is always available from URL even if you use an alias). Then, the Leaflet map will be filtered using this NID and you will get only one marker (display all results and remove your sort date) created with coordinates entered for this specific content (page). Finally, you will need only one block with this contextual filter, since it will be automatically modified according to page URL.

Hope this helps.


How can I add Taxonomy Term to a Node's Breadcrumb? The Node has attached a single Term.

Current breadcrumbs rendered

[HOME] >> [NODE_TITLE]

Want to render like this.

[HOME] >> [TERM] >> [NODE_TITLE]

Themers who don't want to use a custom module to implement a BreadcrumbBuilder can change the breadcrumbs in a preprocess hook.

Example how you can add a link before the last link:

function mytheme_preprocess_breadcrumb(&$variables) {
  $breadcrumb = &$variables['breadcrumb'];
  $lastlink = array_pop($breadcrumb);
  array_push($breadcrumb, [
    'text' => 'New Link',
    'url' => '/newlink',
  ]);
  array_push($breadcrumb, $lastlink);
}

If you add a taxonomoy term from a node you would have to add both as cache tags and a cache context on the url to make this work.


How do I check by default a checkbox from a checkboxes control after an AJAX call I have the next form which behavior is:

When you select an option from select control, different checkbox are load on checkboxes control.
When you check/uncheck checkbox a message is showed on the botton with info about select value and checkbox clicked.

Everything works fine, but is impossible check by default a checkbox from checkboxes control after ajax function.

Any idea?

namespace Drupal\drupal_miseries\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element\Checkboxes;

class CheckboxesAjax extends FormBase {

    protected $values = [
        'select' => [
            '1' => 'Value1',
            '2' => 'Value2',
        ],
        // Options when select 1 is selected
        'checkboxes_v1' => [
            '1' => 'checkbox1',
            '2' => 'checkbox2',
        ],
        // Options when select 2 is selected
        'checkboxes_v2' => [
            '3' => 'checkbox3',
            '4' => 'checkbox4',
        ],
        // Default values for checkboxes
        'checkboxes_df' => [
            // Default value when checkboxes_v1 is showed
            '1' => ['1' => '1', '2' => '0'],
            // Default value when checkboxes_v2 is showed
            '2' => ['3' => '0', '4' => '1'],
        ],
    ];

    public function getFormId() {
        return 'drupal_miseries_checkboxesajax';
    }

    public function selectAjaxCallback(array &$form, FormStateInterface $form_state) {
      return $form['container'];
    }

    public function checkboxesAjaxCallback(array &$form, FormStateInterface $form_state) {
      $checkbox = $form_state->getTriggeringElement();
      $select = $form_state->getValue('select');

      $form['status']['mensaje'] = [
          '#markup' => 'Select: '.$select.' '.$checkbox['#title'].' clicked.'.'',
      ];

      return $form['status'];
    }

    public function buildForm(array $form, FormStateInterface $form_state) {
      $form['select'] = [
        '#type' => 'select',
        '#title' => $this->t('Select form control'),
        '#options' => $this->values['select'],
        '#default_value' => key($this->values['select']),
        '#ajax' => [
            'callback' => [$this, 'selectAjaxCallback'],
            'wrapper' => 'checkboxes_wrapper',
        ],
      ];

      $form['container'] = [
        '#type' => 'container',
        '#attributes' => ['id' => 'checkboxes_wrapper'],
      ];

      $form['container']['checkboxes'] = [
        '#type' => 'checkboxes',
        '#title' => $this->t('Checkboxes form control from select @select',
          [ '@select' => empty($form_state->getValues()) ?
              $this->values['select'][key($this->values['select'])] : $form_state->getValue('select') ]),
        '#options' => empty($form_state->getValues()) ?
          $this->values['checkboxes_v1'] :
          $this->values['checkboxes_v'.$form_state->getValue('select')],
        '#default_value' => empty($form_state->getValues()) ?
          $this->values['checkboxes_df']['1'] :
          $this->values['checkboxes_df'][$form_state->getValue('select')],
        '#ajax' => [
            'callback' => [$this, 'checkboxesAjaxCallback'],
            'wrapper' => 'status',
        ],
      ];

      $form['status'] = [
        '#type' => 'container',
        '#attributes' => ['id' => 'status'],
      ];

      return $form;
    }

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

    }
}

Thanks @IvanJaros, i have read it and i think i'm doing everything fine but i can't understand why is not working.

I have modify selectAjaxCallback to solve this problem:

public function selectAjaxCallback(array &$form, FormStateInterface $form_state) {
      $select = $form_state->getValue('select');

      foreach ($this->values['checkboxes_df'][$select] as $key => $value) {
        $form['container']['checkboxes'][$key]['#checked'] = $value;
      }
      return $form['container'];
    }

This code works, but i'm not sure if it's the right way to solve this problem.

Thanks.


node title preprocess_views_view_field(); I want to save the node title in a variable using: themename_preprocess_views_view_field(), becuase I want to print a the node title above the field.

But when I try to save the title with:

themename_preprocess_views_view_field() {
$variables['node_title'] = $variables['field']->original_value ->    string;
}

I get Error: Cannot access protected property Drupal\Core\Render\Markup::$string in themename_preprocess_views_view_field() (line 123 of themes/custom/themename/themename.theme).

how can I save this variable so I can print it in the views-view-field.html.twig file?

Solution: The way to do this is to add an address Field in the View as Content datasource: address in the Admin GUI.

And select Use entity field rendering.

Under REWRITE RESULTS
 Select: Override the output of this field with custom text

And in the textbox I added in my case:

{{ title }}
{{ field_address }}


Low Maximum execution time I was installing drupal commons on xampp server i got this error, PHP Max Execution Time 30 Your PHP execution time is too low, please set it greater than or equal to 120 seconds. How do i adjust the php execution time so that i can proceed with the installation?

Follow  below steps and change that file.

Go to your XAMPP installation Folder and edit - ..\xampp\php\php.ini file.
Use the FIND function of your editor an look for "max_execution_time"
in that line you will see the value attributed to "max_execution_time"
change it to max_execution_time=120
Save the php.ini file.
Restart the XAMPP Server
Proceed with Drupal Commons installation.


how to add color field after Commerce Fancy Attributes has been installed? In my website I used drupal commerce, and I would like to display product my its color in product display page. This is the link I reference https://www.drupal.org/project/commerce_fancy_attributes, I have successfully installed that module. That guide said create a 'Color' vocabulary, add a text field called "Color" that will hold hex values. But I can't find the 'hex' in field type. So I can't continue the next step. I would appreciate any suggestion you could give me.

Thanks

You should create a simple "text field".


Is it possible to attach my own datetime class for using it in fields? For example, there is a situation, where I need to output date field in some another format. But this format is not supported by PHP.

For example, I want to output year value in Roman numerals format.
Or, I want to calculate year not from the Christmas, but from "the Creation of the world", from foundation of Rome ans so on.
Or "the week" in my calendar doesn't contain 7 days, but it contains another quantity of them.

In this case, if I'm not mistaken, I should create new class inheriting it from DateTime class and there redefine method format or do something else.

Can I afterwards notice Drupal to it use my own DateTime class instead default ?
That is, for instance, I have created new DateTime field for some node type and I can set my date format for this field in the admin date settings page, in Views and so on.

Is it possible in Drupal 7 ?
And is it possible in Drupal 8 ?
If yes, how to do it ?

In your case, you do not need to define a new field type, you just need to write a new field formatter.

In Drupal 8, field formatters are used for displaying fields when displaying the parent entity (eg, a node view page) and when used in a view (even with field output).

Field formatters are easy to write in Drupal 8. In you case you just create a new plugin, and you can likely just extend one of the existing ones.  I suspect something like this would work for you

namespace Drupal\mymodule\Plugin\Field\FieldFormatter;

use Drupal\datetime\Plugin\Field\FieldFormatter\DateTimePlainFormatter;

/**
 * Plugin implementation of the 'Awesome' formatter for 'datetime' fields.
 *
 * @FieldFormatter(
 *   id = "mymodule_datetime_awesome",
 *   label = @Translation("Awesome"),
 *   field_types = {
 *     "datetime"
 *   }
 *)
 */
class AwesomeDateTimeFormatter extends DateTimePlainFormatter {

  /**
   * {@inheritdoc}
   */
  protected function formatDate($date) {
    // Do something awesome!
  }

}

Here, the DateTimePlainFormatter does all of the heavy lifting via inheritance and you just override the method that actually produces the date string to be whatever you need.  You can then use this on Manage Field Display, and other places you can choose a field formatter.

In Drupal 7, you can also just create a field formatter, but the process is more involved.  You would also need to create a views field output plugin, as Drupal 7 / Views 3 does not use field formatters with field output.


hook_preprocess_html(&$vars) not firing I am attempting to add css classes to the body depoendant on what the page contains.

I am using the following...

function myTheme_preprocess_html(&$vars){
    //code here
    //eg.
    $vars['classes_array'][] = 'a-new-class-for-a-node';
}

I cannot get this to fire or add anything to the page. It will not drupal_set_message, echo or more importantly add any classes to the body tag.

What am I doing wrong here please? I am using Drupal 6.

I might be terribly wrong here, but there appears to be no such hook for Drupal 6. If so, it will never fire.

See https://api.drupal.org/api/drupal/6/search/hook_preprocess_html.

Perhaps you're backporting a theme from D7?


How to add country suffix to the hreflang tags? I am working on a multilingual site. In which I am using Alternate hreflang module and everything working as expected.

But it should look like

    <link href="/es" rel="alternate" hreflang="es-ES" />
   <link href="/es" rel="alternate" hreflang="es-MX" />
    <link href="/es" rel="alternate" hreflang="es-AR" />

Means in hreflang need to add country name as suffix like es-ES, es-MX etc.

Tried like below but its not working.

This cannot be achieved in the Alternate Hreflang module or any other Drupal module. They all use the language code as the hreflang code which is incorrect as hreflang contains 2 parts - the language "es" and the country "ES" (Spanish, Spain) or in your example es-MX (Spanish, Mexico).

I've had three or four contributors (metatag, Alternate Hreflang) come back to me and state that you need to create custom languages for this to actually work. So for Mexico create a new language and use the code es-MX then this will show the appropriate hreflang code es-MX. However it will
a) create an unnecessary language
b) probably require Language Hierarchy to avoid superflouous translations
c) also show in the URL as es-MX which in my opinion is also not ideal (the MX is in UPPERCASE and the URL will always be flattened to lowercase on output not ideal for SEO or asthetics...)

Off the shelf them's your options me thinks.

I would suggest coding some simple patch to the Alternate Hreflang module to include the ISO list of country codes so through a UI you could add whatever country you liked alongside the any enabled language into the hreflang code.


Character counter for textarea in webform I am relatively new to drupal. I have webform module and webform validation module installed. I was able to limit the number of characters in webform textarea using webform validation. However, this module does not support character counter for the fields. I have looked at this solution http://drupal.org/node/1459650#comment-5699952 which using maxlength module, but it is very unclear . I am planning to write a module implement hook_webform_component_info_alter(&$components) to add jquery or javascript on to the webform textarea field. Is this a correct way. If so or If not how would i do that?

For webforms use the Webform Countdown module instead of maxlength. Here is a quote about it (from the module's project page):

  Provides a textarea component for Drupal webforms with a configurable, twitter-style dynamic word or character count.


Page titles are wrapped in a span tag On a site we are working on I was asked why the page titles are wrapped with a span tag. We are not using a base theme.
I checked everywhere I could think of, but came up short.
In page-title.html.twig:
{#
/**
 * @file
 * Theme override for page titles.
 *
 * Available variables:
 * - title_attributes: HTML attributes for the page title element.
 * - title_prefix: Additional output populated by modules, intended to be
 *   displayed in front of the main title tag that appears in the template.
 * - title: The page title, for use in the actual content.
 * - title_suffix: Additional output populated by modules, intended to be
 *   displayed after the main title tag that appears in the template.
 */
#}
{{ title_prefix }}
{% if title %}
  <h1{{ title_attributes }}>{{ title }}</h1>
{% endif %}
{{ title_suffix }}

At this point, title is a render array. It is passed in as a Markup object. Where is this happening?
The span doesn't hurt anything, but at this point I just want to find where that is occurring. Is there an option to switch that off? I can preprocess_page_title and strip tag it, but unless there is a good reason, I would rather not have it at all.

This is probably not the case for all pages? I think what you see is the rendered result of an entity field like for example this node field template:
field--node--title.html.twig:
<span{{ attributes }}>
  {%- for item in items -%}
    {{ item.content }}
  {%- endfor -%}
</span>

In other cases when the title is not bubbled up from the rendered main content and it is taken from the route definition there shouldn't be a span tag unless there is a title callback placing such a tag.


Drupal Commerce Paypal: Order information at Paypal I am using drupal commerce paypal. When a client is directed to the paypal site, then by default this information is shown: Order  at .

How can I configure the information shown here?

thanks for any help

The only way to change that is through an alter hook documented in the module commece_paypal_wps.


Adding CSS Class To Unread Comments Hello im sure that this would be possible from my experience of drupal. I have threaded comments. People who reply to comments up the thread have their comment up next to the comment they replied to. My members seem to miss these comments when viewing the thread. Is it possible to add a css class or something so as unread comments are a differant colour?

Thanks

It should wrap new comments in a comment-new class already, but if your theme does it differently, you could edit its comment.tpl.php or copy comment.tpl.php from the comment module to your theme and act upon the $comment->new value to wrap it differently yourself.


How do I move a Drupal site from WAMP server to a live server? I'm a newbie with this so am having quite a bit of trouble. I've created a Drupal site in WAMP Server and am raedy to move the site to my hosting with Heart Internet.

I've copied C:/Wamp/www/mywebsite into a zip folder and uploaded/unzipped into my hosting space so the files are uploaded successfully.

I then went into phpMyAdmin on my computer and exported my database. I then created a blank database on my web hosting on the live server. this database username is c150-drupal and i generated a random password. I then clicked 'restore' on my new blank database and selected the database that I exported from WAMP. however I keep getting the error message below:

ERROR 1044 (420000) at line 22: access denied for user 'c150-drupal'@'%' to 'postcodedatabase'

I'm so confused how I should be exporting mysql databases in order to upload them to my webserver. Also is it acceptable to export a database from WAMP in order to use as a backup incase anything goes wrong so I could import the database back into WAMP?

Thank you,.

You should check your user privilege on your production server because you can't do this action.

This thread deals with your problem : https://stackoverflow.com/questions/8838777/error-1044-42000-access-denied-for-user-localhost-to-database-db


Drupal Leaflet View loading view block through Ajax I created a view block for displaying geocodeed nodes on a View Leaflet map.
Everything working, the map displays the markers as I want.
Now, I would like to load this map throught drupal ajax

I attached the leaflet libraries to the page.
Then I load the view with:

$view = Views::getView('map');

$view->setArguments($args);
$view->setDisplay('block');
$view->preExecute();
$view->execute();
$content = $this->renderer->render($view->render());

$response->addCommand(
    new HtmlCommand('.result__map', $content)
 ));

The $content contain only an empty div generatated from the view and when the response is instered in the Dom nothing happen.
I suspesct that the map is missing some JS trigger to instanciante the map and maybe some JS settings.

Could someone send me an example or point me in the right direction.

You must use the ViewExecutable::buildRenderable function.

Instead of:

$content = $this->renderer->render($view->render());

You must do like this:

$content = $view->buildRenderable('block', $args);


Row weights on taxonomy On my live site I am unable to see the drag and drop functionality only on taxonomy, whereas it is successfully appearing on menus.Below is my screen shot for taxonomy.

It should be like this:

Can any one have idea about this?

Try enabling Aggregate JavaScript files option at admin/config/development/performance.
Sometimes that resolves this type of issues

Here is the screenshot


Re-authenticate a user with X-CSRF-Token I am writing an Android application that consumes the Drupal 8 REST features. I have managed to write REST resources and make API calls with the android app to these resources with success.
My question is about the login and sessions. When the users logs in for the first time we get X-CSRF-Token, which has an expiration date. I also use this token to authenticate myself when making calls to the REST resources.
Does Drupal has a REST feature that refreshes the token without having to enter the user credentials again?
The idea is to have an app on which you log in only once until the users logs out manually.

Rasjaad, You can use android account manager https://developer.android.com/reference/android/accounts/AccountManager for this purpose

Here is a sample Drupal 8 Android app code that uses account manager to reauthenticate. https://github.com/onedrupal/One-Drupal-Android

https://github.com/onedrupal/One-Drupal-Android/blob/master/app/src/main/java/com/technikh/onedrupal/activities/ActivityAuthentication.java
At the launch of the activity AccountManager.getAuthTokenByFeatures is called

mAccountManager.getAuthTokenByFeatures(AccountUtils.ACCOUNT_TYPE, AccountUtils.AUTH_TOKEN_TYPE, null, this, null, null, new ActivityAuthentication.GetAuthTokenCallback(), null);

Here is the AccountAuthenticator  https://github.com/onedrupal/One-Drupal-Android/blob/master/app/src/main/java/com/technikh/onedrupal/authenticator/AccountAuthenticator.java

authToken = AccountUtils.mServerAuthenticator.signIn(site_protocol+site_domain, account.name, password);


Prevent WYSIWYG+CKEditor from stripping html classes I'm using WYSIWYG editor with CKEditor. I'm finding that when adding custom classes to my elements from the "source" view, CKEditor strips those classes when switching out of the source view.

When googling for a solution to this, I found the CKEditor module page which describes how to fix this when using CKEditor alone. (Basically, we need to set up a JS config config.allowedContent = true in its Advanced Content Filter settings).

However, when using CKEditor via WYSIWYG, these settings are not exposed in the admin interface. How do you achieve the same when using CKEditor via WYSIWYG?

PS: I cannot use CKEditor alone because it does not integrate with the media plugin.

I found a solution.

This turns off the filtering, it's working, but not a good idea...

config.allowedContent = true;

To play with a content string works fine for id, etc, but not for the class and style attributes, because you have () and {} for class and style filtering.

So my bet is for allowing any class in the editor is:

config.extraAllowedContent = '*(*)';

This allows any class and any inline style.

config.extraAllowedContent = '*(*);*{*}';

To allow only class="asdf1" and  class="asdf2" for any tag:

config.extraAllowedContent = '*(asdf1,asdf2)';

(so you have to specify the classnames)

To allow only class="asdf" only for p tag:

config.extraAllowedContent = 'p(asdf)';

To allow id attribute for any tag:

config.extraAllowedContent = '*[id]';

etc etc

To allow style tag (<style type="text/css">...</style>):

config.extraAllowedContent = 'style';

To be a bit more complex:

config.extraAllowedContent = 'span;ul;li;table;td;style;*[id];*(*);*{*}';

Hope it's a better solution...


Webform Radio buttons are not getting "radio-checked" class when clicked on I've developed webforms before where I set a component to "Select options" and the design has required these options to look like buttons, so with a bit of simple CSS, we can achieve this:

form .form-radios label{background-color:#bebebe; border-radius:3px; margin-right:5px; border: 1px solid #b6b6b6; padding: 10px; text-align: center; color:#232323;}
form .form-radios label{float: left; width:200px;}
form .form-radios label .form-radio {xposition: absolute; xleft: -99em;}

(the prefix "x" added to the last 2 styles are obviously removed before deployment, it's just so I can see the radio buttons)

Now, when I click on the pretend buttons, they usually gain the class "radio-checked" as per this example on a previous site I've built https://www.feelthepulse.co.uk/request-callback

However, it doesn't work on my current build (you click the button, but no extra classes are added). I've looked for any modules I might have forgotten about, and I can't see any options for the webform regarding ajax or anything.

Has anyone else had this problem, or know what I'm missing ?

After a bit more digging, it appears it's my memory that has failed me. This functionality is provided by Javascript.
So I'm placing my solution here in case anyone would like to make their select options look like buttons.

You have my CSS above.  Next you need to add a javascript folder & file in your sites> all >themes > [theme_name] directory.

I've placed a new folder and file in the above path :  js > webform_tweaks.js

Inside the webform_tweaks.js file, place this code:

(function($) {
  // DOM ready
  $(function(){
    // add a radio-checked additional CSS class to the parent label
    $(".webform-client-form .form-radios input").click(function(){
      $(this.parentNode.parentNode.parentNode).find('.form-item .control-label').removeClass('radio-checked');
      $(this.parentNode).addClass('radio-checked');
    });
  });
})(jQuery);

You need to reference this javascript file in your [theme_name].info file (found in the root of your sites> all >themes > [theme_name] directory.)

Open that file and add:

scripts[] = js/webform_tweaks.js

You will also need to flush your CSS & Javascript caches before you see the change.

Hopefully, now you should be able to click on your "pretend" button and apply a style to it using this new "radio-checked" class and make the button looked clicked by adding a background colour or something to it.


Private files won't be saved anymore in their intended location? (D7) I've got a D7 installation for some time now, with a content type that has a "private file" field.

It was working just fine up until now.

My files usually got uploaded like:
http://....com/system/files/curso/file.txt
And they get saved inside: .../files/private/Private - accessible only to group members/[nodeid]/file.txt

Now I've created a new node with an uploaded private file: demo.txt

When its downloaded it gets this path:
http://....com/system/files/curso/demo_1.txt

But I get "Not Found" when I click it because it gets saved in other location (?): .../files/private/curso/demo_1.txt

Notes

The _0, _1 etc are automatically added to the files when they are saved into the node.
I've tried accessing the file from its real location (.../files/private/curso/demo_1.txt) with no luck.
The "files" folder is directely inside public_html because the original setting was that way (the site comes from a D4.7, D5 and then  a D6 installation).
It worked just fine with other files up until now. I've not done anything special (like installing new modules), except creating a few new node types and rebuilding the permissions.

What could I do? (BTW, I've read this information, and sadly it didn't helped).

Update - Error Logs:

[Mon Mar 02 12:37:40 2015] [error] [client 181.28.74.188] client denied by server configuration: /home/sitio/public_html/files/private/curso/demo_1.txt
(I've found more info about this here)

You spoted your problem in your apache log file : Apache is forbiding access.

You have 2 options here :

If you want apache to allow access to these files then add this to apache conf file :

<Directory /home/sitio/public_html/files/private/curso>
  AllowOverride None
  Order Allow,Deny
  Allow From All
</Directory>

then restart apache and I guess you should be ok to access your file.

But if you want these files to be private then you want to restrict access rather than open it, so

Alternatively,

you let apache restrict access to these files, and you set drupal serve these files via alternative drupal-generated links. Check the documentation for setting up access to private files here, look for the section on "Accessing Private Files".

If you've got no .htaccess file for the folder as you said then create one with :

Deny from all
Options None
Options +FollowSymLinks


Log in with email address only I am looking for a concrete way to only allow logging in with email address only in Drupal 8.

I have seen Login Email and Login EmailUsername modules, but both still allow for username login as well as email.

I am looking only for email.

So far, I have come up with this in the interim - but something is not quite right. While I can trigger a form error, the form still submits and authentication is called. It should not submit if the entered value does not resemble an email address:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_user_login_form_alter(&$form, FormStateInterface $form_state) {
  $form['name']['#type'] = 'email';
  $form['name']['#title'] = t('Email Address');
  $form['name']['#description'] = t('Enter your email address.');
  $form['name']['#element_validate'][] = 'mymodule_login_validate_user';
  $form['pass']['#description'] = t('Enter the password that accompanies your email address.');
}

/**
 * Custom validation handler for the form login.
 *
 * @param $form
 * @param $form_state
 * @return bool
 */
function mymodule_login_validate_user(&$element, FormStateInterface $form_state) {
  $email_input = $form_state->getValue('name');

  if (!\Drupal::service('email.validator')->isValid($email_input)) {
    $form_state->setError($element, 'Please enter a valid email address.');
  }
}

I am also overriding the core user.auth service with my own - I will be generating usernames based on factors about the user (fetching information from a remote AMS).

Is there any way to avoid username in Drupal 8?

edit: Users cannot register on the Drupal site, and forgot password will be replaced with a link to the external AMS system.

It seems Login with Email only should solve that. At least worth a look how they managed to do that.

  This simple Drupal 8 module allows users to log in exclusively with
  their email address from the standard login form.

  Setup:

  Just enable the module.

  Recommended Modules:

  This module is based on the Login Email or Username module:
  https://www.drupal.org/project/login_emailusername


What is the specificity limit of EntityFieldQuery / fieldCondition? I have a webform that I want to grade, like a quiz. (No, not with the Quiz module).
I have a content type called Answer Key with a Reference field called field_answer_quiz.
Upon webform submission, I want to:

Look through all nodes of type Answer Key
Find the one with a field_answer_quiz value == the current webform
Use node_load() or something to pull out content

Here's a Q&A that makes it seem possible: how to extract values of field collection using Entityfieldquery?

But here's a comment that makes it seem impossible:

  If that's what you want, then this is the correct way and EntityField does not help you. What EntityFieldQuery does is load entity IDs of entities based on their properties and fields. You could for example use it if you want to load the node(s) that has a specific version value by first loading the field collection item and then loading the node that references the field collection item. You're doing the opposite, you have the node and want the version value. To get field values, you always need to load the entities.

So, which is it? Is it going to be possible for me to use EntityFieldQuery to do this? I'd really like to avoid having to load a ton of nodes just to shuffle through them.

This is the code I am using.

function webformta_webform_validation_validate($validator_name, $items, $components, $rule) {
$arg = arg();
$nid = $arg[1];
dsm('The NID of the current node is '.$nid);
$query = new EntityFieldQuery;
$result = $query
    ->entityCondition('entity_type', 'node')
    ->propertyCondition('status', 1)
    ->propertyCondition('type', 'quiz_answer_key')
    ->fieldCondition('field_answer_quiz_nid', 'value', $nid, '=')
    ->execute();
    $results = $query->ordered_results;
  dsm($results);

It causes the following error:

  PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'field_data_field_answer_quiz0.field_answer_quiz_value' in 'where clause': SELECT
  [...] (error is really really long)

Yes, it is possible.

The second question is different, what you are describing is exactly what EFQ can do.

Something like this should work:

->fieldCondition('field_answer_quiz', 'nid', $nid)

The column names in the field tables are a combination of the field name and the column name, you need to split that up like the above example.


Is hook_translated_menu_link_alter() thought to be used only on translated menu links? Could hook_translated_menu_link_alter() be implemented to simply alter a menu link before it is rendered?

Clearly, hook_translated_menu_link() is only invoked for menu items that have been flagged from hook_menu_link_alter() as altered; if a module uses hook_translated_menu_link() to alter a menu item before it is rendered, it needs to implement hook_menu_link_alter() too.

Take a look at Devel, it uses hook_translated_menu_link() along with hook_menu_link_alter() to add a destination query to the end of a few of the links.

http://drupalcode.org/project/devel.git/blob/0ca6cc9bd5e2cf650717b73e8938b88726d0ebbd:/devel.module

Line #331 - devel_menu_link_alter()
Line #342 - devel_translated_menu_link_alter()


Iterate through all children of an element I have a Drupal code below:

function myid_create_template($form, &$form_state){
    $form['myid_templates_editor']['#access'] = TRUE;
    foreach (element_children($form['myid_templates_editor']) as $child1)   {
        $form['myid_templates_editor'][$child1]['#access'] = TRUE;

    }
    return $form;
}

This code iterate to the first child only of an element, but not the child with degree 2 or more. How will I iterate it to all child/grandchild of the element?

A simple recursive function will do the trick:

function allow_access(&$root_element) {
  $root_element['#access'] = TRUE;
  foreach (element_children($root_element) as $key) {
    allow_access($root_element[$key]);
  }
}
allow_access($form);


How to include a juery ui file in drupal 7? In my code for drupal 6 I had added the following js, jquery-ui and css files

 jquery_ui_add('ui.draggable');
  drupal_add_css(drupal_get_path('module', 'ort') . '/js/jquery.alerts.css');
  drupal_add_js(drupal_get_path('module', 'ort') . '/js/jquery.alerts.js');
  drupal_add_js(drupal_get_path('module', 'ort') . '/js/ort.js');

For drupal 7 I have to write the above code..
I have read that drupal 7 has jquery ui as part of core so how should add the

jquery_ui_add('ui.draggable'); //drupal 6

code given above in drupal 7 ?

It should be drupal_add_library('system', 'ui.draggable');


How to hide specific term/field value on the node? Is there a way to hide a specific taxonomy terms (specific field values) on the node? (not hiding field/vocabulary altogether, just some values).

For instance, there is vocabulary "Location" with a stucture like:

Europe

England

London

France

Paris

On the node view I need to hide terms "Europe", "England" and "France" and display "London" and "Paris" only.

Each term has a level. So if you want to show only the terms from level 2 (London, Paris) you could loop over your terms, check the level and hide if its not 2. If you need to have individual rules for hide / show, then you could add a field to the term where you can save a value to show or hide and use this in your loop.


Stylize book index with images Intro:  In the root page of the book, there's an index on the bottom that lists all the child pages.  There are also links to previous and next page in each of those child pages.  Not sure what the correct terminology is for that index.

My problem:   What I would like to do is to completely re-design those links.  Since the book contains mostly videos, I want each link to have a thumbnail of those videos.  Of course, I would modify the content type of the page to upload that thumbnail image.  If I could replace those pages with a panel and a view block for example, that would completely solve the problem. (but not sure if it's possible to create such view to list the child nodes)

Question:  Is there a module to redesign those indexes and/or what are the templates I would need to modify to do that?  Thanks!

Note: Using Drupal 7.  Not a newbie, but not an expert either.

You actually don't need a module to do this

The previous/next links can be directly modified by 'just' overriding the file modules/books/book-navigation.tpl

<?php if ($has_links): ?>

      <?php if ($prev_url): ?>
        <a href="<?php print $prev_url; ?>" class="page-previous" title="<?php print t('Go to previous page'); ?>"><?php print t('‹ ') . $prev_title; ?>
      <?php endif; ?>
      <?php if ($parent_url): ?>
        <a href="<?php print $parent_url; ?>" class="page-up" title="<?php print t('Go to parent page'); ?>"><?php print t('up'); ?>
      <?php endif; ?>
      <?php if ($next_url): ?>
        <a href="<?php print $next_url; ?>" class="page-next" title="<?php print t('Go to next page'); ?>"><?php print $next_title . t(' ›'); ?>
      <?php endif; ?>

<?php endif; ?>

this is also described a bit more detailled in this answer to a very similar question:

Next/Previous button for nodes within a book

The book tree is quite a bit more complex.
A good start would probably be to look at the functions template_preprocess_book_navigation and book_children and menu_tree_output and then override the parts you want to 'style' (theme) in your template.php – but that can be tough.

I ran into a similar problem a while ago – and not using the book module was the solution for me. Instead I dived into Entity reference and found it a way more flexible approach than using and theming the book module.


How to order nodes with a number like 1.1.1 I have a long list of files to be downloaded with different categories.

So I created a node for each file.

And assigned a term field for the categories

A file can be used in different categories so I cant sort by posted date or the order might be wrong.

Is it possible to create a text field on nodes and then order them in a view based on that number? Example

1.1.1
1.1.2
2.1.1
2.1.2

Views Natural Sort might work for this but I can only get it working on titles.

You can do this with hook_views_query_alter(). I had a similar requirement few time ago where i have to sort nodes where title those have numbers should display before the nodes those have alphabets.
Here is a snippet i created at dropbucket.rog

http://dropbucket.org/node/1484

Steps:

Add one new text field to the content type you using for files. use textfield because integer or float type field will not allow you value in format 1.1.1.
Create a view.
Add a sort criteria the field you added either desc or asc. because you are going to alter this in hook_views_query_alter().

I tried with textfield name "sort". Change the field name whatever you use in content type, in query alter. You can get field name in view query display if query display is enabled in views settings.

Create a custom module.

function custom_views_query_alter(&$view, &$query) {
  if($view->name == 'your_view_name'){
      // Remove all the sort order fields.
      $query->orderby = array();
      // Show number before the alphabets in titles.
      // This is trick which add 0 to the field to cast it to number then check the not equal to condition.
      $query->orderby['0']['field'] = 'field_data_field_sort_field_sort_value+0<>0';
      $query->orderby['0']['direction'] = 'DESC';
      $query->orderby['1']['field'] = 'field_data_field_sort_field_sort_value';
      $query->orderby['1']['direction'] = 'ASC';
  }
}


Auto-complete and form auto-populate from wikipedia I have some taxonomy terms that would benefit from being (at least in part) being based on wikipedia articles.

It looks possible to make a request via the wikipedia api in PHP, and then link that to my Term via Computed fields, but to make the initial request I need to relate the restful query to the term. I found something similar, but I have no idea how to make this work in my example...

Is there a module out there that would let me run a prefixsearch query to show autocomplete options while typing in the term name on the 'add new term' page, and then autopopulate using a parse query?

Is no module how would I go about coding this up? I don't have any PHP knowledge but it looks like it wouldn't be too hard to do.

To create your own autocomplete callback, you can see Textfield that uses autocomplete which shows a custom autocomplete.

Since all the data is stored of site though, you can save some time and load by implementing it client, since the user must rely on javascript anyway.

Managing JavaScript in Drupal 7 shows how to add the javascript to your site.

I'm not aware of any module, or even php/js library, that does all the wikipedia integration. If you go with the PHP option, you'll probably be interested in Guzzle. When I tried last, it was complicated to integrate composer packages with Drupal 7 though, but it looks like the situation may have improved through Composer manager.


Drupal 7 clearing validation error messages When an image upload fails validation an error message is thrown on the form, when I then upload an image that passes validation, the previous error message is not cleared from the form. How is this accomplished? Thanks.

The reason being after you enter the value the form needs to be submitted for the error to clear out. So if you want the validation removed as the user starts entering values you should look into the Clientside Validation module.


How to get fid of taxonomy term image? Is it possible to get the fid of an image from a taxonomy term?

Yes, it is.

$tid = 1; // Term id
$term = taxonomy_term_load($tid); // Load term
// Output term data with debug()
// See watchdog log at /admin/reports/dblog
debug($term, 'Taxonomy Term');

For example, file fid will be

$fid = $term->field_image[LANGUAGE_NONE][0]['fid'];

You could also get the rendered image, or url with something like:

// Get rendered HTML image tag using image styles.
$image = theme('image_style', 'medium', $term->field_image[LANGUAGE_NONE][0]['uri']);

// Get path to image style image
$path = image_style_url('medium', $term->field_image[LANGUAGE_NONE][0]['uri']);


Uninstalling a module In order to un-install a module I disabled and deleted the folder from the root module folder. Though I have deleted the module yet it's showing in module list page. Why is this? Am I doing wrong?

Simply find the module name, and write the following command in your command-line/terminal/console to disable the module at first (by considering that the current path in your command-line is the Drupal project root directory):

drush dis moduleName -y

then after the completion of the executing the above command, write the following command to uninstall the module:

drush pm-uninstall moduleName -y

If you have several modules, you can list their names. For example for three modules, you can write:

drush dis moduleName1 moduleName2 moduleName3 -y
drush pm-uninstall moduleName1 moduleName2 moduleName3 -y


RSS feeds in the front page How I can set which rss feeds are put at my frontpage like that

Feeds are produced by Views.

Right no feed link exists in frontpage.
What would be also the right syntax for HTML5?

The default frontpage view provides what you need as long you print $feed_icons; in your page.tpl.php


What is the best procedure to upload sites folder from Locahost to live server? I've had problems on and off with executing this task, using D7.

I create sites on localhost , then I ftp the files to live server.

FTPing the whole sites folder doesn't work, sometimes causes errors, how should I upload the sites folder properly?

So what I have done is upload the sites/all  and sites/default/files separately, and I take out the .htacess file from the sites/default/files folder and keep the original one in there...

But that's a pain in the ass, shouldn't it simply be delete the complete sites folder on the server and FTP the one from locahost?

Instead of using FTP, consider using Git over SSH.  Drupal.org has documentation on using Git with Drupal 6, 7, and 8.  Note that for this, your webhost will need to support SSH, which some of the cheapest do not.

If you're using Drupal 8, consider using Git with Composer.

If you need some help figuring out how all this works, consider making a test site and a free account on one of the Drupal-dedicated hosts like Pantheon or Acquia. (Disclaimer: I have sites on Pantheon, but here I'm just recommending trying a free account to see how the Git flow works.)


Set CSS class for the comment block Could you please advice how to set additional CSS class for the comment block using Drupal hook. I'd like to paint the author and date of the comment with green color if the author of comment is not the author of a node.

Something like

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

    if ($author_comment_id !== $author_node_id) {

        $form['#attributes']['class'][] = 'add-class';
    }
}

The problem is that I don't see the #attributes for comment block via dsm ($form). Maybe I'm using the wrong hook? Is there any different way to achive this?

Could you please help?

I would do it by adding a new template for the block. See Drupal 7 Template (Theme Hook) Suggestions

block--[region|[module|--delta]].tpl.php base template: block.tpl.php
Theme hook suggestions are made based on these factors, listed from
the most specific template to the least. Drupal will use the most
specific template it finds:
block--module--delta.tpl.php
block--module.tpl.php
block--region.tpl.php


Views - sticky items per page paginated using several displays (Hooks or UI way) Hi and thanks for take the time to read this post.

(I want to know if exist some hook or User Interface way to make this)

I have two content types (content type X and content type Y), and I want to build one view that have the nodes of content types X and Y, but that shows always sticky items for X content type per each paginated page.

For example: the view will show 10 items per page.

to the first page --> the first 3 items will have positions 1,2,3 to X content type nodes, and the last positions 4,5,6,7,8,9,10 will have Y content type nodes.

to the second page --> the first 3 items will have positions 11,12,13 to X content type nodes, and the last positions 14,15,16,17,18,19,20 will have Y content type nodes.

I am reviewing modules like Nodequeue or Weight but I can not understand how to reach this using this modules (i think that this is a useful way with nodequeue: http://www.absolutecross.com/tutorials/drupal/custom-re-ordered-front-page-teasers but my question about how to sort automatically in the required way still is pending)

I must say that I have some aproximation to resolve this using a php snippet in one page: I use one pagination control that handle a SQL query with all results (all content types needed), and the other two SQL queries will call the respective quantity of data to each kind of content type (the sum of results of all individual queries, must be the number in the respective pagination parameter)...it works, but, like I already indicated, I want to know if exist some hooks way, or User Interface way, to make this because I will use several exposed filters that will change SQL queries.

Thanks in advance.

First off, this can all be done in views, no custom code required (yay!). This is accomplished by creating an attachment view which will inherit the pager settings.

First you create a view with a page display that shows 7 Y nodes only.

Second, on the same view, add an attachment display. For the attachment, set it to show 3 X nodes only. In the attachment settings, make sure that Inherit arguments, Inherit exposed filters, and Inherit pager are set to yes. Set Render pager to no. Set Position to before and set Attach To to your page display.


Page title not displayed at the top of the Content area The page title is displayed in the breadcrumb, but not as a page title, at the top of the content area. Is there a setting somewhere I can edit, or will I need to manually add it to node.tpl.php?

The Title field is there, in the Content type - manage fields.

The search results page however, does have the page title displayed at the top of the content...(?)

According to your node.tpl.php, if the node is viewed in teaser mode, that $title variable will be output. (if (!$page):)

For the node view in full page mode (if ($page == TRUE):) then you need to have print $title in your theme page.tpl.php

i.e:

  <?php print render($title_prefix); ?>
  <?php if ($title): ?>
    <h1 class="title" id="page-title">
      <?php print $title; ?>
    </h1>
  <?php endif; ?>
  <?php print render($title_suffix); ?>


When I run cron I get deleted nodes created again I delete products and product displays nodes type (both powered by commerce module); then all these node are gone.

After this, I run cron and I get all those (deleted) node back in my site.

How can I trace this problem?

Have you used drupal.org/project/feeds to import content into your site? In that case perhaps you have configured your feed to make a import every time cron runs? In that case I think you should set Minimum refresh period to none.

Also, here is a thread facing the same problem: Delete feed, ron cron, feed comes back


Are "files[]" from custom_module.info not included on form submits? I have a module that I am porting to Drupal 7 (specifically, Taxonomy Views Integrator) and there are 2 include files tvi.admin.inc which were included via the module's .info file:

files[] = includes/tvi.admin.inc

The tvi.admin.inc houses the functions that the tvi.module's hook_form_alter() uses, including the validation & submit functions

Although alterations made using the hook_form_alter() work properly, after submit the validation & submit functions in tvi.admin.inc are not available and throw an undeclared function error.

p.s.

I've checked the initial issue for the extended .info module registry via:
http://drupal.org/node/224333#registry and it does say the following which may provide us with an answer:

  Files containing only functions need
  not be listed in the .info file.

As a Workaround,

I now use module_load_include() to load the tvi.admin.inc at the top of the tvi.module which, on form submit, still includes the inc and thus the validation / submit functions.

Files listed in .info files are not automatically included when the module is loaded; they are loaded when a module tries to create an object for a class that PHP doesn't find. In that case, a callback registered with spl_autoload_register() will check the content of the Drupal registry to find which file needs to be loaded to allow the creation of the object.

The only way to load a file containing a function is to use module_load_include().
In the specific case, where the function to load is a form validation handler (or a form submission handler) that is added to a form altered with hook_form_alter() (or hook_form_FORM_ID_alter()), I would rather keep the form handlers in the same file containing the hook implementation. Technically, the file is loaded by hook_form_alter() when it is not necessary, as the form handlers are used after the form has been submitted; so far the code worked, but it is not said that it would not work in future versions of Drupal.

Drupal 7 allows modules to implement hook_hook_info(), which is used from Drupal to know in which files the hook implementations are defined. The System module define its own implementation, which contains the following code:

function system_hook_info() {
  $hooks['token_info'] = array(
    'group' => 'tokens',
  );
  $hooks['token_info_alter'] = array(
    'group' => 'tokens',
  );
  $hooks['tokens'] = array(
    'group' => 'tokens',
  );
  $hooks['tokens_alter'] = array(
    'group' => 'tokens',
  );

  return $hooks;
}

With this implementation of the hook, when Drupal is looking for the file containing the implementation of hook_tokens() for the module custom.module, it will look for the file custom.tokens.inc contained in the directory where the module custom.module is installed.
Third-party modules are allowed to implement their own hook_hook_info(), but it should be remembered they are modifying where Drupal looks for the hook implemented by other modules too, which means that changing the group for hook_token_alter() changes the files where Drupal looks for any implementation of hook_token_alter().

It is possible to use hook_hook_info() to keep some hooks in a file that is different from the module file, using an implementation similar to the following:

function custom_hook_info() {
  return array(
    'form_alter' => array(
      'group' => 'form',
    ),
  );
}

What I reported before is still valid; future versions of Drupal could stop working because they would not find where the form handlers are, even though they know where to find the implementation of hook_form_alter().
This is the reason I keep to put the implementation of hook_form_alter() (or hook_form_FORM_ID_alter()) and every related form handler in the module file.


How to display 1 full article and the a summary of others Hi I'm new to Drupal and I'm trying to find a way to display on my home page the full version of the latest article and a list of other articles as teasers.
The teasers could be either listed under the full article or in a block in the sidebar. Is this possible? Currently I can only list articles as teasers.

Install Views, then enable the disabled view called Front page.

To get two different view modes for the nodes, you could add an attachment display to the view that shows a single latest article in full view mode and add it to the view at the top. Then you would set the page display (the original view) to display teasers, starting at an offset of 1.

It could also be accomplished with Display Suite.


How to make several instances of nivo slider in Drupal 7? I develop a web site using the Drupal 7 cms. I use Nivo Slider and it works perfectly for me. I used nivo slider for the front page of the site. When I configured the nivo slider it's settings are displayed under structure in the Drupal CMS menu. Basically, I have to update images and set transitions and etc.

Now the problem is I have another page where I need to add a new slideshow. But I don't know how to make another instance of nivo slider and use it. Since this is a CMS I guess there should be a easy way to handle this.

I think my problem is clear. If not, please ask in comments where I have to clarify my problem.

You might want to take a look at the Views Nivo Slider module. It allows you to construct the slider using views. Since you can create blocks with views, you should be able to build several galleries (by creating other views).


Why is my content not hidden? I set up a rule that blocks access to a specific piece of content. In fact, for simplicity's sake, I made a rule that blocks everything:

function namhost_node_access($node, $op, $account)
{
    return NODE_ACCESS_DENY;
}

The problem is, if I go to:

/node

And browse through all the content, I still see data that I deliberately blocked. Why are these showing? Is /node some kind of view with full access to anonymous users? Is my access rule not being enforced for some other reason? Am I not understanding what the point of /node is and if I just block that path will I be fine?

Also, are there any other ways that people can access content types I've blocked? It's making me worried that I am able to access content that has been deliberately blocked.

Look at the documentation for hook_node_access, here:

https://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook_node_access/7

The key is where it says:

Also note that this function isn't called for node listings (e.g., RSS feeds, the default home page at path 'node', a recent content block, etc.)

You probably want to check the link following that comment, i.e. the node access rights description, which got more complicated in D7 from D6.

Another thing to pay attention to is: if you're logged in as user id 1, then you won't be affected by those node access grants.


How to send an email to an Organic Group admin for every comment of their group? Drupal 7.x
Organic Groups / Rules 7.x-2.9

What is the best method to send an email to the 'Administrator Member' role of a group every time a comment is posted in their group?

I am looking to specify the exact groups that this rule works for.

You can create a rule with:

Add Event "After saving new comment" or "after udating an existing comment"
Add action to the rule, under the "Organic Groups" section, there is a "Get group managers from group audience".
Then you add a loop for this list, and then use the "Send email" from under "System" section.


Multilingual menus: logic and architecture A question dedicated for developers: What is the right Multi-lingual option for entities and menus in Drupal 8? In contrast to Drupal 7 that never asked me for a menu language, some entities and menus in Drupal 8 asks me for a default... But... I don't want a singular language for that menu... I want it to include 2 and even 3 languages... Thus what is the logical option? My question is basically comprised of two questions:

Is it Not specified? Or Not applicable?, and what is the difference between the two?
I also wonder why the ready-to-work menus that comes with the Drupal 8 installation, are not multilingual and are locked to the language in which the site was installed... Won't it be more flexible to set it to some kind of a multilingual option and that's it?...

It seems to be impossibe to have one multilingual custom menu in Drupal 8.0.

What you have to do is to create one menu per language. You specify the one language of the menu as you show in your image.

Then in blocks you place all your menus in the same place. Here you can choose which menu is chosen for which language.

This is far from elegant, since you have to edit each language separately without a translate button. But apart from being a cluttered process to create, it works nicely.


How to create a separate web page menu to be used only on one of my web pages? My site has a main menu displayed at the top of each page. But one of my pages is about a Parade we host, and it has a lot of content.

I would like to create a menu just on the Parade web page. Every option I have looked at has edited the main site menu.

But how do I create a separate menu just to be displayed on my specific pages?

Add a new menu to the site.

Go to Structure > Menus > Add Menu

Once you have added a menu, and the links, this menu will now be available as a block.

Go to Structure > Blocks and assign the new menu to a region.

under that block settings, you can define which URL you would like the block to display on. Set that to the URL of your page, and you're good to go.


Comment form won't appear in my theme I can't get the comment form to appear in my theme.  It does appear in Garland, but not in Bartik.

I have copied node.tpl.php and comment.tpl.php into my theme from Garland.

I have added text to the node.tpl.php template to ensure that it is in fact the relevant template for the node.

I checked the page source to see if perhaps the comment form is appearing, but is hidden by CSS.

I deleted ALL code from the template.php file in the theme.

I have cleared the cache and run cron after doing all of the above.

I've built more than 100 Drupal sites, so I'm not exactly new to the framework.  And yet I can't get the comment form to appear in this theme.

Clearly I must be doing something wrong, but I can't think of what else to check.

Any ideas?

Remember, the comment box does appear in Garland, so this can't be a permissions issue and can't be due to settings in the node itself.

The Drupal version is 7.41.

Thank you.

The "Comments block" module was the cause of this.  The module appears to be functioning as intended.  I just hadn't encountered this contributed module before, and didn't realize the project made use of it.

Because the "Comments block" module is installed, the "Comment form" block must be added to a region (e.g. "Content") in the theme.  This explains why the comment form was appearing in some themes but not in others.


How to disable the "clear log messages" functionality for administrators? For a production site, for auditing purposes, I would like to disable the "clear log messages" functionality for all administrators. This function is shown within admin/reports/dblog (within the "Recent log messages" report).

How to do this?

You would have to use hook_form_alter, and either remove that form or put access control on it. This needs to happen in a custom module.


Filter by field that only exists for some content types shown in view We're trying to create a view with a number of exposed filters in D7. There are a number of different content types that we want to show in the same view, and to filter using the same filters. However, most but not not all of the content types have all the fields we want to filter by.

For instance, "Difficulty Level" is a field common to many of our content types, including Tutorial and Project. However, an Idea does not have this field.

Ideally, we would like to let end-users filter by a number of fields and specify whether they want the filter to be strict or flexible. Let's say the user is looking for resources that have a Difficulty Level of "Beginner" or "Intermediate":

strict would mean that only nodes that fully satisfy the filters are shown:

no Ideas would be shown, because Ideas by definition don't have a Difficulty Level field to begin with
Tutorials with a Difficulty Level of null would also not show up
an Advanced Tutorial would not be shown

flexible would mean that all nodes that don't outright disagree with the filters are shown:

all Ideas would be shown
Tutorials with a Difficulty Level of null would be shown
an Advanced Tutorial would still not be shown

Is this doable with Drupal? I've searched high and low and haven't been able to find anyone with such a problem...

EDIT: Using the and/or groups is one possible solution, however it doesn't work for taxonomy fields: these lead to joins instead of left joins, so that you can either get the items that have the requested keyword or the items that don't have any keywords, but not both at the same time.

Yes, that's doable.

I would create a separate view for strict and flexible and then tailor each to suit your needs. You may need to use hook_views_query_alter if you can't get the functionality quite right with just the view UI.

A possible simpler alternative approach is outlined in this answer here.

Essentially this involves clicking on the reduce duplicates checkbox when configuring your join in the views UI.


Base url issues and subdirectories I have a drupal site at http://example.com and a development version of the same site at http://another.example.com/subdir. When I'm working on the development version, content that references /sites/default/files/ - such as images - doesn't work because it needs to include the '/subdir' part of the path. Setting $base_url doesn't work because that uses the BASE element's href attribute which doesn't affect urls beginning / if the href includes a subdirectory.

What's the best way of including the subdir in the image references? Do I need to resort to a server rewrite?

There are two things you can do here in order to try and make you site more portable.

In your templates:

Always use l() for all links (even JavaScript links)
If you need to reference an image in the theme use:

<img src="<?php echo $base_path . drupal_get_path('theme', 'themename'); ?>/logo.png" />

In your content:

You do not really have a way in order to preserve uploaded content URL's unless using some form of file manager which do not create absolute links, but much rather links that get sent to drupal that redirect to the file
If the above is not going to work for you then a modification of the rewrite rules for the drupal site sitting under the subdir is required to basically rewrite all URLs requested that start with sites/default/files/(.*) rewritten to subdir/sites/default/files/$1

And the apache mod_rewrite rule may look like the following.

# Redirect all files requests to a subdir
RewriteRule ^/?sites/default/files/(.*) /subdir/sites/default/files/$1 [R=301,L]


Default to MyISAM instead of InnoDB in Drupal 7 Can I make Drupal default to MyISAM for new tables instead of InnoDB? Except for hacking the core, that is.

The quickest and dirtiest way to get all Drupal data into MyISAM perform the following:

Make a backup of /var/lib/mysql before doing these steps

step 1. mysqldump all data out of mysql

step 2. remove all folders and files from /var/lib/mysql, but leave the /var/lib/mysql/mysql alone because it contains user grants.

step 3. add this line in /etc/my.cnf

[mysqld]
skip-innodb

step 4. service mysql restart

step 5. reload mysqldump file back into data into mysql database

UPDATE 2011-10-04 04:28 EDT

step 1. Set Default Storage Engine to MyISAM

add this line in /etc/my.cnf

[mysqld]
default-storage-engine = MyISAM

step 2. service mysql restart

Give it a Try !!!


Views 3 fields as list I am using Views 3 in Drupal 7 to show parent taxonomy terms using nested relationships.

This involves setting up a parent relationship, then a parent relationship of that parent, and then a parent relationship of that parent - this goes five levels deep and appears to be working well.

I have set the view to output the term name associated with each relationship, and with Views set to not render anything if the result is empty, I am being left with exactly what i need - a list of all (well, five levels right now) hierarchical parent terms. I have also set views to link each of these term names to their respective pages - and this is what is causing me problems...

Thing is, I want to see these fields as an unordered list. Setting the format option in Views to HTML list obviously sees all of my fields as part of the same result, and thus makes them the same list item.

The first thing I tried was to hide each field from display and rewrite everything using a custom text field:

[Term_Name_Level_1]

[Term_Name_Level_2]

[Term_Name_Level_3]

[Term_Name_Level_4]

[Term_Name_Level_5]

This works, but when I'm not five levels deep in the hierarchy (which is most of the time), I end up with empty li tags, as so:

(I put periods in here to show the effect, as the blank list items don't show here otherwise)

.
.
.
Grandparent term name
Parent term name

The next thing I tried was to rewrite each individual term name field, adding li tags around each one

[Term_Name_Level_1]

then rewriting the output as follows

    [Term_Name_Level_1]
    [Term_Name_Level_2]
    [Term_Name_Level_3]
    [Term_Name_Level_4]
    [Term_Name_Level_5]

This almost worked, as if there is no result, the whole field is left out including the tags. The problem here is that the link to the term page is wrapping around the li tags, like so:

Grandparent term name

Parent term name

Thats obviously not what I need, so can anyone think of a way to get Views to output each field as a list item, but without printing empty tags when there is no result? I must say, I have a horrible feeling that I'm overlooking something!

Is there perhaps a way to get Views to output a raw link to each term page, so I can rewrite the lot? I see that there is a 'Taxonomy term: Term edit link' field available, but not a link to the actual term!

Thanks!

You can add the Term:ID and set the link to the term in 'rewrite results' as:

taxonomy/term/[tid]

If you want to keep the aliased URLs, you can use Global Redirect module.

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


Display the field filename in the node I have a content type with an image field; the number of files is unlimited. I need to extract, filter using regex, and display the filename for each image in the particular node type using a view.

I tried with field--field-images--content-type.tpl.php and every other overwriting theme hook's trick and nothing even started working.

I think I miss something important on the way.

Checkout this using hook_preprocess_node()

function MYTHEME_preprocess_node(&$vars) {
  $node = $vars['node'];

  if ($node->type == 'the_type' && $vars['view_mode'] == 'full') {
    $field_items = field_get_items('node', $node, 'field_name');

    if (!empty($field_items)) {
      $filenames = array();
      foreach ($field_items as $item) {
        $filenames[] = $item['filename'];
      }

      $vars['filenames'] = theme('item_list', array('items' => $filenames));
    }
  }
}


Don't display block title on some content types I try not to display the title block for one single content type. I do it in the settings of the title block under Visbility -> Content type there I tick the content type which should not have the title block rendered and I check the options Negate the condition.

Basically this works but for example pages generated from the Views module also get no title block rendered then.

Does anybody know about this (in my opinion) "misbehavior" of the block system and how to work around it?

Maybe it's also a problem of the views module... I guess everything which has a content type gets the title except the excluded content type but Views pages do not have a content type and therefor get excluded too.

Do you have Ctools installed? Then you have two visibility plugins for content types. One from Ctools and one from core. Better use that from core, because Ctools is still alpha. If you install the module Block Visibility Groups, then you get the option to negate the condition also for the core plugin.

A core only workaround would be to use the path of the content type and negate this.


Unset terms that show in taxonomy autocomplete I would like to unset terms that show up in taxonomy autocomplete.

For example if TID 1 2 3 4, are in the taxonomy I would only like 1 2 and 3 to show in the dropdown for autocomplete.

Your best bet would be to create your own autocomplete path. Here are the steps to implement this:

Create a custom module

In hook menu create a custom autocomplete path:

$items['my-module-taxonomy/autocomplete'] = array(
  'title' => 'Custom Autocomplete taxonomy',
  'page callback' => 'my_module_taxonomy_autocomplete',
  'access arguments' => array('access content'),
  'type' => MENU_CALLBACK,
);

Create my_module_taxonomy_autocomplete function.  The easy way would be to copy everything from the  taxonomy_autocomplete() function and add conditions in your query. For example:

->condition('t.tid', array(1,2,3), 'IN')

In hook_form_alter() set the autocomplete field from using the default one to the custom one you just made:

/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'my_node') {
    $form['field_term'][LANGUAGE_NONE]['#autocomplete_path'] = 'my-module-taxonomy/autocomplete';
  }
}