Drupal web page logging I have a website built on drupal. I want to log (preferably db log) all the calls being made to a drupal page. The drupal page is called as shown here

http://www.example.com/page-name?url=example2.com&redirect=example3.com&uid2=randomNumber

I need to log all URL fields (url,redirect,uid2) alongwith timestamp and drupal user id.

Whats the best way to do it?

Create a custom module, for example:

MODULENAME.install file with hook_schema() implementation:

<?php

/**
 * Implements hook_schema()
 */
function MODULENAME_schema() {
  $schema['MODULENAME'] = array(
    'description' => 'Description of the table.',
    'fields' => array(
      'timestamp' => array(
        'description' => 'Timestamp of the rquest.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      // definitions for the rest of fields here
    ),
    'indexes' => array(
      // define indexes
    ),
    'primary key' => array('NAME_OF_PRIMARY_KEY_FIELD'),
  );
  return $schema;
}

?>

MODULENAME.module file with hook_menu() implementation:

/**
 * Implements hook_menu()
 */
function MODULENAME_menu() {
  $items['page-name'] = array(
    'title' => 'Example title',
    'access callback' => TRUE, // imply no restrictions
    'type' => MENU_CALLBACK,
    'page callback' => 'MODULENAME_pagename_view',
  );
  return $items;
}

function MODULENAME_pagename_view() {
  global $user;
  // insert into Drupal database
  db_insert('MODULENAME')
    ->fields(array(
      'timestamp' => REQUEST_TIME,
      'user_id' => $user->uid,
      'url' => $_GET['url'],
      'redirect' => $_GET['redirect'],
      'uid2' => $_GET['uid2'],
    ))
    ->execute();
}

?>


How to move block from a region inside of hook_preprocess_node? I have added mycustomblock to the header region in our settings (/admin/structure/block). We are using the standard content block and displaying that in the Content region, which is displayed below the Header region.

For just our Basic Page content type, we would like to move the mycustomblock to display below another field. We tried using the mymodule_preprocess_node hook to move the block below one of the fields (i.e. field_categories). However, we don't know how to move the block.

How would we move the block inside the hook_preprocess_node?

Setup:

Basic Page content type

Title
Categories (field_categories)
Tags (field_tags)
Image (field_image)

node--page--full.html.twig

{{ label }}
{{ content.field_image }}

/* I want to display the block here, using some variable */
{{ mycustomblock_variable }}

{{ content.field_categories }}
{{ content.field_tags }}

Regions (order displayed: top down)

header
content
footer

We tried the following but it didn't work

function mymodule_preprocess_node($variables) {
  $node = $variables['elements']['#node'];

  if($node->bundle() == 'page') {
    $block_entity = Drupal\block_content\Entity\BlockContent::load(123456);// BLOCK_ID
    $block_view = \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block_entity, 'mycustomblock');
    $variables['mycustomblock_variable'] = $block_view;
  }
}

I think you should send render of the block not an array of block entity.
View Method return an array.

Try with renderer service like the following:

/**
 * Implements hook__preprocess_HOOK().
 */
function mymodule_preprocess_node(&$variables) {
  $node = $variables['elements']['#node'];
  if ($node->bundle() == 'page') {
    $block_entity = Drupal\block_content\Entity\BlockContent::load(12345);//BLOCK_ID
    $block_view = \Drupal::entityTypeManager()
      ->getViewBuilder('block_content')
     // Change here default by your block view mode
      ->view($block_entity, 'default');
    $variables['mycustomblock_variable'] =\Drupal::service('renderer')->renderRoot($block_view);
  }
}


How to display user form and hide some fields? I'm building a website which has a member section. People subscribe and complete the "user" form (username, email, password and some other fields).

For an additional fee, they can be part of the "dating" part of the website, where they can meet new people.

After paying, I would like them to complete a form about them (height, eyes, etc.). Those fields are already in the user form.

I'm displaying the user form this way :

global $user;
module_load_include('inc', 'user', 'user.pages');
return drupal_render(drupal_get_form('user_profile_form', $user));

How would i go about hiding some fields that I don't want them to see/modify?

Thanks!

You should alter the form before rendering it.

$form = drupal_get_form('user_profile_form', $user);

// Uncomment this line to inspect the structure of the form array (needs devel module)
//dpm($form '$form');

// hide field.
unset($form['field_name']);

return drupal_render($form);


get user id from username or email without logging in I want to get the user id and role before the user is logged in.  If i have the email or username, what function can I use with D8 to get the user id ?

You can load the user with loadByProperties():

$users = \Drupal::entityTypeManager()->getStorage('user')
  ->loadByProperties(['mail' => $mail]);
$user = reset($users);
if ($user) {
  $uid = $user->id();
  $rids = $user->getRoles();
}


Get single value field_view_field I am using field_view_field() to render a product image.
I have a condition where I want to display only one image for the product not other images of that product. How can I do this?

Use this inside your view template file:

print fields['your_field_name']->content;


PHP drupal added css file does not appear in page source I have enabled LessCSS on my site and I have a node instance where I want to add a specific CSS.

I used the following piece of code:

<?php
    drupal_add_css( '/sites/MyStuff/introduction.css');
?>
<div id="myid" class="box">
    ....some text
</div>

Yet, there is no import or link statement in my page source code for introduction.css. I am not using compression. FireBug does not mention loading an introduction.css file. I have doubled-checked and the file is properly located in the folder.

What could cause this issue? And how to solve it?

P.S.:

The css file contains the following:

.box {
    color: green;
    background-color: red;
}

The styling is not applied on the page.

From https://stackoverflow.com/questions/1410494/drupal-add-css-not-working, the solution is to use CSS Injector. I tried and it worked.

Update

I maintain a page explaining how to use CSS Injector too add CSS to a page.


How can I update core to 8.9.10? I'm trying to apply the security update for core by updating it to 8.9.10 with the following command:
composer update drupal/core

But this only brings back the following notice:

Nothing to install or update

What am I doing wrong? How can I update core to 8.9.10?

Thanks to @leymannx
composer update drupal/core drupal/core-dev --with-dependencies

did it


use taxonomy for organic groups To lock down access to nodes based on OG's, I have implemented a taxonomy as a group. The users can then can select that taxonomy and access level for each content. Is anyone aware of pitfalls I need to watch out for doing it this way?

I apologize if this is out of scope for this site.

I apologize, but I am trying to do something similar.

OG_Menus, taxonomy_menu have seemed to provide a solution. nodeone.se provides a warning, it's unclear if it's been fixed or not. also look at simpleaccess and taxonomy access control.


Why am i getting PDO exception while running the following test from console? I am writing a module to return common parent of 2 revision in a linear entity. For example : After editing a node 5 times, we get a graph similar to 1->2->3->4->5 where 1 is the actual node and 5 is the last revision. I wrote a function which would return the common parent of 2 revision ID. It would return 3 for (4,5) and 2 for (3,4). The code is the following one.
namespace Drupal\conflict;

use Drupal\conflict\ConflictManagerInterface;
use Drupal\conflict\ConflictAncestorResolverInterface;

class ConflictManager implements ConflictManagerInterface {

    protected $resolvers = [];

    public function applies() {
        return TRUE;
    }

    public function addAncestorResolver(ConflictAncestorResolverInterface $resolver)
    {
        $this->resolvers[] = $resolver;
    }

    public function resolveLowestCommonAncestor($revision1, $revision2)
    {
        foreach ($this->resolvers as $resolver) {
            if ($resolver->applies()) {
                return $resolver->resolve($revision1, $revision2);
            }
        }
        echo "No revision found";
        return -1;
    }

    public function resolve($revision1, $revision2) {
        if ($revision1 < $revision2) {
            return $revision1-1;
        }
        return $revision2-1;
    }
}

To test the above written code, I have written a test case:
namespace Drupal\conflict\Tests;

use Drupal\Tests\UnitTestCase;
use Drupal\Core\Entity\Entity;
use Drupal\conflict;

class SimpleLcaTest extends UnitTestCase {

    public function basicTest() {
        $entity = EntityTest::create(['label' => 'revision 1']);
        $entity->save();
        $entity->label = 'revision 2';
        $entity->save();
        $entity->label = 'revision 3';
        $entity->save();

        $revision2 = entity_revision_load('entity_test', 2);
        $revision3 = entity_revision_load('entity_test', 3);

        $manager = Drupal::service('conflict.manager');
        $revisionLca = $manager->resolveLowestCommonAncestor($revision2, $revision3);
        $this->assertTrue($revisionLca->label() == 'revision 1');
     }
}

When I try to run test via console using run-test.sh, I get the following error:

Exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'file' cannot be null

You can't create and save entities in a unit test.

That's what kernel tests are for. You will also need to install the necessary entity schema then, make sure the necessary modules are enabled. One way to do that is to extend from EntityKernelTestBase.

Also, I strongly recommend to run the phpunit tests directly with phpunit, the error reporting is much better and it's faster as well.


Visibility depending on several values of another field I'm having a form with two field. And visibility of the one is depending on the values of the other.

    $form['property'] = array(
    '#title' => t('Property'),
    '#type' => 'radios',
    '#options' => array(
        'private' => t('Private'),
        'bail' => t('Bail'),
        'lease' => t('Lease')
    ),
    '#required' => TRUE,
);

$form['bank'] = array(
    '#title' => t('Bank / leasing company'),
    '#type' => 'textfield',
    '#required' => TRUE,
    '#states' => array(
            'visible' => array(
                ':input[name="property"]' => array('value' => 'bail'),
            ),
        ),

);

What comes to ':input[name="property"]'. How do I make it visible when "bail" OR "lease" values are set?

The Conditional Fields module should be able to do that.


How do I specify an image style in my preprocess function? In my current project, whenever a node's image field is empty, I'm filling it with the image from an entity referenced in the node. To pull this off, I'm using this magical piece of code in template.php:

// Implements hook_preprocess_node();
    function mycustomtheme_preprocess_node(&$vars) {

      $node = $vars['node'];
      $field_name = 'field_main_image';
      if (
        isset($node->$field_name) &&
        empty($node->$field_name)
      ) {
        $node_wrapper = entity_metadata_wrapper('node', $node);
        if ($node_wrapper->field_master_reference->raw()) {
          $project = $node_wrapper->field_master_reference->value();
          $vars['content'][$field_name] = field_view_field('node', $project, $field_name);
        }
      }
    }

It works superbly - but with one small problem: it doesn't give the image its correct image style. In fact it just spits out the original image.

How can I force it to use the field's image style?

Have you tried render

// Implements hook_preprocess_node();
    function mycustomtheme_preprocess_node(&$vars) {

      $node = $vars['node'];
      $field_name = 'field_main_image';
      if (
        isset($node->$field_name) &&
        empty($node->$field_name)
      ) {
        $node_wrapper = entity_metadata_wrapper('node', $node);
        if ($node_wrapper->field_master_reference->raw()) {
          $project = $node_wrapper->field_master_reference->value();
          $vars['content'][$field_name] = render($vars['content'][$field_name]);
        }
      }
    }


drupal 6 search pdf content Is there any way include pdf files in common drupal search. I tried http://drupal.org/project/search_files module. But it gives the results under a separate tab. Is there any to include them in common drupal search.
I  merger the result using hook_preprocess_search_results.

   $file_results = module_invoke('search_files', 'search', 'search', arg(2));
   $count = count($variables['search_results']);
   $variables['search_results'] = '';
   $f = null;
   $filecount = $count + 1;
   foreach ($file_results as $result) {
      $f[$filecount] = $result;
      $filecount++;
   }
   $variables['results'] = array_merge($variables['results'], $f);

But this also is not working. Anybody can suggest a solution? And one more doubt. Is there any way to change search result count.

In my opinion the best thing to use for file search is the http://drupal.org/project/apachesolr module along with the http://drupal.org/project/apachesolr_attachments module.
I probably wouldn't do file searching without solr.

You would then turn off the basic drupal search page and just use the solr one.

It will require a bit of extra setup though and you might not be able to do it if you are on shared hosting.

There is an issue for combining the search files and search pages here - http://drupal.org/node/368195

Unfortunately there isn't a proper patch to use but there is some code in there.
You will just have to do a bit of work yourself to get it going.


Search results: order & group by custom field I customized the display of my search results so I can show custom fields in the search results (other question).

I have a custom field ('Department'). I want to show the search results grouped and ordered by that field.

Found an answer... hook_preprocess_search_results is exactly what I need.

function mymodule_preprocess_search_results(&$variables) {
    $variables['search_results'] = '';
    $output_results = '';
    $output = '';

    // loop through results, group by department
    $departments = array();
    foreach ($variables['results'] as $result) {
            $departments[$result['node']->field_department[$result['node']->language][0]['value']][] = $result;
    }
    ksort($departments);

    foreach ($departments as $department => $departmentResults) {
        $value = "";
        foreach ($departmentResults as $key => $result) {
            $value .= theme('search_result', array('result' => $result, 'module' => $variables['module']));
        }

        $output_results .=  '

' . $department . '
';
        $output_results .=  $value;
        $output_results .=  '
';
    }

    $output .= '
';
    $output .= $output_results;
    $output .= '
';

    $variables['search_results'] = $output;
}


Search API with views -> Apply filters I have a website where i manage to create a database, display it with the views module and add a Search box with Search API.
I followed this tutorial: http://webwash.net/tutorials/how-create-search-pages-using-views-drupal-7

I'm using a bundle filter in my Index. My page only shows and search content from a specific content type.
On that content type i have a field "category" with 2 radio options.

What i want to do is be able to filter the search by that category: If i choose option A, when i type my search it will only search the content within that category.

It must be really easy but i just can't figure it out. You guys have any ideas?

Thank you so much in advance!

You need to add an exposed filter to the view for the category field. Under the advanced settings in views you can select to display filters as a block so that you can place it above the search block.


How To Redirect to a Named Node upon Registration Given a D6 site where users must confirm their email address, I would like new registrants to be immediately redirected to a Page node which explains the email verification process.

I attempted to do this using Actions and Triggers, but "Trigger: After a user account has been created" executes before the activation email is sent and so the message is blocked and never gets out. This appears to be an unresolved issue tracing as far back as D5.

The Login Destination module is listed as supporting this feature for D7.x but not 6.x.

You can use the Rules Module to redirect a user after an account is created.

Simply add a new rule for the event "User account has been created"
Add an action of "Page redirect"
Fill in the information for the page you want to redirect the user to.

Make sure that "Immediately issue the page redirect" is not checked or else the same thing will happen and the email will not get sent.


Import a class via template.php or other ways I'm using Drupal 7 and have this structure:

Lorem Ipsum

...

I want add a class top of this structure. E.G.

**
**

Lorem Ipsum

    ...

**
**

I don't use page.tpl.php files because using Views module. I put this code in template.php but don't working:

function mysite_preprocess_image(&$variables) {
if ($variables['style_name'] == 'node-ortaklar-cv') {
$variables['attributes']['class'][] = 'header';
}

}

Is is possible put a div in structure via template.php or some way? And how? Thanks.

The code needs to go in node.tpl.php, not page.tpl.php or template.php. Just follow these steps:

If you haven't already, copy the code from node.tpl.php into a file with the same name inside your theme's folder.
Edit the node.tpl.php file and add your markup around the main node div
Flush Drupal's caches (or at least the theme reigstry)

Then your nodes will all be wrapped in the markup you need.

If you just need to do this for a specific content type (I'm going to guess at one called image here), your template file will need to be called node--image.tpl.php. You'll still need the original node.tpl.php file in your theme though, as node template overrides won't work without it.


Shopping cart delete button is not removing the correct line item. I have 2 blocks on my shopping cart. The view block for the Main Product and another for the Specials ( which is an add-on), each block has their own delete button. I use a Views Field View on the Main Product block to call the Specials blocks. Each specials and main products are connected via node referencing. I can't use just 1 view block to show it like that because I need the added specials to be filtered/shown below the main product where it's connected.

When removing a specials, it deletes the line item properly but when I try to remove a main product it deletes the special that follows the main product and when there's no more special for that specific main product, it deletes the specials of other main product. It does not delete the line item where the remove is connected. I don't know why it works like that because each remove has their own line item.

Sounds to me like both of your forms on the page have the same form ID and use the same numeric key (likely 0) to identify the first item in the form. Thus when you submit it, Drupal doesn't know how to differentiate which form was submitted and makes a best guess, removing the 0th item in that form.

Alternately, if your configuration is generating a form within a form, that's invalid HTML and would explain a similar confusion on Drupal's part for the processing of the form. You would need to find an alternate method for getting the secondary form on the page, such as using the block system to embed the second form on the page.


White page after enabling modules I installed a pure Drupal on Windows/IIS6 share host, and uploaded several modules in (sites/all/modules). When I want to enable some module together, my administrative pages become white, but front page and other pages work normally.

Take a look at The White Screen of Death (Completely Blank Page) to learn more about the WSOD and how to troubleshoot it.


Unresolved dependency error when updating I Tried updating 2 different sites and both gave error messages saying "Unresolved dependency" missing from different modules.

The pages no longer load on the site saying

  Fatal error: Call to undefined function libraries_load()

Why am I getting these messages?

This is a bit of a guess...

If you're updating modules on a fairly out-of-date site, some of the new versions may now depend on other modules, whereas they didn't when you originally installed them. Either that, or the files have just become missing somehow.

Either way, it looks like you need to download

Libraries
Token
Views
Phone


Change language name based on the domain i'm on I'm looking for a solution which can alter/change a language name based on the domain I'm on.

Here I can configure one name, which is used everywhere, but can't be configured for each domain:
/admin/config/regional/language

I got a site with multiple domains. Every domain has a set of languages: en, nl and fr etc.

Each domain has different labels for those languages. For example:
domain 1: en: English
domain 2: en: International

Any suggestions?

Altering every form, every view output, just feels wrong.

You are looking for url/domain language negociation + url/path language negociation, right ?
You need both of domain+path in /admin/config/regional/language/detection/url to determine wich language to display.

I think you have to implement a new LanguageNegociation plugin in a module which do this. Have a look at :

core/modules/language/src/Plugin/LanguageNegotiation/LanguageNegotiationUrl.php

You should be able to get your own detector (quiet looking like LanguageNegotiationUrl with both domain+path) by extending LanguageNegotiationMethodBase.


Anonymous users can't see new content type in feed I've made a new content type, and I've made a View that is a list of that new content type. Anonymous users don't get any content in that list but can see the individual content types. Admin users can see the content in the view fine. Is it a permissions issue?

There are multiple possible problems. First of, dealing with unpublished content - assuming you created a content type with unpublished option as default, you will have to make sure that you tick the publish option on save/ create of new items. As per default registered and anonymous users can't see unpublished content.

Going further there could also be a problem inside of your view. You can manage access for the view itself in the middle column of the views ui edit page. There might also be a filter to only show published / published or admin items only.

also make sure that anonymous user can see content at all: /admin/people/permissions


How do I wrap two render array elements in a div? Given this renderable array:

$output = array(
    'twitter-icon' => array(
      '#type' => 'markup',
      '#markup' => '

'
    ),
    'twitter-link' => array(
      '#type' => 'markup',
      '#markup' => l('follow us on Twitter', 'https://twitter.com/#!/zujava'),
    ),
  );

How do I wrap both of these elements in a single DIV?

You can also use the #container form element, and code similar to the following one:

$wrapper = array(
  '#type' => 'container',
  '#attributes' => array(
    'class' => array('class-name'),
  ),
);

$wrapper['twitter-icon'] => array(
  '#type' => 'markup',
  '#markup' => '

'
);

$wrapper['twitter-link'] => array(
  '#type' => 'markup',
  '#markup' => l(t('follow us on Twitter'), 'https://twitter.com/#!/zujava'),
);

The #container element wraps its children elements with a
 tag, whose CSS class is the one passed in the #attributes property.

You could even use a container for the "twitter-icon" element, but that doesn't give you any pro, except in the case you could possibly add an element to that, as with the following code:

$wrapper = array(
  '#type' => 'container',
  '#attributes' => array(
    'class' => array('class-name'),
  ),
);

$wrapper['twitter-icon'] => array(
  '#type' => 'container',
  '#attributes' => array(
    'class' => array('twitter-icon'),
  ),
);

if ($condition) {
  $wrapper['twitter-icon']['twitter-icon-text'] => array(
    '#type' => 'markup',
    '#markup' => t('Icon text'),
  );
}

$wrapper['twitter-link'] => array(
  '#type' => 'markup',
  '#markup' => l(t('follow us on Twitter'), 'https://twitter.com/#!/zujava'),
);


How to Change the Format of the Email Template Sent with Webforms Ok, so I have a customer that has a ridiculously long form that individuals need to complete to apply for funding, but the email that is getting sent to our customer as well as each individual is not easy to read at all.

I have already installed MailSystem and MimeMail, so it is set to send in Full HTML, but it's still not that clear.

Is it possible to change the format so that the answer/response to each field is located below the field label? If possible, is this something that is relatively easy to do?

What about adding a line break between each field (label and response) so they aren't all one long list without any space to help distinguish between each one?

Any assistance with this would be GREATLY appreciated! We have a ton of nonprofit customers that all have similar forms and it would be very beneficial to have this option.

If you need any further clarification, just let me know.

Thank You!!

Nicole

Go to: node/%nid/webform/emails/%mid and there is a fieldset (E-MAIL TEMPLATE) where you can define your own email template (per mail account) by using all available tokens and by writting pure html (like <p>, <strong> etc) within the text-area. Don't forget to select "Custom Template".

Read more


How do I change the scrolling speed? I recently installed and enabled the Back To Top module. It gives a button at right bottom of the screen to scroll back to the top of the page.

How can I increase the scrolling speed?

In the file back_to_top/js/back_to_top.js you'll find the following on line 23:

$('html,body').animate({ scrollTop: 0 }, 1200, 'easeOutQuart', function() {

The 1200 is the animation duration in milliseconds. Lower it and the animation will go faster. Optionally you could raise a feature request in the module issue queue to make this a configurable setting.


.trigger("click") not firing I'm trying to automatically launch a dialog box containing an iframe if the user's cursor gets within 25 pixels of the top of the browser window.

In the code, a simulated click of a hidden button should open a dialog box which then loads an iframe containing information inside of a hidden div. However, the code doesn't seem to be executing. What am I doing wrong?

I'm working with Drupal 7. I'm sure there's a far more elegant way of accomplishing my goal, but bear with me right now.

<?php
drupal_add_js('https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js','external');
drupal_add_js('https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js','external');
drupal_add_js('jQuery(document).ready(function() {
    jQuery(document).mousemove(function(e) {
      if (e.pageY<=25) {
     jQuery("dialog_trigger").trigger("click");
        jQuery("#dialog_trigger").click(function()
        {

        jQuery("#dialog").dialog("open");
      });
    }
    });
});
    jQuery("#dialog").dialog({
        autoOpen: true,
        position: "center",
        title: "         ",
        draggable: true,
        width: 800,
        height: 700,
        resizable: false,
        modal: true,
    });', 'inline');
?>

<div id="dialog" style="display:none;" title="Dialog Title">
    <iframe frameborder="0" scrolling="yes" width="700" height="650" src="http://google.about.com/b/2013/04/01/google-nose.htm" style="padding-left:50px;> </iframe>
</div>

Never mind. I figured it out:

<?php
drupal_add_js('http://code.jquery.com/jquery-1.9.1.js','external');
drupal_add_js('http://code.jquery.com/ui/1.10.1/jquery-ui.js','external');
drupal_add_js('jQuery(document).ready(function() {

jQuery(document).mousemove(function(e) {

if (e.pageY<=5) {
        jQuery("#dialog").dialog("open");
}
});

    jQuery("#dialog").dialog({
        autoOpen: false,
        position: "center",
        title: "         ",
        draggable: true,
        width: 850,
        height: 700,
        resizable: false,
        modal: true,
    });

});', 'inline');
?>

<button id="dialog_trigger" style="display:none;">Open The Dialog</button>
<div id="dialog" style="display:none;" title="Dialog Title">
    <iframe frameborder="0" scrolling="yes" width="800" height="650" src="http://www.google.com" style="padding-left:25px;"> </iframe>
</div>


How to limit access to content to only users with the same role as the content author? I'm having trouble in my Drupal the Views and I don't really know how to solve it.

Let's suppose that we have two roles named Org1 and Org2. We can have more than one user per role so for example:

A and B belong to Org1.
C belongs to Org2.

The trouble I'm having is that I want that the content posted by A is seen by all the users in Org1 (in this case A,B) but not the users that are in Org2 (C).

How could be this made? I'm new to Drupal but not to programming in general. I've tried several modules but maybe due to my ignorance I have not been able to make it work (so any suggestion would be great). Any programatically suggestion also would be great (but it will be first time programming in Drupal 7).

What I have currently in mind and would probably solve my problem I think that is to filter by the user is logged in (if I'm user A for example filter by Org1). How could this be done?

Option 1 - Group module

You could, for sure, use the Group module for this. Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

For more details about the various roles and permissions, refer to my answer to "What are the various roles supported by the Group module?".

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".

Option 2 - Possible alternatives

Refer to my answer to "Recommended modules for managing Content access?" for some other modules that you might want to consider as a possible alternative. Even though it's not part of your question (today), I don't think any of them have a D8 version already.


Recovering from a WSOD related to hierarchical select module I was messing around with the hierarchical select module (trying to create an exposed filter that would use the hierarchical select interface) I got some strange AJAX related error and then tried to cancel out of what I was doing.  After doing so, when ever I try and edit this view I get the White Screen of Death. I went to MAMP server PHP log files and found this error:

  [02-Feb-2012 15:58:10] PHP Fatal error:  Call to undefined function _hierarchical_select_setup_js() in /Applications/MAMP/htdocs/sites/all/modules/custom/hierarchical_select/modules/hs_taxonomy_views_handler_filter_term_node_tid.inc on line 26

Since I can't get back to my view I don't seem to have any way to remove this broken exposed filter.  Any way out or did I just lose this whole view?

The _hierarchical_select_setup_js() function is defined in the hierarchical_select.module so this is one of those "it should work" situations.  Since it isn't, a quick workaround would be to copy it out of there and into, oh, say, your template.php file, wrapped in a "if !function_exists()" so it doesn't WSOD when it does :)


Taxonomy Access Control module - don't display term instead of disabling it I'm using Taxonomy Access Control module to manage allowed categories of content user can create/edit. I want to change default behaviour of this module which disables term which user cannot assign ("black" in this example) but still displays it.
I know, it can be hidden via CSS or removed via JS, but I want to remove it on the module level.

There is an issue in the issue queue regarding (https://drupal.org/node/1209154) this where the maintainer has given some options for a potential fix and has tried a few options out, however there is still no proper fix for the problem.

The module already handles the back end and not allowing users to submit those values, the disabling is really only for visual reasons, so removing via js is a viable solution in this case.


Steps to Create a copy of a Drupal 7 website using cpanel? I want to create an exact copy of an existing drupal 7 website in a subdomain. What steps should I take to do this using just cpanel?

Here are the steps I would take in cloning the site. First, Create the subdomain. Then copy all the files from the live site to the subdomain. Then I would back up the database. Create a new database and import the backup into that. Assign the user from the first database to the second one. Then change the settings.php file to read from the second database. Also, if you have a base url set in settings.php you would need to change that as well. Hope that helps.


Filter view with multiple displays Using Drupal 7. I have a view with several page displays, 2 of them being /review and /mentions. I have some exposed filters on these pages visible on a side block of the page.

When clicking the apply button to filter the content, I get redirected to /review?filter=....
whether I am on the /review page or /mentions page.

How can I make the filter work so that
- when filtering the /review page, I land on /review?filter=...
- when filtering the /mentions page, I land on /mentions?filter=...

Thanks for your help,
Jerome

I found what I was doing wrong.

I assumed that the exposed filter block for the view was the same for all displays of that view, When it actually creates 1 block per display.

I disabled the block "Exposed form: filter_view-page" for the /mention path and added the another block "Exposed form: filter_view-page_2" for it.

Works fine now.


Reservation / register module for D7 I need a simple reservation module for my D7 restaurant site.

What I need in the form is:

Customer information fields (Name, email, contact number, address, etc)
Number of tables to be reserved by that customer
Upon submission of reservation will lead to another link (I will write codes to link to payment gateway)

Admin are able to configure:

Price per table (Eg: USD 100 per table)
Total number of tables available to reserve (Eg: 100 tables)
Closing date for reservation, so that customer can't reserve after the closing date

Admin able to see:

Report of reservation
Details such as customer name, number of tables reserves, etc

I had tried using Webform, but I can't do the following:

Reservation close on particular date
Limit number of tables so that overall tables reserved will not exceed 100

Is there any reservation or registration module that I can use?

Or is there any method I can modify my webform to suit the requirement?

Perhaps the Drupal Restaurant Distribution is what you need, and if not it should at least give you some ideas.

It contains a number of modules, including on for reservations which I assume will do all you need, and more.

https://www.drupal.org/project/restaurant

From the feature list:

  Reservation System - Manage your reservations easily from one
  dashboard. View all reservations for today, this week or this month.


How do I limit taxonomy by content type? I want to limit the results of my code snippet below to query only items that have been used in a particular content type. How do I do that

<?php

$vid = 15; //vocabulary id
$num_term = 20; //limit maximum terms

//USE INNER JOIN below to only show terms with a count of 1 or more (the LEFT JOIN includes terms with a count of 0)
$query = "SELECT td.tid AS tid, name, COUNT( nid ) AS count
FROM {term_data} AS td
LEFT JOIN {term_node} AS tn ON td.tid = tn.tid
WHERE td.vid=". $vid ."
GROUP BY tn.tid ORDER BY name ASC LIMIT ". $num_term;
$result = db_query($query);
while ($term = db_fetch_object($result)) {
$items[]= l($term->name, "taxonomy/term/$term->tid") . ' (' . $term->count . ')';
}

if(count($items)) {
return theme('item_list',$items);
}

?>

You would also join in the node table (on term_node.nid = node.nid) and add node.type to the WHERE clause.

Do note there are several problems with your above code. First and foremost, as mariomc asks, any special reason why you're doing this manually instead of through Views?

Second, if you do have a good reason to do the querying yourself, do look into using placeholders with db_query. Its primary purpose is preventing SQL injection problems (strictly speaking, if the variables really are hard coded like this, there is really no danger, but consider what happens when you decide to feed them in from somewhere else at a later date).

All in all, code that would both answer your question and is more "correct" would be (untested):

<?php

$vid = 15; //vocabulary id
$num_term = 20; //limit maximum terms
$type = 'story'; // Your type

$query = "SELECT td.tid AS tid, name, COUNT( nid ) AS count
  FROM {term_data} AS td
  LEFT JOIN {term_node} AS tn ON td.tid = tn.tid
  LEFT JOIN {node} AS n ON tn.nid = n.nid
  WHERE td.vid=%d AND n.type = '%s'
  GROUP BY tn.tid ORDER BY name ASC LIMIT %d";

$result = db_query($query, $vid, $type, $num_term);

// ...
?>


Rebuild permissions needed after installation from profile Once solved this issue:
How to define settings from an install profile

I would like to skip the Error Message I get on first load of the application:

Message d'erreur
Les permissions d'accès au contenu doivent être reconstruites. Reconstruire les permissions.

To do so, I've created a task to perform the function
    node_access_rebuild(FALSE);

function genius_install_tasks(&$install_state) {
  $tasks['genius_settings'] = array(
      'display' => FALSE,
      'type' => 'batch',
      'run' => INSTALL_TASK_RUN_IF_NOT_COMPLETED,
  );

  $tasks['link_taxonomy_menu'] = array(
      'display' => FALSE,
      'type' => 'batch',
      'run' => INSTALL_TASK_RUN_IF_NOT_COMPLETED,
  );

  $tasks['rebuild_permissions'] = array(
      'display' => FALSE,
      'type' => 'batch',
      'run' => INSTALL_TASK_RUN_IF_NOT_COMPLETED,
  );

  return $tasks;

}

But it seems to don't be enough.In fact, I set a message that I can't see, so I think this task maybe is not being perform.

function rebuild_permissions() {
    // Rebuild permissions
    node_access_rebuild(FALSE);
    // This message is set at the end of the node_access_rebuild
    // Keep here to ensure this task has been made
    drupal_set_message(t('Content permissions have been rebuilt.'));

}

I am going to try to change the type of the task to normal.
EDIT: This change doesn't solve the problem

Mindwhile, appreciate reader, do you have any advice to do the rebuild permissions at the end of the installation correctly?

Thanks for the reading.

Finally it seems as it is done from the hook_install.


How to add exposed form block to .tpl.php I've added this code to preprocess function but it dosen't work :
in preprocess :

//edit_search_api_views_fulltext is the form_id of exposed form block;
$vars['custom_search'] = drupal_render(drupal_get_form("edit_search_api_views_fulltext"));

in tpl.php

print $custom_search;

What I'm missing ?

You want to print an exposed block in tpl, right? I am using this in drupal 7

<?php
  $block = block_load('views', '-exp-VIEWNAME-DISPLAYNAME');
  $output = drupal_render(_block_get_renderable_array(_block_render_blocks(array($block))));
  print $output;
?>

for example

<?php
  $search_block = block_load('views', '-exp-cruise_package-page');
  $output =  drupal_render(_block_get_renderable_array(_block_render_blocks(array($search_block))));
  print $output;
?>


Auto increment using serial variable In this code i want to incerment the value by 4 and not by one .
How Can i do it ?

    select_id' => array(
          'description' => 'TODO: please describe this field!',
          'type' => 'serial',
          'not null' => TRUE,
       ),

Auto-incrementing by a value other than one is not an easy task. Drupal's Schema API allows you to supply the mysql_suffix property to supply mysql specific properties as explained in this comment.

The problem is that there is no mysql TABLE CREATE option which allows you to change the auto increment amount. There is a MySQL variable auto_increment_increment but it can only be set globally.

In this similar question a solution has been posted using MySQL triggers. AFAIK this is the  best SQL solution that exists.

The best solution would probably to find a way to not need to auto_increment with a value other than one or use an INTEGER type and do the incrementation manually through PHP.


get drupal base path in views rewrite result i want to get Drupal base path in views rewrite result. but rewrite result doesn't support PHP code.

how can i add Drupal base path to replacement patterns in views rewrite result? i try installing some modules like entity api, token but it doesn't help.

i know there is http://drupal.org/project/views_php and i get base path with php code  but it has a dev release.

You can do this in the theme layer by overwriting the template and calling base_path(). If you are displaying Fields, you can overwrite the template for the field you want to rewrite.


Due to Clean Url issue, the site is not working I have downloaded Drupal 8 from official site.But during installation it shows following error:

but i continue installation, and it installed properly. The problem is that except home page whenever i click on any link it shows "Page Not Found".

I have enabled mod_rewrite for apache . Also i uncomment and edit "RewriteBase/d8" in.htaccess file.

I tried all whatever i found on drupal.org but nothing work for me.I desperate to work in d8 but helpless to continue.
Million of Thanks in advance.

I was having the same problem, I opened the /etc/apache2/apache2.conf file and located this portion of the file

<Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
</Directory>

And found that AllowOverride is set to None. Go ahead and replace it with All.

Restart your apache service when done. Similar question is asked here


Display solr result by specific field order I am implemented the Apache Solr with Search API module.
Everything working fine but now requirement is to show solr result by specific field order.

I have total 4 fields in content type

Field 1
Field 2
Field 3
Field 4

Now solr show result random order from this field i.e any field coming on top.

I need to show result by field order. i.e display all result on top by matching "field 1" then "field 2" and so on.. Anyone can help me to achieve this result...

I am resolve my problem by using edismax of solr.

Ref Link: https://cwiki.apache.org/confluence/display/solr/The+DisMax+Query+Parser

http://localhost:8983/solr/collection1/select?q=search_word&wt=json&indent=true
&defType=edismax&qf=field_1^20+field_2^19+field_3^18+field_4^17&pf=field_1+field_2+field_3+field_4


Install module via Drupal Console fails I'm trying to install a module via the new Drupal Console on Drupal 8.

I chmodded my modules directory to 777 without success.

drupal module:install admin_toolbar

[ERROR] Unable to install modules admin_toolbar due to missing modules admin_toolbar

Try to download it first and then install.

drupal module:download admin_toolbar
drupal module:install admin_toolbar


Translation of Menu items HI I'm trying to work out how to translate my menu items, weirdly Log Out appears to be the only one which translated from the onset. But I can't see where this was implemented. If I search for the menu name as a string in transate interface/transalte they can't be found. and editing a menu offers no extra fields for translate options??

any body know?

First of all, when you search for translations they are case sensitive. don't include aditional spaces, it has to be exact, but it can be partial.
If one translation was previously made and the same word appears in many places it will list it, but what applies is the first translation made (sorted by time)
You have to make sure that your Log Out is really a tranlation

in my case it appears in chain: /admin/settings/language as Log out @username, so if I translate this, it works in the other languages
there is another Log out in the chain with the same name...so be careful


Setting value to checkboxes in a form I've been having troubles with form_set_value(). I've extended the Search form, everything works, but after submission, the form values for those fields added by me return to default (see the code).

What am I doing wrong?

Thank you!

<?
/**
 * implementation of function hook_form_FORM_ID_alter
 */
function myModule_form_search_form_alter( &$form, &$form_state, $form_id ){

    $form['myM_options']['entity'] = array(
                                            '#type' => 'radios',
                                            '#title' => 'Search by',
                                            '#default_value' => 'gene',
                                            '#options' => array(
                                                                "gene" => "Genes",
                                                                "ortholog" => "Orthologs",
                                                                "microarray" => "Microarray Features"
                                                            ),

                                        );
    $form['myM_options']['plant'] = array(
                                            '#type' => 'checkboxes',
                                            '#title' => 'Choose plants',
                                            '#options' => formatPlants(),
                                            // select all checkboxes by default
                                            '#default_value' => array_keys(formatPlants()),
                                        );
    $form['#validate'][] = 'myModule_search_validate';
    $form['#submit'][] = 'myModule_search_form_alter_submit';
}
/**
 * validation functoin
 */
function myModule_search_validate( $form, &$form_state ){
    // this works as expected
    form_set_value($form['basic']['processed_keys'], trim($form_state['values']['keys']), $form_state);

    // this doesn't !!!
    form_set_value($form['myM_options']['entity'], $form_state['values']['entity'], $form_state);
    form_set_value($form['myM_options']['plant'], array( 'id_1', 'id_2' ), $form_state);
}

$form: An associative array containing the structure of the form,
  which is passed by reference. Form validation handlers are able to
  alter the form structure (like #process and #after_build callbacks
  during form building) in case of a validation error. If a validation
  handler alters the form structure, it is responsible for validating
  the values of changed form elements in $form_state['values'] to
  prevent form submit handlers from receiving unvalidated values.

So your form validation function should be as the following:

/**
 * validation functoin
 */
function myModule_search_validate( &$form, &$form_state ) {
  // function body
}

Then in your form submit function you need to set $form_state['rebuild'] = TRUE as following:

/**
 * submit functoin
 */
function plant_Ontlogy_search_form_alter_submit( &$form, &$form_state ) {
  // function body

  $form_state['rebuild'] = TRUE;
}

If setting state rebuild to TRUE didn't work with you by itself, try to set default value as the following example to each additional field:

$form['myM_options']['entity'] = array(
  '#type' => 'radios',
  '#title' => 'Search by',
  '#default_value' => isset($form_state['values']['entity'])? $form_state['values']['entity'] : 'gene',
  '#default_value' => 'gene',
  '#options' => array(
    "gene" => "Genes",
    "ortholog" => "Orthologs",
    "microarray" => "Microarray Features"
  ),
);


Modifying twig file to show elements side-by-side I am working on views with embedded filters and my resultant view fields have the below twig setup:

 {% set index = 0 %}

       {% for key, field in fields -%}
        {% if index == 0 or index == 5 %}

        {% endif %}

          {%- if field.wrapper_element -%}
            <{{ field.wrapper_element }}{{ field.wrapper_attributes }}>
          {%- endif %}

          {%- if field.label -%}
            {%- if field.label_element -%}
              <{{ field.label_element }}{{ field.label_attributes }}>{{ field.label }}{{ field.label_suffix }}</{{ field.label_element }}>
            {%- else -%}
              {{ field.label }}{{ field.label_suffix }}
            {%- endif %}
          {%- endif %}

            {%- if field.element_type -%}
              <{{ field.element_type }}{{ field.element_attributes }}>{{ field.content }}</{{ field.element_type }}>
            {%- else -%}
              {{ field.content }}
            {%- endif %}

          {%if index == 4 %}

              <button class="button js-form-submit form-submit btn-info btn" type="button" value="Btn1" name="">Btn1</button>

              <button class="button js-form-submit form-submit btn-info btn" type="button" OnClick = "window.print();" value="PRINT" name="">PRINT</button>

          {% endif %}

        {%- if field.wrapper_element -%}
            </{{ field.wrapper_element }}>
          {%- endif %}

        {% if index + 1 == fields | length %}
          Click to go to next page
          {% endif %}
        {% if index == 4 or index + 1 == fields | length  %}

        {% endif %}
        {% set index = index + 1 %}
      {%- endfor %}

In this setup the lable is showing above and then the text beneath. Is there a way to make them show next to each other:

Current output:

 label:
 Answer

Desired output:

label:answer

[![enter image description here][1]][1]

Any help?!!

It’s likely because field.label_element is a p tag, which makes the new line.

Try to use span instead, like this:

{{ field.label }}{{ field.label_suffix }}

  {{ field.content }}

You can also add a
 tag after the closing a tag to make sure that all label/content sets are shown on separate lines.

Since the above did not work in your case, you can add a div around the two elements and then you can add some simple flexbox styling in your css to get the desired result.


Is it possible (and within convention) to insert a hidden field in an views exposed filter to control form content (e.g for re-submit search)? Examples:

(my requirement) when wanting to control the content of the view title for a listing of locations (E.g. title "venues near you") created using a view with Drupal module ip_geoloc ("IP Geolocation Views & Maps") based on the user's detected location (via html5 geo location) and then offering further searches (e.g. a different specific location) and wanting to display a different title in those results "venues near New York City"
simpler example "search again" for subsequent displays of the form (an user-visible views exposed filter).

For example 1., I'm currently using hook_views_pre_render in my own custom module to compare the submitted value with the detected location to be able to set a custom title for the view, snippets (note, not full declaration and module) of how I get each of these here:

    $locationAsString = "";

    if (function_exists('ip_geoloc_get_visitor_location') ) {
      $locationAsArray = ip_geoloc_get_visitor_location();

      // debug
      //dpm($locationAsArray);

      if ( isset($locationAsArray['locality']) ) {
        $locationAsString = t($locationAsArray['locality'].", ".$locationAsArray['country']);
      }
    }

    $submittedLocationAsString = "";
    if ( isset($view->exposed_raw_input['field_geofield_distance']['origin'] ) )
    {
       $submittedLocationAsString = $view->exposed_raw_input['field_geofield_distance']['origin'];
    }

    // debug:
    //drupal_set_message( "submitted location is: ".$submittedLocationAsString );
    //drupal_set_message( "actuallocation is: ".$locationAsString );

    if ( $locationAsString == $submittedLocationAsString )
    {
      $view->build_info['title'] = "We think you're near ".$locationAsString.". ".$thereAreAsString." here.";
    }
    else
    {
      $view->build_info['title'] = $resultsAsString." near ".$submittedLocationAsString;
    }

My ideal solution

But as you can see, this straight compare is not necessarily that robust. To determine the title I want, I think it may actually be better to insert a hidden field in the form, in hook_form_alter and detect the value/presence of this field in cgformutils_views_pre_render - is this approach within convention and not 'illegal' or bad practice?

Though I am providing the solution for the question which you have asked but as per your description I understand you are looking to achieve content boosting with views.

It's a nice idea which has been implemented on some websites like meetup.com, where they boost the local event at top when you visit & these works for anonymous users too as well as authenticated.

You will need 3 modules to achieve this - Location, Smart IP & Views.

I have written a blog post about configuring them to achieve this, which you can find at - http://drupalconnect.in/content-boosting-views

I will recommend you to try this if you trying something like this :)


force views to bring a specific nid I want to have a views with this Filter criteria

Content: Nid (= 2410)
OR
Content: Type (= news) AND
Content: value (= high) AND
Content: published (Yes)
OR
Content: Type (= multimedia) AND
Content: category (<> cinema) AND
Content: piblished (Yes)

and Sort criteria :

Content: Post date (desc)

and just need to display 10 items.

actually, I need to force views to bring one or more NIDs. But when it sorts the results by post date if the specified nid is older than the 10 first results it does not appear in the results.

How can I solve the problem?

I can think of two solutions. I will improve my solution a bit if you clarify exactly what the concept is behind the fixed node ID.

Solution 1: Custom field

Create a custom boolean field (working just like the node.sticky property).
Filter and sort your view by the boolean property.

The advantage of this approach is that the admin would be able to change the hard-coded default node you want to display by simply updating the custom field from the node form. Also, they would be able to specify more than one such forced-appearance nodes, which is good in certain cases.

Solution 2: Custom sort handler

You can write  a custom views sort handler and add an ORDER BY n.nid = 2410 DESC.
You will have to ensure that this sort is placed before the other sorts though.

BTW, as an additional suggestion, if you are using a hard-coded nid in logic, then make sure nobody can delete that node, otherwise you will have to change the relevant code every time someone deletes that node by mistake.

Hope this helps! Good luck.


How to add  around two blocks? In D7 I have a search view but would like to change some layout of it.

My current HTML situation is:

<div id="block-block-12"  .....

<div id="block-block-13"  .....

<div id="block-block-14"  .....

In the current layout:

 --------------------------
|            |            |
|     B12    |     B13    |
|            |     B14    |         |
---------------------------

I would like to change this into

 <div id="block-block-12"  .....

 <div id="block-block-13"  .....

 <div id="block-block-14"  .....

The reason for this is that I would like to have a 100% background color styling with the help of class xxtr.

I set the width of all block at 33.3% but then the display is:

 ------------------------------------
|            |            |         |
|     B12    |     B13    |   B14   |
|            |            |         |
-------------------------------------

While the result should be with all the same background color:

 ------------------------------------
|            |            |         |
|     B12    |     B13    |   empty |
|            |     B14    |         |
-------------------------------------

I add a custom tpl for this query but do not understand how to get that extra div around these blocks.

The tpl file.

<?php

?>
<div class="<?php print $classes; ?> view--page">

        <?php print render($title_prefix); ?>
        <?php if ($title): ?>
            <?php print $title; ?>
        <?php endif; ?>
        <?php print render($title_suffix); ?>
        <?php if ($header): ?>

                <?php print $header; ?>

        <?php endif; ?>

        <?php if ($exposed): ?>

                <?php print $exposed; ?>

        <?php endif; ?>

        <?php if ($attachment_before): ?>

                <?php print $attachment_before; ?>

        <?php endif; ?>

        <?php if ($pager): ?>
            <?php print $pager; ?>
        <?php endif; ?>

        <?php if ($rows): ?>

                <?php print $rows; ?>

        <?php elseif ($empty): ?>

                <?php print $empty; ?>

        <?php endif; ?>

        <?php if ($pager): ?>
            <?php print $pager; ?>
        <?php endif; ?>

        <?php if ($attachment_after): ?>

                <?php print $attachment_after; ?>

        <?php endif; ?>

        <?php if ($more): ?>
            <?php print $more; ?>
        <?php endif; ?>

        <?php if ($footer): ?>

                <?php print $footer; ?>

        <?php endif; ?>

        <?php if ($feed_icon): ?>

                <?php print $feed_icon; ?>

        <?php endif; ?>

<?php /* class view */ ?>

Any suggestion ?

I solved this by adding the view of the second box in the footer of the first box and add the php code of the third box in the footer of the second view. This way only one box is shown and with the help of the blok_wrapper css can be used to layout this template.


Need help adding an action to registration and user form submit I'm a Drupal frontend developer with limited experience with coding PHP and scripts. I believe the task is fairly simple for a drupal backend developer (hopefully).

Here is the basics of what we are trying to achieve:
We need to execute a function upon submitting form feilds of user-register-form and the user_profile_form. Both of the functions basically take the field data and send it to our CRM tool. We have tested both of these functions using an HTML based form and can confirm that both work properly. The challenge for me is how to trigger these functions upon existing Drupal forms.

Here is the example of the script that needs to be triggered for the user-registration-form:

$(document).ready(function () {
            $("#user-register-form #edit-submit").click(function () {
                alert("Hello world");
                //var ulMembers = $('#ulMembers');
                var member = new Object();
                member.name = $("#edit-field-first-name-und-0-value").val();
                member.country = $("#edit-field-country-und").val();
                member.emailId = $("#edit-mail").val();
                member.description = $("#edit-field-description-und-0-value").val();
                member.membershiplevel = $('#edit-field-membership-price-und').val();
                $.ajax({
                    url:
'http://gsplatformapi-test.ap-southeast-1.elasticbeanstalk.com/api/Values',
                    //url: 'http://localhost:54915/api/Values',
                    type: 'POST',
                    dataType: 'json',
                    data: member,
                    success: function (data) {
                        alert(data);
                        $('#successmessage').text('record inserted');
                    },
                    error: function (error) {
                        console.log('Error in Operation');
                    }
                });
            })
        })

Here is the function that needs to be triggered user_profile_form. It is basically the same type of function as the one above, just with more fields:

      $(document).ready(function () {
            $("#user-profile-form #edit-submit").click(function () {
                //var ulMembers = $('#ulMembers');
                var member = new Object();
                //member.name = $("#edit-field-first-name-und-0-value").val();
                member.country = $("#edit-field-country-und").val();
                member.emailid = $("#edit-mail").val();
                member.website = $("#edit-field-website-und-0-url").val();
                member.description = $("#edit-field-description-und-0-value").val();
                member.membershiplevel = $('#edit-field-membership-price-und').val();
               $.ajax({
                    url:
'http://gsplatformapi-test.ap-southeast-1.elasticbeanstalk.com/api/Values/' +
$('#txtName').val(),
                    type: 'PUT',
                    dataType: 'json',
                    //Accept: '*/*',
                    //Origin: 'http://localhost:64636/',
                    data: member,
                    success: function (data) {
                        //
                        alert(data);
                        $('#successmessage').text('record updated');
                    },

                    error: function (error) {
                        console.log('Error in Operation');
                    }
                });
            }
            )
        }
        )

If anyone can help point me in the right direction I would greatly appreciate it. Thanks very much!

You must implement hook_form_alter, like this:

function MODULENAME_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'user_register_form') {
    $form['#submit'][] = 'name_of_callback_function';
  }
}

NOTE: You can also implement this hook in your theme. Remember to clear the cache.


Understanding State of JS in Drupal I have a simple contributed module that I have written. It has pretty basic javascript. I decided to clean it up and write it in vanilla js, removing jQuery since that seems to be the direction we're going. Here is the resulting code...

const viewSourceLinks = document.querySelectorAll(
  '.simple-styleguide--view-sourecode'
);

[].forEach.call(viewSourceLinks, el => {
  el.addEventListener('click', () => {
    el.nextElementSibling.classList.toggle('active');
  });
});

const calculableElements = document.querySelectorAll('.calculate');

[].forEach.call(calculableElements, el => {
  const measuredElement = el.querySelector('.measure');
  const info = el.querySelector('.info');
  const lineHeight = `line-height: ${
    window.getComputedStyle(measuredElement).lineHeight
  }`;
  const fontSize = `font-size: ${
    window.getComputedStyle(measuredElement).fontSize
  }`;
  const margins = `margin: ${
    window.getComputedStyle(measuredElement).marginBottom
  }
        ${window.getComputedStyle(measuredElement).marginRight} ${
    window.getComputedStyle(measuredElement).marginBottom
  } ${window.getComputedStyle(measuredElement).marginLeft}`;

  info.innerHTML = `${fontSize}<br/>${lineHeight}<br/>${margins}`;
});

My question is, is this ok? Is this good enough to include as is? In general, it seems the advice is to always add your javascript within attached behaviors.

However, once I go down that road, I'm pretty much having to include jQuery in the wrapper. And I would much rather just have vanilla javascript.

The resulting code with behaviors ends up being something like this...

(($, Drupal) => {
  Drupal.behaviors.simpleStyleguide = {
    attach(context) {

      const viewSourceLinks = context.querySelectorAll(
        '.simple-styleguide--view-sourecode'
      );

      [].forEach.call(viewSourceLinks, el => {
        el.addEventListener('click', () => {
          el.nextElementSibling.classList.toggle('active');
        });
      });

      const calculableElements = context.querySelectorAll('.calculate');

      [].forEach.call(calculableElements, el => {
        const measuredElement = el.querySelector('.measure');
        const info = el.querySelector('.info');
        const lineHeight = `line-height: ${
          window.getComputedStyle(measuredElement).lineHeight
        }`;
        const fontSize = `font-size: ${
          window.getComputedStyle(measuredElement).fontSize
        }`;
        const margins = `margin: ${
          window.getComputedStyle(measuredElement).marginBottom
        }
              ${window.getComputedStyle(measuredElement).marginRight} ${
          window.getComputedStyle(measuredElement).marginBottom
        } ${window.getComputedStyle(measuredElement).marginLeft}`;

        info.innerHTML = `${fontSize}<br/>${lineHeight}<br/>${margins}`;
      });

    },
  };
})(jQuery, Drupal);

I've also read that if you have BigPipe enabled, you have to include jQuery. Not sure if that's true or not.

The vanilla js code above seems to be working. I just want to know that I'm doing this right, and that I'm not violating some Drupal standard by not wrapping it in a behavior.

Note: I should mention there is no ajax behavior in this module. If there were, perhaps I would have to use behaviors and context.

The best practice is still to use Drupal's behaviors system even when not relying on jQuery. See Drupal 8 Drupal.behaviors without jquery for reference.

That said, I think you're on the right path. I find jQuery just slows down the page load when vanilla JS will usually do the trick. That's just my opinion and there's a lot of debate out there.


Drupal 7 theme similar to Wordpress Twenty Fourteen theme? I'm looking for a Drupal 7 theme similar to the wordpress theme Twenty Fourteen. The main factors that I would like to find in a drupal theme are

the image grid for posts similar to the grid pictured on the theme page
the menu locked into the side
responsive

I was hoping to find something with as little modification needed as possible, but I'm not opposed to creating a subtheme and doing some customization. I tried searching some drupal theme repositories like the offerings available on themeforest and template monster but I haven't found anything that caught my eye.

You're going to find Drupal is pretty limited on well made pre-built themes. If you're looking for a good grid system, NineSixty and Boostrap provide a good base to build upon. As far as menu settings and post output, this is typically custom to each site. The post output, for instance, would rely on a custom content type and View to display this information.


URL Aliases - Patterns Error I'm getting a list of the following errors in my new drupal website. Any idea where this is coming from and what I need to do to fix it?

The Default path pattern (applies to all content types with blank patterns below) is using the following invalid tokens: [node:title].
The Default path pattern for Applications (applies to all Applications content types with blank patterns below) is using the following invalid tokens: [node:title].
The Default path pattern for Careers (applies to all Careers content types with blank patterns below) is using the following invalid tokens: [node:title].
The Default path pattern for Events (applies to all Events content types with blank patterns below) is using the following invalid tokens: [node:title].
The Default path pattern for Executive Team (applies to all Executive Team content types with blank patterns below) is using the following invalid tokens: [node:title].
The Default path pattern for News (applies to all News content types with blank patterns below) is using the following invalid tokens: [node:created:custom:Y], [node:created:custom:m], [node:created:custom:d], [node:title].
The Pattern for all Products paths is using the following invalid tokens: [node:title].
The Default path pattern for SlideShow (applies to all SlideShow content types with blank patterns below) is using the following invalid tokens: [node:title].
The Default path pattern for Solutions (applies to all Solutions content types with blank patterns below) is using the following invalid tokens: [node:title].
The Default path pattern for Test Type (applies to all Test Type content types with blank patterns below) is using the following invalid tokens: [node:title].
The Default path pattern for Webform (applies to all Webform content types with blank patterns below) is using the following invalid tokens: [node:title].
The Default path pattern (applies to all vocabularies with blank patterns below) is using the following invalid tokens: [term:vocabulary], [term:name].
The Pattern for user account page paths is using the following invalid tokens: [user:name].

Just in case other might encounter it and bump in this page. To recap on how we fixed this error. In @MG1 case, restore the database from live site and downgrading the php version on her local machine from 7.0.8 to 5.4.42 and upgrading the Drupal core module in latest version did fixed the problem all errors are gone.

We also encounter this one just in case other's encountered it.

  Fatal error: Call to undefined function
  form_process_autocomplete() in
  /Users/***/Documents/Sites/Link-New/includes/form.inc on line
  1850

this one help us out in trouble https://www.drupal.org/node/2610498

Note:
This might be fix in other way but in MG1 case this solved the problem.


Display image and text above form I have form built with form api in Drupal 8,
now, i want to show an image and some text description on top of that form, meaning, before the form is rendered, what i can think of is, doing a node_load and then suffix and prefix with the node_load value or entity load,
but my question is, in case i write a function for node_load or entity_load, where would i call the return value of these functions and how ?
i am thinking of something like this :

$form['image_div'] = array(
            '#prefix' => '
',
            '#suffix' => '
',
        );

how can i call the path to image here, which is a function return value.

Example:

 $theme = \Drupal::theme()->getActiveTheme();
 $form['image_div'] = array(
 '#prefix' => 'getPath() .'/images/smile.png">',
        '#suffix' => '
',
    );


Does hook_node_info() have to be in .module or can it be in .install? due to some code sharing it would help me quite a bit if I could put hook_node_info() to a .install file instead of a .module file. Now, from what I've tested it doesn't seem that it could be a problem but then every tutorial says you have to put it in .module file.

And the official documentation is silent in regards to this problem. So my question is, can I do it without braking something?

hook_node_info should be in the .module file. However, you could implement the hook in the module file and then just call module_load_install from there to include another function in the .install file, if that helps. Another option is to export the content type using a module such as Features instead.


Same dates for publish and post I am using the published date module.

The posted date, and published date are the same for the nodes. Does anyone know any reason why that is so?

The publish date can change, like after unpublishing and republishing some content. The post date is rather fixed, it's the date the content is created...


Is there a way to add a dynamic URL token to images so that the move from local host to live doesn't require code change? Is there a way to add a dynamic URL token to images so that the move from local host to live doesn't require code change?

When uploading images in content, the path changes form localhost to live, how can I have it consistent so the database can be exported without changes?

I would like to leave out the name of the site in the path

Handling of the links in the field having a WYSIWYG editor, or any other long text field is a common issue when the site moves from one server (say dev) to other (say stage or production).
The links should be saved in such a way that they do not break.

Pathologic module does that for you.

  Pathologic is an input filter which can correct paths in links and images in your Drupal content in situations which would otherwise cause them to “break;” for example, if the URL of the site changes, or the content was moved to a different server. Pathologic can also solve the problem of missing images and broken links in your site’s RSS feeds. See more example use cases on the documentation page.


change where Authoring information and Publishing options Checkbox is displayed Currently Authoring information and Publishing options have options within their own how do you call it "tab/page". Example: When you edit a page you have to click Publishing options in order to see the checkbox Published.

I want that checkbox Published + it's functionality when checked somewhere else within the edit content page.

So there is no step where you have to click Publishing options. Should I do this with a custom block?

Can anyone assist because I really don't know how to do this :)

In the admin/content page
1. at the top there is filters provided to sort content by number of options like for e.g filter by content type, published or unpublished.
2. then below that there is drop down containing list of actions like "publish selected content", "delete selected content", etc
3.You can select the check box corresponding to the content you want the action to perform and submit.


Entity Query field condition for Webform submissions I'm trying to query webform submissions based on a field value. The field is called "ticket_for".
Somethings I tried and do not work:

    ->condition('ticket_for',$adnummer)
    ->condition('webform_submission_data:ticket_for',$adnummer,'CONTAINS')
...

What kind of condition should I be using in a query like this?

$query = \Drupal::entityQuery('webform_submission')
->condition('webform_id', 'ticket')
->condition('entity_id', $eventID)
->condition('webform_submission_data:ticket_for',$adnummer,'CONTAINS');

As imclean says webform_submission_data stores as EAV model. You can also do the following, If you need to have just one condition ticket_for == $adnummer.

$select = \Drupal::service('database')
->select('webform_submission_data', 'wsd')
->fields('wsd', array('sid'))
->orderBy('wsd.sid', 'DESC')
->condition('wsd.webform_id', 'your_webform_id', '=')
->condition('wsd.name', 'ticket_for', '=')
->condition('wsd.value', $adnummer, '=')
->execute();

$results = $select->fetchAll(\PDO::FETCH_COLUMN);
if ($results != null && count($results) >= 1) {
    $storage = \Drupal::entityTypeManager()->getStorage('webform_submission');
    $submissions = $storage->loadMultiple($results);
}

Now just loop the $submissions. Done.


Move term to a different vocabulary I want to move a term from one vocabulary to another.  In drupal 7 one can use taxonomy manager to do this but drupal 8 branch has not implemented MOVE yet and the module has not received any update in some time.

Taxonomy merge that is suggested in this thread has not even been ported in drupal 8 yet.

Thus the only way that is left to do such a task is programmatically.

How do you update programmatically the vocabulary or a term?

You should load existing term using term id and then update vid of term from new vocabulary vid then save it.

use Drupal\taxonomy\Entity\Term;

$term = Term::load($tid);
$term->vid->setValue('ID value');
$term->Save();


How can I implement a feature to change settings? in our site we have a country field in a registration page of our drupal site. admin can download the all registered users as excel report. I added a new country field in my users.XLS report in data export option at Structure > Views > Administrator:users in my development site.

How can I deploy these changes in my staging site(other development site) by using the Features module?
Which feature components can I choose while creating the feature?

1) If you made the changes in only views then only export the view form your local development and import it in your production server

or

2) If you added an new field in content type then goto admin/structure/features/create select the field from FIELD INSTANCES (x) (field_instance) and module will select the dependency automatically then add Name in GENERAL INFORMATION and download and upload it in your module folder and enable it and then follow the 1 point

Note: First try it on your another test development and then on production


Programatically create field collection into Profile2 on new user creation I've set up my own custom multi-step registration form, because I just couldn't find a way of making anything out there do what I want. I've found other questions on here like this one and this one which have basically got me 95% there. My main problem now is that I've got a series of field collections in my Profile2 fields, and I just can't seem to find out what my code needs to be in order to get it done properly.

*At this point in the code I've created a new user ($user), and their profile2 ($profile2) and I'm trying to format my fields from my form so that I can throw them all into the $profile2 object.

field_activities

field_start_year
field_end_year
field_text

My code so far is:

$field_collection = entity_create('field_collection_item', array('field_name' => 'field_activities'));
$field_collection->setHostEntity('profile', $profile2);
$field_collection->field_start_year = $entry['start_year'];
$field_collection->field_end_year = $entry['end_year'];
$field_collection->field_text = $entry['text'];
$field_collection->save(FALSE);

And the error I'm getting is:

  Fatal error: Call to a member function setHostEntity() on a non-object

Which would make more sense to me if $profile2 wasn't an object, but it is.

I've got too many unknowns to figure this out at the moment, is it the right code? can I build a create a field collection item on a newly created profile2 object? do I populate all the fields of the profile object first, and then once it's saved, then add the field collections, etc.

Fatal error: Call to a member function setHostEntity() on a non-object

The error means that you are trying to call setHostEntity() method on a non-object, in other words the $field_collection is not an object (NULL probably).

So please check one line before, which is:

$field_collection = entity_create('field_collection_item', array('field_name' => 'field_activities'));

So basically you are trying to load field_activities field collection, but it is not there, therefore your $field_collection is FALSE as per entity_create  API:

  Return value: A new instance of the entity type or FALSE if there is no information for the given entity type.

Therefore please make sure your field_activities exists as field collection (e.g. at /admin/structure/field-collections), or add additional failing scenario to your code, so when $field_collection is FALSE, do not execute further code.

For valid examples using field collections, check: Entity metadata wrappers page.


How to filter a view to show current month I am building a Church Management System. I have a contact type for individuals. One field they have is D.O.B. which is a date popup field.

I want to create a block that lists people and their D.O.B. and have it filtered to only show those whose birthdays are in the current month.

I created the block and have it showing the people and their D.O.B. but how do I get it to filter to show only the people in current month?

Thanks

in the view select filter type your dob field select apply then another popup opens in which you have to select "Date selection form element" as popup (Provided you have enabled the Date Popup module in Date API package) then "Filter granularity" by month select apply operator should be equal to and in front of that theirs a option select a date .. you have to select enter a relative date and in relative date type now.apply and save


How to get Taxonomy Menu working properly with Contextual Filters in Views? I can't get taxonomy menu links working properly with contextual arguments in Views.

This is what I have done:

0) I create a menu called: Catalog menu

1) I create a Vocabulary called: Catalog terms and in the Taxonomy menu area I set Catalog menu for the Menu location (I have Taxonomy menu module enabled which allow me to do this)

2) I the Catalog vocabulary I added 2 terms: Cars and Phones

3) In admin/config/search/path/patterns I set Pattern for all Catálogo taxonomy paths to catalog/[term:name]

4) In admin/structure/block I enable the Catalog menu block to the First sidebar

So far so good. I have a menu in my first sidebar with the links: cars and phones.

5) I have a content type called Products with a field of the type Term reference called: field_catalog

6) Now I create a new view called: Catalog view where I need to show Products which has an specific term in the url. The path of this view is catalog

7) I added a RELATIONSHIP called: Content (field_catalog)

8) I added a CONTEXTUAL FILTERS called Taxonomy term: Name using the previous relationship

Now if I enter "cars" in the Auto preview Preview with contextual filters: area it works fine. It only shows products that has cars term.

So the Catalog Menus is fine and the view is fine.

But if I go to the url www.mysite.com/en/catalog/cars it takes me to the list of content that has the temr cars. Here I need to show the Catalog view passing cars as an argument and not that list.

You have made one mistake that is easy to make. The alias created in the menu doesn't change the "true" url. So when you go to catalog/cars Drupal will perceive that as taxonomy/term/[tid].

What you could do instead is to enable the default taxonomy term view that ships with Views (which uses taxonomy/term/[tid] as the path) and then set it up like you want.

See Screen shot:


How to add content title as dropdown list for exposed filter? I have a node ABC and using view where content is of type ABC. I have content title as a field in Views.

What is the way in which I can get a drop down for field content title in the filter criteria?

You have to implement a hook_form_alter with a custom module like this:

    function mytools_form_alter(&$form, $form_state, $form_id) {
  if($form_id == 'views_exposed_form') {
    //unset($form['average']);
    $form['average'] = array(
      '#type' => 'select',
      '#options' => array(0 => t('<any>'), 20 => '*', 40 => '**', 60 => '***', 80 => '****', 100 => '*****'),
      '#default_value' => 0,
      '#title' => t('The average vote is more than'),
    );
  }
}

Where the form_id is your current views form ID (you can see it with firebug in your code).


How to change the view mode programmatically? I want to change the view mode of node programmatically. I used hook_preprocess_node(&$vars) and set the view mode:

function moduleName_preprocess_node(&$vars) {
      // if conditions to apply particular view mode
      $vars['view_mode'] = 'teaser';
      $vars['elements']['#view_mode'] = 'teaser';
}

But this is not working as expected. Am I missing something here?

Altering the view mode in the preprocess function is doing it too late.
The correct way to alter the view module is implementing hook_entity_view_mode_alter(), which is called before the entity content is rendered. For example, in node_view(), that hook is invoked from node_build_content(), which is the first function called from node_view().

  if (!isset($langcode)) {
    $langcode = $GLOBALS['language_content']->language;
  }

  // Populate $node->content with a render() array.
  node_build_content($node, $view_mode, $langcode);


Get Template Variables in my Custom Module I am new in drupal. I am trying to get a variable from a template file e.g. maintenance-page.tpl.php and want to get $title variable in a form e.g. admin/config/development/maintenance form. This form will contain a field/textbox to set a custom title and I want to print that custom title on maintenance-page.tpl.php page. How could it be implemented with custom module. I am using Drupal 7. Thanks in Advance.

In Drupal 7 getting global module specific settings or module-site configuration settings is done via:

variable_set

  Sets a persistent variable.

variable_get

  Returns a persistent variable.

variable_del

  Unsets a persistent variable.

This is to be used for global settings which means it is used site-wide. In your use-case it seems appropriate to use.

For your custom form you will get the variable when you build the form, and set the variable in the form's submit handler. If you are using system_settings_form, then the process is even easier as all you have to do is to make sure that your form element for the title is named exactly the same as your persistent variable.  For an example please refer to: How to add a custom admin settings form to accept variable values in Drupal

To print the variable in your template you can either get the variable using variable_get in a preprocess function and set a preprocess variable for it which you then use, or you can just get the variable directly within the template. How do you know which method to use? If the template file is rendered because of a theme function, then there will be a preprocess function for it. But don't break your head to much over this one. Because getting a variable using variable_get is such a small operation, you might as well just do it directly in the template file.


Change the way nested views behave In drupal 7 I have news posts grouped by the value of certain fields, I can filter them and display correctly the latest # news per category in a tabbed view: one tab per category. I also have another tab, which should collect the last news item from each category and I'm struggling to do it right.

I tried the nested views approach but despite creating a new template and new "helper" views with which I had hoped to strip all unnecessary tags, many tags are still created, breaking the layout (not really BREAKING, but it's not as it should).
Could someone suggest a way to strip the tags or (better!) to do this in one go?

I'm not a php/drupal dev but if assisted I can understand code.

Update:

I have narrowed down my problem to the fact that all items are rendered in one single row by the external view. This breaks the layout because there's no </li><li...> between them. Instead, they are wrapped by divs. I have worked on this but I don't know how to make them appear on separate rows and it seems all the remaining wrapping is created by the last print $row in the chain.
Can I change the behavior of the print or make the view display each field on a separate row?

In the end the Semantic Views module helped me achieve what I wanted to do.

I specified that rows had no tag and fields instead were <li>, I had to modify the template too, for consistency and theming reasons to reproduce the original layout of a normal view.


Installing a v8 module If a contrib module's info.yml contains core: 8.x and not core_version_requirement: ^8.8 || ^9, how can a site be upgraded to Drupal 9 using composer?
composer update downloads modules in "require": { which needs to be before "patches": { because there needs to be a module before it can be patched. Assume the patch patches the info.yml file with core_version_requirement: ^8.8 || ^9.
So composer update can't resolve to an installable set of packages and throws errors like this:
- Root composer.json requires drupal/entity_jump_menu 1.1 -> satisfiable by drupal/entity_jump_menu[1.1.0].
- drupal/entity_jump_menu 1.1.0 requires drupal/core ~8.0 -> found drupal/core[8.0.0-beta6, ..., 8.9.x-dev] but it conflicts with your root composer.json require (^9.1).

It looked like the answer was changing drupal/core and drupal/core-dev to a value of "^8.8||^9.1". composer update will now run, except the site is still building in version 8.9.13.

Following the suggestions on the mediacurrent blog post, I changed composer.json to the following
  "repositories": [
      {
          "type": "composer",
          "url": "https://packages.drupal.org/8",
          "exclude": ["drupal/entity_jump_menu"]
      },
      {
          "type": "git",
          "url": "git@git.drupal.org:issue/entity_jump_menu-3130218.git"
      }
  ],
  "require": {
      ...
      "drupal/entity_jump_menu": "dev-3130218-drupal-9-deprecated",
      ...
  },

Which downloads the fork of the module, into vendor/drupal/entity_jump_menu. Unfortunately Drupal and/or Drush don't see the module in that directory.
I'm going to try the computerminds solution next.

The solution from computerminds adds the fork of the module to the modules/contrib directory. Here's the code.
"repositories": [
    {
        "type": "package",
        "package": {
            "name": "drupal/entity_jump_menu",
            "type": "drupal-module",
            "version": "dev-3130218-drupal-9-deprecated",
            "source": {
                "type": "git",
                "url": "git@git.drupal.org:issue/entity_jump_menu-3130218.git",
                "reference": "268adc649cfb4ad716751a8643e60f5df4dbb80d"
            }
        }
    },
    {
        "type": "composer",
        "url": "https://packages.drupal.org/8"
    }
],
"require": {
    ...
    "drupal/entity_jump_menu": "dev-3130218-drupal-9-deprecated",
    ...
},

Thanks for pointing me in the right direction.

You'll need to fork the module. This is more of a pain than patching but it's much better now that you can make issue forks on drupal.org.
Here's a detailed tutorial.
The basic workflow is this:

Make an issue fork on drupal.org that updates the version requirement.
Add the forked repo to your composer.json and update your site that way.
When the module gets a real Drupal 9 release, switch your composer.json back to the release.


How to programatically resize image and respect aspect ratio when saving a node I was wondering if there is an api call that lets me resize an image and respect the aspect ratio.  Right now I am using image_resize to successfully resize an image to a given width and height but it ignores aspect ratio and distorts the images.  Is there an api call that will allow me to do this and maintain original aspect ratio?

image_scale() will do this if you just provide a width or a height rather than both.


Custom ckeditor.styles.js file with WYSIWYG module I am trying to customize the "Font style" dropdown in CKeditor through the WYSIWYG module, but I see no way to specify a path for ckeditor.styles.js in the wysiwyg module's profile editor.

Refer to this post for futher information - it says there should be a way to specify a location for that file.

These are 2 ways (there are certainly more) to add custom ckeditor stylesets using the drupal wyswiwyg module.

Using the contributed module Ckeditor Styles
Using hook_wysiwyg_editor_settings_alter as follows:

(code "inspired" by ckeditor_styles module)

In a custom module add the hook_wysiwyg_editor_settings_alter implementation:

/**
 * Implements hook_wysiwyg_editor_settings_alter().
 *
 * @param type $settings
 * @param type $context
 */
function MYCUSTOMMODULE_wysiwyg_editor_settings_alter(&$settings, $context) {
  // We only add the settings to ckeditor wysiwyg profiles.
  if ($context['profile']->editor == 'ckeditor') {
    $format = $context['profile']->format;
    $path = drupal_get_path('module', 'MYCUSTOMMODULE') . '/js';
    $settings['stylesSet'] = "mycustomstyleset:/$path/ckeditor_styles.js";
  }
}

and add a file named ckeditor_styles.js in a sub directory js of the custom module:

CKEDITOR.stylesSet.add('mycustomstyleset',
  [
    { name : 'Red', element : 'span', styles : {'color' : 'red' } },
    { name : 'CSS Style', element : 'span', attributes: { 'class' : 'my_style' } },
    { name : 'Marker: Yellow', element : 'span', styles : { 'background-color' : 'Yellow' } },
    { name : 'Heading 4' , element : 'h4' },
    { name : 'Blue Button', element : 'div', attributes : { 'class' : 'blue-button' } },
  ]);


Filter view results by day of the week instead of the date - Date Module I have a view which includes a date field, and I'd like to provide a filter for users to show only items from a certain day of the week. From what I can see, though, the date filter only allows you to select the date by which to filter. Is it possible to create a filter which will allow users to show, say, all nodes which have a date that falls on a Wednesday?

I think you have to use the Views Day of Week module to filter the result by day of week. Here is a quote from it's project page:

... Views Day of Week provides a simple filter plugin for Views 3 to enable filtering content that should be visible based on the current day of the week.
Example: With this module you can select that some content should be visible only on Mondays, some on Tuesdays and Thursdays and some only on Fridays.


Fatal PHP error on Drupal 7 with IIS Logging as Admin user on Drupal 7 website stored on an IIS machine, I get the following error:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]:
General error: 2006 MySQL server has gone away'
in E:\inetpub\wwwroot\teams\includes\database\database.inc:2139
Stack trace:
#0 E:\inetpub\wwwroot\teams\includes\database\database.inc(2139): PDOStatement->execute(Array)
#1     E:\inetpub\wwwroot\teams\includes\database\database.inc(664): DatabaseStatementBase->execute(Array, Array)
#2 E:\inetpub\wwwroot\teams\includes\database\database.inc(2318): DatabaseConnection->query('SELECT expire, ...', Array, Array)
#3 E:\inetpub\wwwroot\teams\includes\lock.inc(167): db_query('SELECT expire, ...', Array)
#4 E:\inetpub\wwwroot\teams\includes\lock.inc(146): lock_may_be_available('schema:runtime:...')
#5 E:\inetpub\wwwroot\teams\includes\bootstrap.inc(420): lock_acquire('schema:runtime:...')
#6 E:\inetpub\wwwroot\teams\includes\bootstrap.inc(442): DrupalCacheArray->set(Array)
#7 [internal function]: DrupalCacheArray->__destruct()
#8 {main} thrown inE:\inetpub\wwwroot\teams\includes\database\database.inc on line 2139

Any idea on how do I debug those statements? And how do I release locks?

Indeed, setting maximum allowed packet size in MySQL worked like charm. To solve, we've went to the [mysqld] section of my.ini and added the following:

[mysqld]
max_allowed_packet=100M

then restarted the Windows server machine in order to restart MySQL.

The only difference in IIS is that the machine required a boot.


Users can "promote" node for a fee? Basically I want a classified ad system where users can pay extra to make their ad more visible - sticky at the top of lists, for example.

lm_paypal or pay-per-node for the simple payment for posting a classified, but how about the extra payment for making it sticky? Any ideas?

The best answer I could come up with was simply have a different node type that is automatically sticky / treated differently by views, which can then be set as a different price using either of the two modules I mentioned in my question.


Timetable for event. i'm trying to create a timetable using Drupal 7. I need this timetable for an event.

At the moment I created it throught views but I think it is too much "heavy".

I did it in this way.

I created 3 content types: Speaker, Company and Agenda.
In the Agenda content type I've got the node reference fields pointing to Speaker and Company.
The event has got 3 streams.
Now I'm managing the display throught the views, I've created a basic page with a table and per each row (time) I've put one view (content) which shows 3 nodes (one per each stream).
this is a normal view wich shows title and body of the node.
To show the speaker and the company I've created another view (fields) with agenda nid such as contextual filter. I've put it inside agenda--node.tpl.php.
Then I've put another view inside agenda--node.tpl.php which create a js dialog with the topic, speaker and company info.
Basically we have in one page about 70 views...

Is it heavy?

I need to create something like this http://cph2010.drupal.org/sessions/timetable.html and the way I would like to create it is this http://groups.drupal.org/node/2567 with this dript style.

Does anyone know the right way to create a timetable with drupal?

Thanks in advance.

One simplification could be the following:

Create just one content type called presentation that has speaker, agenda, time, title, and company as fields (and anything else you want).

Then you create one view which lists nodes of type presentation.

In the fields portion, you select all the fields you think are relevant to show in the table, perhaps just title and speaker.  The title can be a link to the full content.
Perhaps have the style be 'grid' and order the items by 'time', so the ones in the same time slot are on the same row.

That's one idea to make it simpler.  Does it work in your case?


Create/Update a commerce order using parameters passed via the url Is it possible to Create/Update a commerce order using parameters passed via the url?

What options are out there to achieve this?

As far as I know, the only way to do this is with a custom module. It should implement hook_menu() to accept as many parameters as you need, and invoke a callback that uses the Drupal Commerce API like in this example.

[EDIT] There are three modules that may help you do this if you don't want to create a custom module yourself:

Rules link. It attaches a link to entity displays that triggers a rule. It passes the entity to the attached Rule
Rules link event. In some ways similar to Rules link, but from what I can tell, you can actually use the SKU (or other parameters) as an argument in the URL link, accessible to the Rule through a token [path:last] and so forth. Main difference between Rules Link and Rules Link Event here.
Commerce cart link. Similar to Rules link event, but works with ctools to create a token for the link, which increases security.