How to reuses page--front.html.twig for multiple pages I created a page--front.html.twig which allows me to create a distinctive front page.

How would I go about reusing this page to create a landing page, a page with an identical layout the front page has?

Implement hook_theme_suggestions_page_alter(), and you can suggest the template file used for those land pages.

I assume you are doing it from a theme; if you are doing it from a module, you can implement either hook_theme_suggestions_page_alter(array &$suggestions, array $variables) like for themes or hook_theme_suggestions_page(array $variables).

function mytheme_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  if ($your_condition) {
    $suggestions[] = 'page__front';
  }
}

The code you write for $your_condition depends from how you check which pages are your land pages. The following are some useful snippets you could need.

To get the internal path for the current page

$internal_path = Url::fromRoute('<current>')->getInternalPath();

Alternatively, the current path can be obtained with \Drupal::service('path.current')->getPath() (Drupal core uses both of those)
To get the node being viewed

if (!empty($variables['elements']['#node'])) {
  $node = $variables['elements']['#node'];
  // Get the content type.
  // $bundle = $node->bundle();
}


Create container.html.twig template for specific page I'm attempting to edit the search page.
I've edited container.html.twig to contain

{%
  set classes = [
    has_parent ? 'js-form-wrapper',
    has_parent ? 'form-wrapper',
  ]
%}

Search Results

{{ children }}

It works fine when I leave the file name as container.html.twig. But I'd like for it to only apply to the search page. I've tried naming it container--search-results.html.twig but that did not work.

How do I rename container.twig.html to only apply to my search page?

Am not sure if this contains the answer, but you should definitely read this:

Twig Debugging


Create taxonomy 'add terms' form into block I have two vocabularies named 'vocab_one' and 'vocab_two'. I create custom multiple blocks module named 'add library', in order to display the taxonomy 'add terms' form to each blocks.

Each block displayed on the same node in the content area. The position of 'Vocab Two Block' are above 'Vocab One Block'.

When I add new term on 'Vocab One Block', the new term is always stored in the 'vocab_two'. Then I switch position of the block. This time, the new term is always stored in the 'vocab_one'.

How to store a new term within selected vocabulary, without worrying about the block position?

here is my add_library.module:

function add_library_block_info() {
  $blocks['Vocab Two Block'] = array(
    'info' => t('Vocab Two'),
  );

  $blocks['Vocab Two Block'] = array(
    'info' => t('Vocab One'),
  );

  return $blocks;
}

function add_library_block_view($delta='') {
  $block = array();
  switch ($delta) {
    case 'Vocab Two Block':
      $block['subject'] = t('Add Vocab Two');
      $block['content'] = add_vocab_two();
      break;
    case 'Vocab Two Block':
      $block['subject'] = t('Add Vocab One');
      $block['content'] = add_vocab_one();
      break;
  }
  return $block;
}

function add_vocab_two() {
    module_load_include('inc', 'taxonomy', 'taxonomy.admin');
    $vocabulary = taxonomy_vocabulary_load(2);
    return drupal_get_form('taxonomy_form_term', $vocabulary);
}

function add_vocab_one() {
    module_load_include('inc', 'taxonomy', 'taxonomy.admin');
    $vocabulary = taxonomy_vocabulary_load(4);
    return drupal_get_form('taxonomy_form_term', $vocabulary);
}

Every block must have unique delta, so in hook_block_info first $blocks change 'Vocab Two Block' to 'vocab_block_first', second $blocks 'Vocab Two Block' change to 'vocab_block_second', then in 'switch' change first 'case Vocab Two Block' to 'case vocab_block_first' and second 'case Vocab Two Block' to 'case vocab_block_second'. Then show these two blocks on the same place.


Drupal 7: How can I display nodes of specific author in a taxonomy term? I've a question about taxonomy terms.
In my organization I've actors that work for me and, for each actor I created a taxonomy term containing some information, such as bio, an image etc.
Each actor can create content of type "post". I want display all contents of a specific actor in his own term.
So, if in actors vocabulary there are "alan", "jack" and "Lucy", whan an user reaches alan term, he can see all posts created by Alan, and so on.
For security I don't want the actors select terms when create posts.
I hope you can understand my question.

I probably wouldn't have used a taxonomy term to store that info, but that's not a big deal.

It sounds like you want a block containing the information in the taxonomy term to appear on a user's post.

You need an entity reference connecting a user/author with the appropriate taxonomy term.

Create View that is based on the taxonomy vocabulary. Use a "contextual reference" starting with the post's node id in the URL to a relationship to the author of the post to another relationship to the taxonomy term using the entity reference.


Disable delete button on a view under certain conditions I'm very new to Drupal 7. I have an administration screen created in Views to edit/delete my custom content type called events.

In my custom module, I'd like to disable the delete button under certain conditions. Is there any hook that I can use for this purpose?

The reason I like to do this is to prevent users from deleting 'certain' events.

Inside each user profiles, there is a field that defined which stores that user can edit/view. I like to make it that when people click on the delete button, if that store is not of their stores, they shouldn't be able to delete it, they should get redirected back with an error message.

Here is the code I have so far:

function my_modue_form_alter(&$form, &$form_state, $form_id){
    dpm($form);
    dpm($form_id);

    if ($form_id == 'myformid') {
      unset($form['op']);
    }
}

On the /delete screen, it doesn't print out anything.

Here is a screen shot of how the delete node page looks like:

And here is how the URL looks like:

http://example.com/node/123/delete?destination=admin/manage-events

Thanks

You need hook form alter: https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_form_alter/7

You first have to inspect element of the form and get the Form ID. Then use the following to unset the submit button. You will have to print_r() or use devel to output the $form array to find the submit button to unset.

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

if ($form_id == 'myformid') {
  unset($form[submit button])
}

}


Image Insert and Theming When you have have an image field on a content type, and use the Insert button to place it into the body, do you get a chance to theme it in Drupal 7?  theme_image doesn't seem to get called, and I am not seeing anything the the API refernce.  I know this is JS functionality on the edit page, but there could be ways to still theme it.  Thanks.

Edit for clarification:

When you use Insert to get images into the body, just the image gets inserted and the theme system gets bypassed.  If you use the image as a field, then all modules get a chance to theme it.  This results in inconsistent image usage on a site.

For example, if I use an image as a field, the RDF module will tack on some metadata and my custom theme_image will do its thing.  When I use Insert with the same image, just the plain image gets put in.

On previous projects, I have added some javascript to the theme to fix these discrepancies, but the code needs to be adjusted each time something changes with how images get themed.  Ideally, I am searching for a method to allow images-as-fields and image-inserted-into-body to be themed the same way, without resorting to Javascript or manually editing the images in the body.  If this isn't built-in functionality, I may try to patch the Insert module to allow it.

I will assume you are referring to using the Insert module.

Once you have inserted an item into a node field (most likely the body), it then becomes a simple string of text within that field and is processed as such. There is no longer anything linking it to the image field that you used to upload it, and no way to hook onto it and perform any programatic changes. The only "theming" that can be done to the image at this point is CSS changes.

You could potentially add optional styles for the images via your WYSIWYG's configuration or you could use the Image Resize Filter module to allow the node editor to change the size of the image and/or create a link to the full-size image.

If you could give some details about what exactly you are wanting to do to that images that have been added via the Insert module, there might be another solution someone can suggest.


Can the themeing and render api be accessed independently? Are there de-coupled versions of the form rendering and theming APIs that can be used outside of the Drupal framework?

Not in Drupal 7 or earlier. There might be chances for Drupal 8. But in the currently available major versions of Drupal the mentioned components are still strongly integrated in the core system.


get node id of field collection I have the following code. I am able to load the field collection item using entity_load_single. I want to be able to get the node id for a given field collection item. How can I achieve this?

function dc_car_guide_model($model_id)
{
    $model = entity_load_single('field_collection_item', $model_id);
    //How can I get nid?
}

$model = entity_load_single('field_collection_item', $model_id);
$node = $model->hostEntity();
echo $node->nid;


How to get a flag counter for anonymous users? I'd like to have a counter for flagged nodes for anonymous users. I'd like to use a view. In this view I need a relationship to the anonymous user (session).

How can I get it?

Or is there another solution to get a flag counter for anonymous users?

The Session API module is required (a prereq) to make the Flag module functionality available for anonymous users (even with page caching enabled),

Consider checking out the great article about Enhancing the Anonymous User Experience: Adventures with Flags to get this to work.


Can "No front page content has been created yet. Add new content" be removed totally? I noticed that if there is content placed in the main content block, "No front page content has been created yet. Add new content" will appear on front page or perhaps any page. Most templates will be done in blocks, except node pages.

Can it be totally removed? If yes, how?

Add this to your theme's template.php file

function THEME_preprocess_page(&$variables) {
  if ($variables['is_front']) {
    unset($variables['page']['content']['system_main']);
  }
}


How to programmatically alter feed item values before saving Feeds Tamper does this job, which allows me to "tamper" with feed items' values before saving it to an entity.

My question is how can I do that programmatically in Drupal 8 with a custom module.

Thanks to No Sssweat, I managed to use an EventSubscriber using afterParse event to do this job.

File 1: mycustommodule/mycustommodule.services.yml

services:
 mycustommodule.feeds_subscriber:
   class: Drupal\mycustommodule\EventSubscriber\FeedsSubscriber
   tags:
     - {name: event_subscriber}

File 2: mycustommodule/src/EventSubscriber/FeedsSubscriber.php

<?php

namespace Drupal\mycustommodule\EventSubscriber;

use Drupal\feeds\Event\FeedsEvents;
use Drupal\feeds\Event\ParseEvent;
use Drupal\feeds\Feeds\Item\ItemInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Subscriber to Feeds events.
 *
 * This happens after parsing and before going
 * into processing.
 */
class FeedsSubscriber implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[FeedsEvents::PARSE][] = ['afterParse', FeedsEvents::AFTER];
    return $events;
  }

  /**
   * Acts on parser result.
   */
  public function afterParse(ParseEvent $event) {

    /** @var \Drupal\feeds\FeedInterface $feed */
    $feed = $event->getFeed();
    $feed_bundle_name = $feed->bundle();

    // Only alter a particular feed
    if ($feed_bundle_name == "MY_FEED_IMPORTER_MACHINE_NAME") {

      /** @var \Drupal\feeds\Result\ParserResultInterface $result */
      $result = $event->getParserResult();

      for ($i = 0; $i < $result->count(); $i++) {
        if (!$result->offsetExists($i)) {
          break;
        }

        /** @var \Drupal\feeds\Feeds\Item\ItemInterface $item */
        $item = $result->offsetGet($i);

        /**
         *
         * My custom code here using $item->get() and $item->set()
         * to alter whatever values I want.
         *
         */
      }
    }
  }
}


users forced to reset password I'm on 7.39 and I get a lot of reports from users that re forced to reset their password every time they visit the site.

I'm honestly clueless about how to debug and haven't been able to find similar support requests on the forums.

Any ideas are extremely welcome

update
Here's feedback from a user that couldn't even reset:

*If I use this link: http://www.tambourhinoceros.net/user/user-id/orders/order-id:

  You are not authorized to access this page.

If I try to login ... with this e-mail adress and my password ... nothing happens.
If I request a new passwort this message
appears

  There was a problem with your form submission. Please wait 6 seconds
  and try again. You must be a human, not a spam bot, to submit forms on
  this website. If you insist that you are a human, please try again. If
  error persists, contact webmaster using contact link at the bottom of
  this page and give all the details of this error (your browser,
  version, OS). Form is submitted too fast. Please spend more time
  filling in the form.

*

You could use the Password Policy module to manage your password policies.


How to translate a header in drupal 7 I have a drupal 7 site I inherited to manage.  There is a view I can edit at /newsletters#overlay=admin/structure/views/view/newsletters/edit and it has a section titled "header" that I can't figure out how to enable for translations.  The section below it,"content", is showing up properly translated on the front end.

The menu for Header looks like this:

Clicking Edit Global: Text area reveals this:

What do I have to do to translate this and display it properly?

The "global" header and "global" footer built in Drupal Views isn't treated as a separate translatable entity like a node is.

One recommended approach (that will also avoid giving content managers access to edit views) is to setup a single custom content type for view headers and footers and then with the Entity API module enabled, set/embed an entity reference to the specific node in the view header (and/or footer). A breakdown of steps for this approach is below:

Make sure your site has the Entity API module installed and enabled.
Create a custom content type (it can be just a body field and title.  NOTE:  the title will render in the embedded entity in the view, so you may want to utilize it for the view page title/H1 in lieu of the specific "title" field on the specific display of the view. Otherwise you can preprocess the node type to exclude the title or use css to hide it.
Enable internationalization/translations for the new content type.
Create a node for each specific view header or view footer where you need manageable/translatable content, noting the node ID upon save.
Export a backup of the views impacted.
Edit the desired views; be sure to be editing the specific "view display" that applies to your block or page.  In the "Header" or "Footer" section of the view edit/config page (where you currently have a global textarea), click "ADD".
In the modal, make sure the selector in the top left corner is set to apply changes to "This Page"/"This Block"/etc and not "All Displays".  Select Entity: Rendered Entity and click Apply (this display).
Input the node ID and choose the desired display mode (full node should suffice as outlined, unless you need a custom display mode setup on the node/content type).
Remove the Global Text object in the View Header or View Footer.  After applying this change (and assuming you have no other custom objects in the view header or footer), you should only see the referenced entity in the View Header or View Footer section.
Save and test the page where the view appears.
If you decide to revert, import the backed up copy of the view as Admin1 to restore it.


How do I display all available field types? I want generate an new form in a custom module via the generate:form command.

In this step, I must enter a field type.

How can I get all available field types?

With the term "field type" you probably don't find what you are looking for. Better search for "form and render elements". You can find a list of all available elements here:

https://api.drupal.org/api/drupal/elements/8.2.x

You can use all elements of the type "FormElement".


Node view mode in page template suggestions I would like page template suggestions when a node is using a custom view mode.

I think this would happen in hook_theme_suggestions_page_alter().

I have already been able to get page-level template suggestions based on the node's content type, so it seems like I should be able to snag the name of the custom view mode?

I'm not good at this part of Drupal at all, so any help would be appreciated.

The hook hook_theme_suggestions_HOOK is the one you should implement.

When you have a node of type page (labeled as Basic Page from the default profile), then the HOOK is node and the specific hook you would implement is hook_theme_suggestions_node(array $variables)

As @pinueve points out, there is already a specific suggestion that includes the custom display mode: node--page--CUSTOM_VIEW_MODE.html.twig.

Also, as @pinueve suggests, the easy way to find the template suggestions is by enabling the debugging mode. I tested this using a custom view mode called customvm that I created, so I can see these suggestions in the browser by inspecting the source code:

* node--17--customvm.html.twig
* node--17.html.twig
* node--page--customvm.html.twig
* node--page.html.twig
* node--customvm.html.twig
x node.html.twig

Alter hook

Note that there is also an alter version of the hook [HOOK_theme_suggestions_node(array &$suggestions, array $variables)][3], you should use this if you are trying to alter the existing suggestions, maybe changing the priorities.

Suggestions for a page from a custom controller

The page HOOK is meant to be used when the output comes from a custom controller and route, like the one in this example:
https://www.drupal.org/docs/8/api/routing-system/introductory-drupal-8-routes-and-controllers-example

In this case the HOOK is page and you would implement these hooks:

HOOK_theme_suggestions_page(array $variables)
HOOK_theme_suggestions_page_alter(array &$suggestions, array
$variables)


hook_menu not rendering page or form I'm using 6, and I CANNOT get hook_menu to take me to the page where the form is. I go to www.myurl.com/test_form (and for good measure, www.myurl.com/?q=test_form) to check.

If I clear the caches, then I get a WSOD. If I don't, I get a 404. I have changed permissions and cleared caches and tried to figure out what Drupal wants with no luck. What did I do wrong?

function module__menu() {
      $items = array();
      $items['test_form'] = array(
            'title' => 'New Form',
            'page callback' => 'drupal_get_form',
            'page arguments' => array('module_form'),
            'description' => 'Form',
            'access callback' => TRUE,
            'type' => MENU_CALLBACK,
      );
      return $items;
}

function module_form($form_state) {
$form = array();

    //my form stuff.....

    return $form;
}

UPDATE: Thanks for the advice. Did what you guys said. Still no luck. Error log doesn't show any errors either, so I'm totally lost here.

You've got two underscores in your menu function declaration, try changing it to:

function module_menu() {

Other than that your code is fine, although on the off chance you're using this module to create a custom content type I'd recommend changing the name of your callback function so you don't get a collision with hook_form().


Redirect SimpleTest queries to a different database How can I tell SimpleTest to use a different database than the default connection? I want to be able to run the tests against an in memory database while keeping the local data on disk.

UPDATE:

So far the answers I'm getting are on how to set up tmpfs and move mysql data to that folder. That's great and super helpful. However this is missing the specific answer that I am looking for. I'm most interested in how to run SimpleTest against a different connection than the default database connection. You can see above that my question reflected by both the title and the first line of my original submission. I apologize for the confusion caused by my mention of an in memory database, I provided that only as context, but it is not the root of my question.

It's not possible to do this on a storage engine level. You can't install Drupal on top of the HEAP storage engine, there are various missing features, the most obvious one being: "MEMORY tables cannot contain BLOB or TEXT columns." (copied from the link in the comments).

The qa.drupal.org testbot's have the complete MySQL data directory in a tempfs that is stored in memory, which is copied from the real file system during startup and back during shutdown. I don't think that's a doable setup for a development environment because, at least in my case, databases of real sites quickly get too big for something like this (Working on large sites with multiple GB of data). http://drupal.org/node/466972 has some more tipps and scripts for the tempfs thing. Make sure to read the comments.

Not sure what exactly takes 2,5m in your case, I can run a single test in ~10s (Note that every test method is a separate test that runs in a new installation).

I'm quite sure that I've already written quite a list of tipps on how to speed up tests in an answer somewhere but I'm unable to find it. The most important thing is defining $profile = 'testing'; in your test class, that will only install the absolutely required modules for Drupal to run. Speeds up test runs by ~50%. Another way is prefixing your different test methods with anything other than test and having a single public test method that calls all other. Downside is that your tests then run in the same environment and might affect each other. You e.g. can't have hardcoded node id's and things like that.

Another thing is optimizing your mysql configuration, than can speed up tests quite a bit as well, see http://techblog.md-systems.ch/blog/improve-mysql-performance for a start.

To actually override the used database connection, you need to completely overwrite the setUp() method where the connection is created and activated and instead use whatever connection you want, see DrupalWebTestCase::setUp().


Field formatter module throws cannot declare class error I am trying to write a custom module, which defines a field formatter plugin, but when I visit the Manage display page, I get this error:

  Fatal error: Cannot declare class Drupal\my_formatter\Plugin\Field\FieldFormatter\MyFormatter, because the name is already in use in /var/www/sites/drupalroot/web/modules/custom/my_formatter/src/Plugin/Field/FieldFormatter/MyFormatter.php on line 0

I've compared my module to several other working field formatter plugins and can't seem to figure out what I'm missing.

My module directory is laid out like this:

web/modules/custom/my_formatter/
├── my_formatter.info.yml
├── my_formatter.module
├── src
│   └── Plugin
│       └── Field
│           └── FieldFormatter
│               └── MyFormatter.php
└── templates
    └── my-formatter.html.twig

My info file:

name: My Formatter
type: module
description: 'Do some fun stuff.'
package: Field types
core: 8.x
dependencies:
  - field
  - file

And my MyFormatter.php file:

<?php
/**
 * @file
 * Contains \Drupal\my_formatter\Plugin\Field\FieldFormatter\MyFormatter.
 */

namespace Drupal\my_formatter\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\file\Plugin\Field\FieldFormatter\FileFormatterBase;

/**
 * Plugin implementation of the 'my' formatter.
 *
 * @FieldFormatter(
 *   id = "my",
 *   label = @Translation("My Formatter"),
 *   field_types = {
 *     "file"
 *   }
 * )
 */
class MyFormatter extends FileFormatterBase {

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = [];
    foreach ($items as $delta => $item) {
      $elements[$delta] = [
        '#theme' => 'my_formatter',
        '#my_var' => 'Hello',
      ];
    }
    return $elements;
  }

}

Any help would be greatly appreciated.

Here are some pointers that might help:

Run drush cr to clear cache and see if the error persists.
Enable error backtraces from the Config > Development > Logging & Errors page to see if you get more info in the error message about where the class is being redeclared.
Search your project for the name MyFormatter and see if you find anything besides the MyFormatter.php file you've mentioned.
File, directory and class names are case-sensitive – in what you've shared, they seem to be correctly named.
Make sure you're not manually using require or include anywhere to include this file.

Probably, not applicable in your case.


l() Link function adding Icon before Link Text Is there a way to pass in an icon inside the  tag of the link built by using the link (l()) function?

<icon> Link Text

I use it like so currently:

l('text','path',options)

Options all seem to be attributes of the  tag itself besides the "text". Using html =>true, I can add  before the link text:

print l(' ' . $link["link_title"]

However, I cannot check if the span isset inline there, unless I am missing something...

This works (below), but all my  have  linktext... even if span is empty, and I don't want that blank tag in there:

<?php print l(' ' . $link["link_title"],$link["link_path"],array('attributes'=> array('class'=>array($link[options][item_attributes]["class"], 'nav-link')),'html' => TRUE)); ?>

How can I add an icon, without CSS, before my link text as well as check if that span is empty?

you can use something like this:

l(t('Back'), 'node/' . implode(" ",$link[options][attributes]["class"]) . '/edit/', array('attributes' => array('class' => array('btn btn-default btn-back'))))


Cannot find /libraries for installing ckeditor module I'm trying to install the CKEditor Codesnippet module. I've downloaded the source but I don't know how to install it.

In the module page istructions are:

  Download the plugin from http://ckeditor.com/addon/codesnippet at least version 4.5.11.

  Place the plugin in the root libraries folder (/libraries).

  Enable CodeSnippet in the Drupal admin.

  Configure your WYSIWYG toolbar to include the button.

I cannot find the /libraries folder. Should I create it in the root folder of Drupal installation or somewhere else?

You can (need to) create it in the web root.


How can I fix a migration input format mess? I did a migration from Drupal 6 to Drupal 8 and now I have two Full HTML, two Plain text, and all other individual for both versions of Drupal default text formats. Of course when I try to modify the duplicates I have warning that it is not possible to have the same human readable names so I have Full HTML and Full HTML2 now. I want to get rid the one of them. It looks like that all the migrated by me content is with a text format with a machine name 2 while the other Full HTML text format with no any content in the website is with the machine name full_html. Also the default Plain Text, the one that it is not possible to be removed is with a machine name 3.

As far as understand by the research I did, even if I disable the full_html text format, I cannot use its machine name for the other one. I don't mind what the name is, but can I safely change somehow the text format machine name 2 to something more meaningful?

Is it necessary to do so, or it will be fine if I leave it this way and just remove the full_html one as far as I do not need it?

One option is in the migration template, to add the input format value.

I found the default_value plugin worked well there e.g, to set default full_html:

field_subheading:
  plugin: sub_process
  source: field_subheading
  process:
    value: value
    format:
      plugin: default_value
      default_value: full_html

Another option, could be to run an SQL query to update the field data and revision data tables

update node__field_subheading set field_subheading_format = 'full_html' where field_subheading_format = 'other_format';
update node_revision__field_subheading set field_subheading_format = 'full_html' where field_subheading_format = 'other_format';

then clear cache.

However fixing as part of the migration template mapping is recommended.


Update a record in custom module I've read several custom module tutorials but none seem to show how to edit a record. My module does not use node but has a custom table. So, I think I ought to be able to drupal_get_form and populate the #value with the fields. But to set up the menu to get the parameter in the URL and my page callback is not working.

Looking around I found this answer and modeled the below after it but I get a default page instead of my expected form.

$items['redashboard/project/%/edit'] = array(
  'title' => (t('Edit project')),
  'page callback' => 'drupal_get_form',
  'page arguments' => array('re_dashboard_edit_project_form', 2),
  'access callback' => TRUE,
);

function re_dashboard_edit_project_form($form, $form_state, $projectid) {
  $project = pull_project($projectid);
  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Research Project Name/Question'),
    '#value' => $project->projectName,
    '#required' => TRUE,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Create',
  );
  return $form;
}

function pull_project($projectid) {
  $query = db_select('Projects', 'p');
  $query->fields('p', array('ProjectID', 'residentID', 'projectName', 'projectMentor', 'projectStatus', 'citation', 'lastUpdated'));
  $query->condition('ProjectID', $projectid);
  $result = $query->execute();
  return $result->fetch();
}

So, how should I set up a page to edit this record if not this way? Or to the point how should I set up the menu so that this callback gets rendered? thx, sam

The $items['redashboard/project/%/edit'] declaration needs to be made inside of re_dashboard_menu(), and there needs to be a re_dashboard_edit_project_form_submit() function to pipe $form_state['values'] into db_update().

Other than that, it looks like it will get the job done.  You could use db_query() instead of db_select(), since it's faster, and the query conditions are static.  Also, make sure you have a way to handle db_select() not returning any results, since fetch() will return FALSE in that case.


Alter the username label in the login block I want to alter the username label. Instead of username, I want to change it to User ID.
I've written the following code to perform this function, but I'm not sure how to implement it.  When I implement it in the page that contains the login block, nothing happens.
function lae_form_user_login_form_alter(&$form, &$form_state, $form_id) {
 $form['user-login-form']['edit-name']['#title'] = t('User ID');
}

Will this actually work? If it will, how do you implement it?

Your code needs to go inside a custom module. Assuming your module is called lae then you just need to make one or two small changes to your code:

function lae_form_user_login_form_alter(&$form, &$form_state, $form_id) {
  $form['name']['#title'] = t('User ID');
}

The edit- prefix that you get from the element's ID in HTML is actually provided by Drupal automatically, it's not the name of the key in the form array that identifies the element. Also the elements (at least for this particular form) will normally be at the root of the array so you don't want to reference $form['user-login-form']['edit-name'] (as it most likely doesn't exist).

I would advise downloading and installing the Devel module and using the dpm() function to print a nice representation of your form array to the screen, so that you can inspect it and see the correct array keys you'll need to target to effect a certain element.

// Add this to your form alter function:
dpm($form);


Is it still a partial port or does it take a different approach? At the moment of this question, I am using:

Drupal 8.1.3
Panels 8.x-3.0-beta4
Page Manager 8.x-1.0-alpha23
Layout plugin 8.x-1.0-alpha22

I am having difficulties replicating what was easy with Drupal 7, and I am not sure if the reason is simply that the ports of Panels and Page Manager are still incomplete, or that the approach has changed and I am not getting it.

In Drupal 7, you could create panels, and insert content into panes:

You could really add anything into a pane.

In Drupal 8, it looks like I can only add blocks:

What I want to achieve is being able to override a basic page (I'm overriding /node/{node}), and for example have a simple 1-column layout to display:

          <node title>

           <block 1>

          <node body>

           <block 2>

It could be more complex than that of course.

So, back to my question: is it just a matter of waiting for a complete port of Panels, or am I missing something?

It looks like you've forgotten to install one of the modules that implement panels.
From: drupal.org/project/panels

Panels in Drupal 8
We’re actively working on Panels for Drupal 8 which works with the new layout_plugin module and mainly is an interface to configure and store these layouts.
Panels is an API in Drupal 8
In order to use panels, you must use an implementing module. Currently, Page Manager and Panelizer implement panels.
If you’re interested in following the Drupal 8 port in detail, follow #2169319: [meta] Drupal 8 port of Panels in the issue queue OR join us on IRC every Tuesday at 12 noon CDT (UCT-0500) in the #drupal-scotch channel for our weekly meetings.


Allow a role to edit a specific taxonomy list of terms We have a blog that needs to be categorized by topics. I want to allow a blog administrator to add/edit/delete blog topics that are listed in a taxonomy vocabulary. But I don't want to give him add/edit/delete access to other taxonomy lists. Is there a permission that I am missing? Is there a D7 module that handles this? Or can someone point me in the right direction for writing my old module?

Taxonomy Access Control provides this functionality.  Workbench does as well, though it is slightly more complex and from my limited experience performs better when only a single term is used per node to control access.  Workbench (access + moderation) includes a nice set of tools for content moderation and workflow not found in Taxonomy Access Control. Both are worth a look before you decide for your use case.


Changing the HTML produced by Panels: Is it possible? I like to use panels, however panels is a pain in the butt to style because of the massive amount of div's it generates. Also the classes it applies to those divs make no sense and are way too bulky as well. Causing confusion among my fellow front-enders.

To show you the output they generate:

The problem is that i'm using 960.gs and panels adds their own classes and bulky div structure, making me have to override their classes. This is something i don't want to do, i want to clean up the divs. Is there any way to do this?

Edit:

What i did to clean up some div's that i considered useless:

Starting from line #388 in flexible.inc (panels/plugins/layouts/flexible)

$output = '';
//$output = "
base['canvas'] . " clearfix\" $renderer->id_str>\n";
    //  $output .= "
base['canvas'] . "-inside\">\n";

      $output .= panels_flexible_render_items($renderer, $settings['items']['canvas']['children'], $renderer->base['canvas']);

      // Wrap the whole thing up nice and snug
      //$output .= "
\n
\n";

I actually made a copy of the flexible layout and edited that one, but if i had more time on this project, i would create a cleaner plugin for this.

Note: This isn't the best solution, this was the fastest possible route to accomplish my goal. Creating you're own small plugin is the best way to go, you can always use one of the existing plugins as a base.

I've looked into this issue before. Here's the issue you want to read. It seems nuts at first, but there are actually good reasons for it being like this.

Bottom line: think of Panels Flexible Layouts as a prototyping tool. Use it to try out and draft ideas in development, staging, user-testing etc, then when you've got the perfect layout signed off, implement it for production with clean, crisp, hand-optimised HTML as a custom Panels layout (more on those below).

Here's a quick summary of why it is the way it is, based on that issue I linked to:

Panels' HTML output needs all that crazy markup to be able to accommodate the craziest flexible layouts anyone could want to create - think loads of nested fluid and fixed regions side by side.
Nothing automatically generated will be good enough for HTML purists, so the Panels guys haven't tried to keep them happy within the flexible layouts feature. So there's no HTML optimiser algorithm that tries to pare down the HTML generated by your layout to the bare minimum, because no matter how good it was, it still wouldn't be best-standards HTML.
Something they don't mention: if there was such an optimiser, certain changes to the layout would cause now-redundant divs and classes to disappear. If you hung CSS off these, you'd need to re-write your CSS most times you make a small change to a Panels flexible layout. This means that if they tried (and failed) to make Panels Flexible Layouts into a best-standards production tool, they would also have weakened it as a prototyping tool.
You can get clean, lean Panels HTML output. The expected workflow, reading between the lines, is I believe something like this:

You use Panels Flexible Layouts during early development, while trying out ideas.
Once you have settled on a particular layout, if you want clean HTML, you implement it using a custom layout, using only the precise amount of HTML markup that layout needs with just the right classes, semantics etc for your site (how-to below).

While I didn't like it at first, on reflection I think it makes sense. Rather than trying to do the impossible and create one tool that is perfect for both prototyping and for best-standards in a production context - which both have very different needs and could only result in a comprimise that wasn't quite right for either - they've gone with one tool that is ideal for prototyping and another seperate tool (custom layouts) that is ideal for lean production.

This means you can get the best of both, at the cost of a little bit more work implimenting your final layout as a template based on best-standards HTML - but a HTML purist will want to do that little bit of extra work anyway to get their output perfect.

How to create custom panels layouts? There's a detailed guide in the documentation on how to do so. Here's a quick basic summary:

Copy an existing layout from /sites/all/modules/panels/plugins/layouts to become /sites/all/themes/[your_theme_name]/layouts/[new_unique_layout_machine_name]
Rename the files in the new copy to match their new folder name. Note that the .tpl.php file should have hyphens instead of underscores.
Add a line to the theme info file: plugins[panels][layouts] = layouts This tells Panels that you have custom layouts in this theme, and where they are (replace the string layouts if it's not the path from your theme to your custom layouts folder)
Edit the files with your perfect, sleek, minimal, semantic best-standards HTML and CSS.

Don't forget to also update the .inc file with info about your layout like name, categories, filenames, etc.
theme in the .inc file should match the .tpl.php file's filename, without the extension. Any underscores you enter here in the theme value will be converted to hyphens.
Also consider editing the .png icon to better reflect your actual layout.

Clear the cache. Your new layout appears as an option in Panels with the name, category, etc you specified in the .inc file. Use it.


Is it possible to use a different theme for just a section on the page? In Drupal 7, using a different theme on each page is easy, but what I could really use in this particular case is 2 themes on the same page.

Let's say I want to use Rubik theme for all page sections (menu, etc.) except 'content' section, where I'd like to use Stark theme.

Is this possible at all? If it is, how?

Thanks Clive and Cromian for your input. Guess its not possible to actually use 2 different themes on the same page.

The simplest solution I found is to use one theme, then add 2nd ones css using drupal_add_css function. Then hope 2 CSS don't interfere too much and it's good enough without HTML part of the theme.


How do I create a custom theme, or layout using images? I would like to create a custom theme, for which I have the images for parts of the theme, such as header, footer, menu, logo. I don't understand how to start to create a layout. I have gone through "Themeing guide," but I don't know where to start.

You should download a theme such as AdaptiveTheme  or Zen as a base and then create a sub-theme.


Overriding contributed module functionality Every so often, I need to make a little hack to a contributed module to add a bit of needed functionality, usually something specific to the project that the module maintainers probably would not want to use.

Currently, I create a patch file for every hack, and I store all such patch files in sites/all/modules. This way, whenever I update a module, I can easily reapply my hacks and address any conflicts.

I can't help but feel like I'm doing something wrong though. Am I?

A patch doesn't necessarily apply to a new version of a module: It is enough the patched function is moved to a different line, or the code for that function is changed, and the patch doesn't apply anymore. For the function to be moved to a different line, it is enough another function is re-written to take more lines (or less lines).

A better way to alter the behavior of a module is, for Drupal 7:

If the module uses code for a page callback that you want to change, change the page callback with hook_menu_alter().
If the module implements a theme function you want to alter, change the function associated with hook_theme_registry_alter(). In alternative, if it is sufficient to change the variables the theme function gets, then you can implement the preprocess function for that theme function (e.g. hook_preprocess_rdf_metadata() for theme_rdf_metadata(), and change the variables that theme function will get.
If the module executes an SQL query using db_select(), and assigns a tag to the query, change the executed query with hook_query_alter().
If the module implements a hook you don't want it is executed, you can implement hook_module_implements_alter() to avoid it is executed.
If the module implements an alter hook (e.g. hook_page_alter()), and you want to change what that hook altered, implement the same alter hook, being sure it is executed after the one implemented from that module.

In the case the function you want to alter is not a hook, then:

Check that function is using hooks implemented from other module. For example, node_save() invokes hook_node_presave(); if I would want to change the "changed" property of the node, I don't hack node_save(), but I rather implement hook_node_presave() to alter it.
Check that function is referenced/used from a hook; in that case, you can do something for that hook, as I previously described.

If anything I said until now doesn't apply, then it is better to create a custom module, and use the code of the other module to create it. I would also try asking a feature request for the existing module, hoping the feature is implemented.
Hacking a third-party module is never a good idea, especially because automatic updates of the module (via the Update Manager, or Drush) would not anymore possible for that module.


Altering main menu in drupal 7 I am new to drupal, and i am trying to alter the code generated by my main menu. I would like to replace this :

Link1

link2

By this :

Link1
link2

The code i have added on my page.tpl.php

print theme('links__system_main_menu', array('links' => $main_menu, 'attributes' => array('id' => 'main-menu', 'class' => array('links', 'inline', 'clearfix'))));

I have been looking around and found that it could be achieved by using theme_menu_link & theme_item_list in my templatye file....no success so far.

Can anyone show me the proper way to do it ?
Thanks

It's a bit unusual request, but if you want to clear main menu from ul anl li tags and print just links, you can do that in this way:

template.php

/**
 * Main menu
 * Implements theme__menu_tree().
 */
function YOURTHEME_menu_tree__main_menu($variables) {
  return $variables['tree'];
}

/**
 * Main menu
 * Implements theme__menu_link().
 */
function YOURTHEME_menu_link__main_menu(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $element['#localized_options']['html'] = TRUE;
  $output = l('' . $element['#title'] . '', $element['#href'], $element['#localized_options']);
  return $output . $sub_menu . "\n";
}

go to admin/structure/block and place main menu in header region (or wherever you want)

Result

Link1
link2


How do I fix these installation errors? I'm installing D7 on Ubuntu 12.04. I've been following the procedure explained in this page. And this is the error I'm getting:

I've already made MySQL database called 'drupaldb'.
I've also checked PHP and it's installed and it's running. I'm configuring NGINX to run D7 on it.
Please help!

To install gd library in ubuntu:

  $ sudo apt-get install php5-gd

Above command will install PHP gd library in Ubuntu.

Refer this question from Server Fault to install mysql-pdo driver in ubuntu


Webform to content type In the Webform module version 8.x-5.0-rc27 there isn't the tab to add a webform to a certain content type.

Is this intentional? If not, is there a workaround for this issue?

The Webform (node) References tab should still be working as expected in rc27.


Notify user checkbox I'm looking for a bit of code, or module that would insert the following behavior into my user registration flow that exists as a php file.  Use case as follows:

User registers for a free trial
User checks a box that says "Send an email reminder to [WILL AUTOMATICALLY INSERT USER EMAIL].com 3 days before I am charged.

User checks box. The back-end functionality might need to be manual for now. All I want to do is add the box, text, and have it pull the email address token automatically.

You can add as many field you like to the user object using Fields. Just tell your field to be visible on the main user panel.

Once this is working, implement hook_cron and send your mails using drupal_mail().


How to add a custom language? In Drupal 7 there is a section to add a custom language

But in Drupal 8 that section does not exist,

How can I add my custom language in Drupal 8?

There is,just open Language name select list and  choose  last item Custom language ... .


How do I add HTML to my module's custom admin page? I have set up a new page in my admin for my module like so:

/**
 * Implements hook_menu().
 */
function scraper_menu() {
    $items = array();

    $items['admin/scraper'] = array(
        'title' => 'Scraper',
        'description' => 'The main action page in the admin area where we control our scrapers.',
        'page callback' => 'scraper_page',
        'access arguments' => array('administer users'),
        'type' => MENU_NORMAL_ITEM,
    );
    return $items;
}

/**
* Page callback: Scraper page
*
* @see scraper_menu()
*/
function scraper_page() {
    return '
Hello world
';
}

When I navigate to admin/scraper I get the following error:

Fatal error: Unsupported operand types in /######/includes/form.inc on line 1079

So how do I create a custom HTML page in the admin?

What you have tried is the right way to do. I have checked the same code snippet and its working for me in my D7 installation. Hopefully the issue will be with some other form element (probably custom block ) that has be assigned in this page, might have some syntax error.

Thanks


A Rule component to change author on nodes? I am looking to create a rule's component to allow users to bulk modify the author value on nodes using VBO. Any insight on how I what this component part in rules would look like? The action must allow the user to define whatever author they wish either using a textfield or a list of available accounts on the site in VBO.

Create a view listing the content that you want to edit.
Add a bulk operation in fields

Select change the author of the content

Go to your view to select the nodes for which you want to change the author

Select the author who should be made the new other for all these content.


How do I include custom CSS files in the styles dropdown? I am trying to include custom css file to ckeditor.

It doesn't show css file in styles drop-down list.

I have included this two lines of code into;

 /drupal/sites/all/modules/ckeditor/ckeditor.config.js

 config.extraPlugins = 'stylesheetparser';
 config.contentsCss = 'test.css';

Thanks a lot for the help.

Have tried going adding the css file via the configuration page?

yoursite.com/admin/config/content/ckeditor/edit/

navigate to the page, edit the target profile and click on the CSS link to expand the configuration pane... you should be able to tell CKeditor what to do from there. I'm not sure if its necessary but you may need to refresh the site's cache before the new files get picked up.
hope this helps.


how to change the weight of a moderation state transition outside the database how can I change the weight of a Moderation state transition in code?  is it possible?  This is for Drupal 8

Change the weight in the admin panel, then export the yaml files with drush config-export


Prevent the email registration module from appending the user ID as a suffix on new user's username I'm a newbie in Drupal and I have an issue with the User module (I think).

In my user registration form there is no username field but there is email field provided by the Email Registration module. When users register, Drupal generates a username from given email using its first part before @ and appends user ID to it. For example: if I will try to register with email user@mysite.com, Drupal will generate username for my account user_123 where 123 - is user ID.

How can I change this default behavior and prevent Drupal from adding _123 to generated username? Is there is any solution to get rid of the username, and use the email?

While looking at the project page of Email Registration, it reads:

  A username is generated and assigned based on the user name part of
  the email address and their user ID. Sites that want to create
  usernames in their own way can do so by implementing
  hook_email_registration_name.

And when looking at hook_email_registration_name(), we see how we can alter the username by returning a value.

So, what you need to do is:

Create a custom module (there is plenty of documentation for that on this site and the rest of the internet).
Implement hook_email_registration_name() (place this function in your module file and replace hook with your module name).
Have the hook return a new username.

So you need to put something like this in your module file:

function mymodule_email_registration_name($edit, $account) {
  $mail = $edit['mail'];
  $mail_parts = explode('@', $mail);
  $username = $mail_parts[0];
  return email_registration_cleanup_username($username);
}

This will return the first part of the email as the username. So john@gmail.com becomes john. bob@yahoo.com becomes bob. john@hotmail.com becomes also john... But that was already in use and Drupal does not allow duplicate usernames, so you have a problem. (And you discovered the reason this module by default appends a unique token to the username.)

You could solve this by implementing a small iterator. Appending 1, 2, 3 to every subsequent John but it would result in just as ugly usernames (and for the 100th john you had to do 99 database lookups making this slow).

So I'd like to propose to you Real Name. This nifty module will override the username display everywhere with the value of one or more other profile field. So you add a namefield to the registration, configure Real Name to use that field and the user will never know his username is john_123 because he will never see it.

I don't know your specific requirements and this might not be suitable for you, or if you can think of another way to enforce uniqueness, you can always use the hook and implement your own method. See what fits you :).


Any way to add CSS for common path? I have a Drupal 7 with several basic pages with repeated paths, for example:

1) /red-car/ford-and-chevy
2) /red-car/nissan-sport
3) /red-car /renault-mazda
4) /blue-house/mexico
5) /blue-house/colombia
6) /blue-house/el-salvador

How can I add a file red-car.css for "/red-car/" and blue-house.css for
  "/blue-house/" from template.php?

You might want to do something like this in your template.php file.

function MYTHEME_preprocess_node($vars) {
  switch (arg(0)) {
    case 'red-car':
      drupal_add_css(drupal_get_path('theme', 'MYTHEME') . "/css/red-car.css");
      break;
    case 'blue-house':
      drupal_add_css(drupal_get_path('theme', 'MYTHEME') . "/css/blue-house.css");
      break;
  }
}


User Points Rules: Remove points (based on content type) I currently am using the User Points Rules module to grant points (both moderated and unmoderated) to users for signing up for content using the Signup module. However, for cases where the user cancels the signup, it doesn't seem possible to remove (through another transaction) the points.

The points aren't static (i.e. 1 point per signup and thus -1 point per cancellation), but are dependent on the integer value entered for the Events content type.

Suggestions?

Issue on d.o: https://www.drupal.org/node/2419721

Your question seems to be a variation (not a duplicate) of the question "How to grant user User Points equal to certain field's value / calculated value?".

Similar to the accepted answer to that question, use the Rules module and try to create a rule with these Rules Actions:

Calculate a variable that corresponds to "the integer value entered for the Events content type" (similar to what you wrote in your question).
Convert the data type of that variable (to integer).
Grant points to user (using the calculated + converted variable.

With that, the only thing left to do is to find an appropriate Rules Event to get this rule triggered.

PS: such "convert data type" is simply a matter of how Rules works (by design), so it's not to be considered as a bug either.


How to disable payment cart pane when discount brings total to $0 I am using the uc_discounts_alt module on a Drupal 6 / Ubercart 2 site to provide specific dollar amount discounts for specific products. The discounts bring the product price down to zero, and conditional actions check for that discount code and, if found, make the shipping cost $0 as well.

I enabled the Ubercart Free Payments Module to allow these free orders to check out, but the cart states that the credit card info is missing when I to proceed to the order confirmation page. Apparently the Free Payments Module is not working as expected.

Is there any way I can hide or otherwise disable the payment panel when a certain discount is being applied... or any other options that may give me the functionality I need? Unfortunately, I am in a bit of a time crunch as we have a big promotion starting tomorrow, and this issue was masked by another payment method.

Thanks!

I was able to fix the problem by modifying the "Free Order" payment method's Conditional Action. Free Order is the payment method associated with the Ubercart Free Payments Module and comes pre-loaded with a CA that checks the cart total to see if it is more than $0.01... if it is more than that, it negates that condition and does not allow the Free Order payment method in the cart.

I changed that CA to instead check whether the cart had the discount(s) in question. If the discount(s) was used, the cart pulls in the Free Order payment method, and it all works as expected.


Empty search redirect to Home page I am using Drupal 7 and my search functionality is not working properly.

When I click on search button without enter any keyword it redirects to home page with showing the message Please enter some keywords. and same thing happens when there is no result found for the respective search keyword.

So can anyone please guide me how can I redirect the empty search to search page?

Thanks in advance...

Something like this should work:

/**
 * Implements template_preprocess_search_results.
 */
function YOUR_THEME_preprocess_search_results(&$variables){
  $results = $variables['results'];
  if(count($results) == 0){
    drupal_goto('<front>');
  }
}


Meta tags not showing on front page I'm using the module "metatag" to make my website SEO friendly. This works very well for all pages except the front page.

I go to modules -> Meta tags -> Settings -> Global: Front page

There I set a description. But this description isn't shown if you search the site directly in google. All other pages are working great, with the correct description.

When I look at the source, I see no meta data included at the front page.

You need to assign a node to be 'front'. Otherwise the meta won't show.


How to create a Node Info Bar (or Node Info Block)? I want to create a teaser with 3 sections:

Title Section.
Information Section (Info Bar):

When this Node Writed? (Date & Time).
Whom is writed this Node: (Author of Node).
What category consist this: (taxonamy or category).
How Many Viewed (Node View Statistics).
How many add Comment (Comment Statistics).

Show only "Read more" Linke: at the bottom of a node teaser and remove or unset other links like the "Add New Comment", "2 New Comments", "2 Comments" at the end of a node teaser,
because I dont think it makes good sense for people to comment on something that they haven't read yet.

I want to achieve something like the following picture:

Views module covers pretty much everything you want. You only have have to solve "node views count" somehow (extra field, hidden from display).


How to pass arguments based on term filter I have content type called 'software' and added taxonomy terms to this content type as select list. There are 10 taxonomy terms in that list.
And now I have created 10 pages under this 'software' content type with 10 different taxonomy terms selected among them.

> Page1 -> Term1
> Page2 -> Term2
> etc.

What I need is, If i see www.mysite.com/taxonomy/term/3  in the url, I need to display only the page title of the listed nodes in the view (rather than the title and teaser), for those nodes tagged with taxonomy term(3).

How can I achieve using views arguments and filters?

If I understand your question correctly, here are the steps you'd need to take to override the default taxonomy term view with your own customized one.

Go to the listing of available views on your site at /admin/structure/views and at the bottom of the page you'll see grayed out views that are not enabled.  One of them will be the Taxonomy term view which is delivered by default with the module.  Let's go ahead and clone it, so we can customize to fit our needs.
Hit 'clone' next to that view, in the drop-down options and rename it to something like 'Custom Taxonomy term'

Next, navigate to the 'Page' display and change the Format to display 'Fields' instead of 'Content: Teaser'

Add whatever fields you want.  It sounds like in your case, you'd want to add the Title field.  I would uncheck the label from being displayed (uncheck 'Create label') when configuring the field.

Finally, save and navigate to your view again: www.mysite.com/taxonomy/term/3 and see the change!  Your new view should be picked up and will replace the old one.

Go ahead and beautify and edit as you please from now on to customize the default terms view.  Hope this helps!


programmatically create one bean block to the default theme I am trying to programmatically create beans in a custom module using entity_metadata_wrapper. This is creating a bean for each installed theme. (In Drupal 7)

Is there a way I can create only one instance of the bean block?

for example in my database it creates a bean block for

my subtheme
omega
seven

I would like to only create one block/bean for my subtheme. I am then using mymodule_beans_block_info_alter(&$blocks, $theme, $code_blocks) {} to then change region location and other block parameters.

function bean_ctas_enable(){
    foreach(bean_ctas_info() as $bean_content){
        $bean_ids = array();
        $bean = bean_create(array('type' => 'block_cta'));
        $bean_wrap = entity_metadata_wrapper('bean', $bean);
        $bean_wrap->label->set($bean_content['label']);
        $bean_wrap->title->set($bean_content['title']);
        $bean_wrap->field_text->set(array(
            'value' => ($bean_content['field_text']),
            'format' => ('full_html'),
            ));
        $bean_wrap->field_link->set(array(
            'url' => ($bean_content['link_url']),
            'title' => 'Read More',
        ));
        $bean_wrap->save();
        $bean_ids[] = $bean_wrap->bid->value();
        //set variable to store bean ids
        variable_set('bean_ctas_bean_ids', $bean_ids);
    }
}

I used hook_block_info_alter(&$blocks, $theme, $code_blocks) to alter the blocks in my custom modules .module file

inside of my  hook_block_info_alter i wrote an if statment

if($blocks['bean'][$key]['theme'] == variable_get('theme_default', '0')){}

to make sure I was only altering regions only for my default theme


how to manage url redirects in drupal 7 My website is currently accessible via 2 address

www.mydomain.com
and
mydomain.com

What is the best way to manage redirects. I would like

mydomain/blah to redirect to www.mydomain.com/blah

I always use the vhost file for this:

# Enforce domain.
RewriteCond %{HTTP_HOST} !^example.com(:.*)?$
RewriteCond %{HTTP_HOST} ^(?:.*?)(:.*)?$

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

I would much rather to this on the Apache level, than PHP, to keep it as fast a possible.

Similar configuration for nginx here.


WYSIWYG with CK editor Profiles I am using WYSIWYG with CK editor library. The problem is its showing blank toolbar by default on WYSIWYG editor on node add/edit page. To make the buttons appear on the WYSIWYG toolbar I always have to goto admin/config/content/wysiwyg/profile/full_html/edit

and have to select which buttons to appear on the WYSIWYG editor toolbar.

Is there a way we can select all check boxes at once

You can do that with Firebug or any other browser that has a console. You need to go to edit page of the WYSIWYG profile and on this page, open Firebug or your browser's web developer tool. And in the console enter this line and run:

jQuery('#edit-buttons input.form-checkbox').attr('checked', 'checked');

This will set all the checkboxes under 'Edit buttons' section and you can save your setings.


How to make a custom translatable string? For example, i've a array contains string for each elements

$description[] = $discount->short_description;

foreach ($description as $value) {
$line.= $value."
";
}

the $line will be used in

  $output[$field_name] = array(
    '#theme' => 'field',
    '#title' => $instance['label'],
    '#label_display' => 'hidden',
    '#field_type' => $field['type'],
    '#field_name' => $field_name,
    '#bundle' => $node->type,
    '#object' => $node,
    '#items' => array(1),
    '#entity_type' => 'node',
    '#weight' => $display['weight'],
    0 => array('#markup' => t($line)),
  );

how can i make this $line will appear in admin/config/regional/translate/translate, so i can translate it?

Clear caches. Then, go to http://example.com/admin/config/regional/translate/i18n_string and hit "Refresh strings" button. This should do it.

Also, t() is known to cause problems if used on variables, not strings directly. But most of these problems affect tools that tries to extract strings into .po files, so there is a fair chance it will work for you. But think twice if you really need a variable there.

If it happens to you that your string aren't recognized by panel, you can use one more method. Write your own .po file. Structure is as follows:

white-space
#  translator-comments
#. extracted-comments
#: reference...
#, flag...
#| msgid previous-untranslated-string
msgid untranslated_string
msgstr translated_string

Repeat this (in one file) for all strings. Create one file per language you want to translate to. Then go to http://example.com/admin/config/regional/translate/import and import your files. From now on, strings will be available for translation in interface.


Creating a Field in order to add Icons to content's Title we want to add Icons before the Content's title just like the picture below (icon before Glory of the Hero):

but the problem about the stuff already existing in prior asked questions is that we're gonna work with that a lot in our site , so if we're gonna code it for EACH title, it wouldn't be useful for us >>>>> so we wan to add a field in our content types for example called title's image , and so each time we upload a file there, we'll have an icon before that content's title.

I've already read:

Icon images with node title
https://www.drupal.org/node/140517
https://stackoverflow.com/questions/8976315/drupal-7-display-images-instead-of-nodes-titles
https://stackoverflow.com/questions/10665893/how-to-add-image-with-title-of-an-html-page
Optionally add image/icon after node title based on boolean content type field?
https://www.drupal.org/node/270332

and they didn't help at all...
is there any way to do that?

You can do this by creating node.tpl file.

    <?php print render($title_prefix); ?>
      <?php if (!$page): ?>
     //"print image here"
 <h2<?php print $title_attributes; ?>><a href="<?php print $node_url; ?>"><?php print $title; ?>

      <?php endif; ?>
      <?php print render($title_suffix); ?>

You can get all the field value here and just print the image before the title.


Some variables not listed when creating feature I'm building a feature that includes modules settings stored as variables. Strongarm module is great for that but for some reason, pathauto_entity's module variable called pathauto_entity_available_entity_types is not listed as available strongarm variable when I'm creating new feature.

The variable is listed on Strongarm's admin page when I go to admin/config/development/strongarm.

Any ideas why this is happening? Is it strongarm or maybe CTools issue?

The variable exists in database and I can read it with drush without problems.

If that variable is showing up in the Strongarm admin page, then it means that it's already strongarmed - it probably already exists in another Feature. Use the grep command to search for instances of it in your codebase:

grep -irn 'pathauto_entity_available_entity_types' [codebase-dir]

I bet that will turn up an existing Feature that is managing that variable.

You can't export the same variable to more than one Feature. But you can override it with the Features Override module.


Insert the next recurring charge date in custom table when user purchase a product? My site have a subscriber role that have some special permissions. User has to purchase the role. I used ubercart module for this.

I added a feature to assign role on purchase of subscription. Subscription can be for 1 week, 1 month or 1 year. User can cancel own recurring charge. Uc_role module manages the assign and remove role of user. It handles the next date of recurring. But uc_role not manages the past date.

My question is that I want to show the user who purchase a subscription in past. Is there any hook or something so I can work on it?

I have done something similar although I don't think it's the best way.

I created a rule that is triggered with the event I wanted and then added an action which was custom php. Then use drupal db api to make the update or insert in the table.

https://drupal.org/project/rules
https://api.drupal.org/api/drupal/includes%21database%21database.inc/function/db_query/7


Can you display data dynamically from a textfield in the URL and Name of Views? I have a content type of Product which includes a text field for the user to enter a Brand. This text field is open to the users to enter correctly, as there are hundreds of brands and I don't want them to have to learn how to enter taxonomy terms.

I am wondering if there is a way to dynamically create a View that will also dynamically generate the page name and page URL depending on the brand, and then display a table view of all of the Products with that Brand.

So for example if I have /category/brand/product-name as the parameters for the URL, for a specific product it would be /tshirt/busted/open-road, and with Busted being the Brand entered by they user, the view would automatically create the /busted url, and populate it only with Busted brand products in a table view.

Is this possible? I was thinking perhaps I needed to use tokens to grab the [node:field_brand], but I am unsure exactly how I would do this, or if it was even possible. Also, if there is a better way of handling this data instead of a textfield, I would like to know!

I think you can still use taxonomy for this. The taxonomy can be open ended not need to make it closed to the terms you define.

When you add a taxonomy reference field choose the widget as autocomplete this will enable the user to add their own taxonomy term which may not be there in the list already.

If you are very particular about using the field then you can use that a contextual filter in a view so that it would appear in the url as mentioned.


Extend core modernizr library I am noticing objectFit is not part of Drupal 8 core/modernizr library. How do I add objectFit detection without overriding core modernizr?

I'm pretty sure you have to override core/modernizr with a later version in order to get objectFit.

Download an updated modernizr.js and include objectFit.
Place the file somewhere in your theme's path (js/ or scripts/)
In your theme's info file (theme-name.info.yml) , override the existing modernizr library

libraries-override:
  core/modernizr:
    js:
      assets/vendor/modernizr/modernizr.min.js: scripts/modernizr.js

You should now have access to objectFit.


Adding a base field definition in an update hook - it's not appearing I want to add another base field to a Drupal entity. It used to be possible to just change the code for the entity definition and then update it via the Drupal console. But now it has to be done in an update hook.

I've added the following update hook, done drush updb and the process completes without errors. I then did drush cr to clear the cache, and then opened up the edit form for the entity in question and gave it a hard refresh. But the new field has not appeared. Any idea what I'm doing wrong? Thanks. The code is based on this: https://www.drupal.org/node/3034742, section named "Installing a new field storage definition".

function opencase_entities_update_8002() {
  $storage_definition =  \Drupal\Core\Field\BaseFieldDefinition::create('datetime')
      ->setLabel(t('Date and time'))
      ->setDescription(t('When the activity started.'))
      ->setRevisionable(TRUE)
      ->setSettings([
        'datetime_type' => 'date'
      ])
      ->setDefaultValue('2000-01-01')
      ->setDisplayOptions('view', [
        'label' => 'above',
        'weight' => -3,
      ])
      ->setDisplayOptions('form', [
        'weight' => -3,
      ]);

  \Drupal::entityDefinitionUpdateManager()
    ->installFieldStorageDefinition('activity_date_time', 'oc_activity', 'oc_activity', $storage_definition);
}

The problem lies in your display options configuration (reference 4k4's answer to #244122).

Try this:

function opencase_entities_update_8002() {
  $storage_definition =  \Drupal\Core\Field\BaseFieldDefinition::create('datetime')
      ->setLabel(t('Date and time'))
      ->setDescription(t('When the activity started.'))
      ->setRevisionable(TRUE)
      ->setSettings([
        'datetime_type' => 'date'
      ])
      ->setDefaultValue('2000-01-01')
      ->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'datetime_default',
        'settings' => [
          'format_type' => 'medium',
        ],
        'weight' => -3,
      ])
      ->setDisplayOptions('form', [
        'type' => 'datetime_default',
        'weight' => -3,
      ]);

  \Drupal::entityDefinitionUpdateManager()
    ->installFieldStorageDefinition('activity_date_time', 'oc_activity', 'oc_activity', $storage_definition);
}

Edit: Don't forget to update your Entity definition as well!


The answers are being cut off I'm using the FAQ module on my Drupal website; I noticed that, on one of the questions, the answer has been completely cut off.

I've tried changing input format (e.g. full HTML instead of WYSIWYG), but I'm still having the same problem.

Is there any problem with the module, or am I doing something wrong?

I figured out the answer to this problem

I went to admin/structure/types/manage/faq/display/teaser and noticed that the format said 'Trimmed'. I changed that to 'default' and the answer is no longer cut off.


What are some php cache related modules for drupal 7? i just updated my server to php 5.5 and been reading about apc and opcache, and I'm not to sure which one to use or what modules support this feature. What are some modules or modifications to drupal 7 that take full capabilities of these php caching mechanisms? Am i correct that opcache is superseded by opcache for php 5.5?

For opcode caching APC, Zend Optimizer, and OpCache are totally transparent to the application.  If you have them installed and enabled, Drupal will use them whether you like it or not.  There are some configuration tricks you can do to use them better, but this is really system specific.  For example, to help save memory, some users will filter out .admin.inc files from APC so they never get cached.

I am using OpCache on my PHP 5.5 servers.

To confuse matters, APC and Zend provide user caches which can be used as alternate cache backends to replace and/or supplement the database cache mechanism.  I would not recommend APC for this.  Memcache and Redis are the go-to solutions for these.  MongoDB can also be used, too.

My PHP 5.5 servers also have APCu installed just in case there is anything that may be using it.  Last time I checked, the Performance module would use APC user cache for stats.


How to use node field tokens as a value in Metatags module? I am trying to optimise SEO on my site by ensuring that each page has a unique value for descriptive metatags.

I am trying to achieve this using the Token and Metatags modules, and am using Drupal 8.

To do this, I have added a field called "Description" to both the basic page and article content types.

I would then like to use the [node:field_description] token as the value for any relevant metatags in the Metatags module.

However, when I view available tokens in the Metatags module the [node] token is not available and the [current-page] token doesn't appear to have any way to reference the main node displayed within that page.

I know this issue has been discussed extensively for D7 and this issue appears to provide what I'm looking for:

https://www.drupal.org/project/token/issues/919760

Is there an equivalent solution for D8? Alternatively, what's the best way of achieving this?

This from Mario Steinitz (in comments) answered the question:

"I'm not at my desk anymore for today, but I'm pretty sure you have the [node] token available for content meta tags and can access field content as well. We're using these tokens regularly for all D8 sites we're working on. Where did you try to add them?"


Reminder action for users I'm using drupal 7.
Simply i need to remind some user every 28th to do something.
What the best module to make a reminder for users?

You could use the Rules module to do this.


Menus - hard coded primary nav with per-page sub nav My primary navigation is hard coded (it has to be; graphical purposes).

Firstly, how can I tell which one is "active" (current page)?

Secondly, based upon which one is active, how can I show child links of that link in the sidebar? I've thought of a possibility, but it would require creating tons of blocks for the menus and then only enabling them on their parent page. This seems like a lot of work for something that a module should take care of.

I've found http://drupal.org/project/menu_block which looks promising, but I'm not clear how to use it in my situation.

I prefer to have total control of how the menus will look (a custom .tpl file)

I am not sure which part you need hardcoded, but if it is everything but the a tag, then then l() helper function comes to the rescue:

    <?php print l("Foo", "original/path/to/foo") ?>

Now, if you access "/original/path/to/foo" or (on of its) alias(es), the l() helper will automatically add a class "active" to the a tag, generated by l().

If, for some reason you need the l() outside of the a, or if you want to customize the a itself (e.g. by adding markup to it), you can use the code seen in the l() to determine activeness  of the current item. Place this as helper in template.php of your theme:

function _my_theme_is_active($path) {
  $active = FALSE;
  if (($path == $_GET['q'] || ($path == '<front>' && drupal_is_front_page())) &&
      (empty($options['language']) || $options['language']->language == $language->language)) {
    $active = TRUE;
  }
  return $active;
}

Obviously my_theme is the name of your theme.

Then in the tpl.php files, or anywhere in the scope of your theme, you can use the function:

  <a href="<?php print url("original/path/to/foo") ?>" <?php print (_my_theme_is_active("original/path/to/foo") ? 'class="active"' : ' ') ?> id="foo-1">
    Foo

Beware that you use url() to catch aliasing for the oringial path, but that you /do/ pass in the original (system) path into the _my_theme_is_active helper.


How to add Replace (mysql) function in view query condition field I am using EntityReference Autocomplete with filter by entity reference view. And I want to ignore space in search filed.

For example, column username in DB has value first name it should popup when user types first or firstname. To achieve this I wrote hook_views_query_alter to change the condition, I would like to pass the condition as REPLACE(username, ' ', '') LIKE '%firstname%'.

Even if I set field value in condition to REPLACE(username, ' ', '') its getting changed to REPLACEusername. Even I tried running the query separately, like below in node,

$query = db_select('node', 'n')
              ->fields('n', array('title'))
              ->condition('type', 'article', '=')
              ->condition('REPLACE(n.title, \' \', \'\')', $category, 'LIKE')

When I output query prints like below,

    SELECT n.title AS title FROM {node} n WHERE (type = 'article') AND (REPLACEn.title LIKE '%articleone%' ESCAPE '\\')

How can I set it correctly? Is there any other way to do?

I don't think condition is what you want, rather expression. And then, to use that expression as a condition, you might need to use havingCondition-- but I'm not sure, test it out. Also note that you need % for a wildcard matching in SQL, so you might have to do ->havingCondition('title', '%' . $category . '%', 'LIKE');.

So, your final code might look something like this:

$query = db_select('node', 'n')
  ->addExpression('REPLACE(n.title, \' \', \'\')', 'title')
  ->condition('type', 'article', '=')
  ->havingCondition('title', '%' . $category . '%', 'LIKE');


Highlight active page in a table row using views I have a drupal 7 view that is outputting the titles of nodes which is in table form.

       Link 1

        Link 2

Drupal gets me close by adding "active" class to the link (Link 2), but I would like it for the entire row (TR).

I saw another question like this one asked for an unordered list, but I tried that code and it didn't work. Maybe a little tweaking needed?

Thanks guys!

I was able to get the answer using jquery. Hope this will help others who need it. Just add this code into the top of the page template and it will create the active class for you.

<script type="text/javascript" charset="utf-8">

$(function() {
   $('.views-table a.active').closest('tr').addClass('active_row');
});

</script>

Remember to change the "views-table" to match your own table.


Serial vs int schema data type options When should serial be chosen over an int when choosing a data type for a table column? Are they separated out for indicating a difference in the data types. If so what type of data should be stored as serial and as int?

Examples would be greatly appreciated.

Serial is used for auto-increment column of the table(so here auto increment is implicit), e.g. for node table nid has a serial data type and int can be any number based on size provided.

  'type': The generic datatype: 'varchar', 'char', 'int', 'serial',
  'float', 'numeric', 'text', 'blob' or 'datetime'. The types map to the
  underlying database engine specific datatypes. Use 'serial' for auto
  incrementing fields.

Reference: https://www.drupal.org/docs/7/api/schema-api/schema-reference


How to view "your own comments" without the permission view comments? In Drupal there is a permission "view comments" and "add comments". I would like to activate "add comments" and disactivate "view comments". How to allow to view your own comments for users? It's a little bit strange to publish comments and they disappear into nowhere.

I think this kind of logic is better handled in a custom module instead of the theme layer. Something like this might work for you:

/**
 * Implements hook_permission().
 */
function mymodule_permission() {
  return array(
    'view own comments only' => array(
      'title' => t('View only own comments'),
      'description' => t('The user will not see comments made by other users.'),
      'warning' => t('Sometimes this might not work...'),
    ),
  );

}

/**
 * Implementation of hook_query_TAG_alter()
 */
function mymodule_query_comment_filter_alter(QueryAlterableInterface $query) {
  if (user_access('view own comments only') && !user_access('administer comments')) {
    $query->condition('c.uid', $GLOBALS['user']->uid);
  }
}

This defines a view own comments only permission. If this is set and the user does not have the administer comments permission, comments made by other users will be hidden on the node page.

There are a few problems with this solution (and you'll probably have the same problems if you are trying to do this in a template file):

comment count will not be modified
Recent comments block will not be modified


Should I put my site on maintenance mode before using "drush sql-dump"? When performing drush sql-dump, should I set the site in maintenance mode or will this command makes sure a coherent dump will be generated even if users are busy using Drupal? I can't find confirmation in the documentation.

According to Moshe's answer in advantages of drush bam vs. drush sql-dump / drush sql-connect, the answer is no.  drush sql-dump does the right thing and will result in a consistent backup.


show all the blocks added to the particular page? I've been tasked to remove a tracking javascript from a particular URL on our Drupal 7 website. I've grepped our site's codebase for the name of the javascript that's being loaded, but I don't see it.

I need to start combing through content, but I'm looking at making my task easier.

Sometimes our front-end devs will include scripts in blocks. I want to look at all the blocks that are included in my target URL, but I don't see how to do that in the interface.

It seems that I must look at each of our blocks and then see if it's added to the page. I wonder, however, if there is a page somewhere in the admin menu where I can enter the URL I'm looking at and see what blocks are being attached to it.

The simple answer is that there isn't such a page. But you can go to the block administration page and see a list of all blocks for the given theme. If there is a 'configure' link for the block, it's a block that was created through the admin interface, so you can go through them to try to find the block in question.

The other thing you can do is examine the HTML to find the HTML id for the block. This will give you an indication of which block it has been added to, or if it was even added through a block or not.


change background color in Drupal 7 I have Drupal 7.14 and Zen 7.x-5.1. I cannot figure out how to simply change the background color. I have tried placing background: red; in several of the css pages but have had no luck.

The Zen theme uses many different CSS files. You need to create a subtheme for Zen and then you are supposed to choose which layout you want. Fixed or Liquid.

Within the subtheme there are many CSS files. Depending on your choice of Fixed or Liquid you have to edit that css file...

layout-liquid.css
or
layout-fixed.css

Within that file you can change the parameters you are trying to override. As long as you don't have css files aggregated in the performance settings you do not need to clear the caches, otherwise you do.

To create a Zen subtheme you need to follow a tutorial:
http://drupal.org/documentation/theme/zen

I recommend going through that completely and reading and learning as much about Zen as possible. One thing to know is that you never want to alter the core files of Zen, you only want to override them in your own subtheme.

Lastly, adding your own custom CSS file can be useful, but for this situation it would not be recommended because there are already CSS declarations for your use. I use a custom Zen subtheme for this site: https://www.fdanconia.com/ - I love the Zen theme structure and once you learn where everything is and how to override everything is a great theme to use.


Views tagging question (bulk update tags) We have a few taxonomies and don't want users to spend time tagging content. Ideally, we would like to have a view where we could tag content without opening each node.

A module exists for exactly this purpose in D6 but nothing in D7.

http://drupal.org/files/images/views_tagger_screenshot.png

Is there any other way to accomplish this??

Found a solution, via the editablefields module!! Here is a quote about it (from the module's project page):

  ... allows CCK fields to be edited on a node's display (e.g. at node/123), not just on the node edit pages (e.g. node/123/edit). It also works within views etc. Anywhere a 'formatter' can be selected, you can select editable (or click to edit).


How can a form remember the selected tab after submit? I'm using vertical tabs in a form, and I keep all the values with $form_state->setRebuild(true);. In this way, the user can change some of the submitted values.

I would like to keep the selected tab active as well. How can I achieve this?

If there aren't other solutions, I will use JavaScript to manually select the tab after the form is reloaded.

You should be able to see which vertical tab was selected at the time your form was submitted. If not, you can certainly use js and a hidden field to keep track of it. Once you have it submitted your form then you can easily set the #default_tab of your vertical tabs based on the value in your the recently selected tab. Something like this:

$form['information'] = array(
  '#type' => 'vertical_tabs',
  '#default_tab' => isset($form_state['values']['selected_tab'][...) ? $form_state['values']['selected_tab'][... : "some_tab",
);

Another option would be to use a pure js solution. By storing the currently selected tab in local storage and then selecting that tab when the form loads should work as well. In this case you may see your form "flash" as the selected tab is selected but that may or may not be a problem depending on your form and desired UX


Change workbench_moderation_state from select to radio I have workbench installed, and want to change the moderation status dropdown in the add node form to a radio.
But I don't get it. I have a custom module with a hook_form_alter hook which prints the $form array via

  dsm($form)

This does NOT print any workbench_moderation_state variable.
If I print it via print_r($form), I get a

 [...]
 [workbench_moderation_state_new] => Array (
   [#title] => Moderation status
   [#type] => select
   [#options] => Array (
     [needs_review] => Current: Needs Review
     [draft] => Draft
     [published] => Published
   )
   [#default_value] => needs_review
   [#description] => Moderationsstatus für diesen Inhalt setzen.
   [#access] => 1
 )

So it has to be there.

Why is the workbench_moderation_state_new Array not displayed in krumo via  dsm(), but printed via print_r()
(more important) Why the f**k does a simple

  $form['workbench_moderation_state_new']['#type'] = 'radio';

  not change the select into a radio, but introduce a new empty radio button in the form? I tried to follow the Drupal form API.

Argh. As almost always, I found the answer myself 5 minutes after posting here. Cost me 3 hours of searching and try-and-error before. workbench_moderation_state_new is a sub-array of options.

So a $form['options']['workbench_moderation_state_new']['#type'] = 'radios'; does the trick. Mind 'radios' instead of 'radio' as well. For anyone interested.
Problem solved.

$form['options']['workbench_moderation_state_new']['#type'] = 'radios'; does the trick.
I just forgot the ['options'] array.


Can't restore profile-installed site after D7.12 core upgrade I have just attempted to do another minor core upgrade from 7.9 to 7.12. While the former went rather smooth, the latter is giving me a headache. I constantly get fatal errors like these below:

Notice: Undefined index: schema_fields_sql in /includes/entity.inc on line 265

Catchable fatal error: Argument 2 passed to SelectQuery::fields() must be an array, null given, called in /includes/entity.inc on line 284 and defined in /includes/database/select.inc on line 1300

I am now in the middle of yet another attempt to restore the site

The difference in that website, compared to that which successfully passed the core upgrade, is that this was originally installed using commerce kickstart profile. And my questions are:

Has anyone successfully performed core upgrade within a
profile-originated site?
What are safety rules to observe when doing
such upgrades (apart from obvious backing up the files and
database?)?
What approach you prefer for upgrading live sites? Do you usually create a new directory, which you test, and when ready, you redirect root catalog to that directory?

I hope your insights will bring back my confidence as per having chosen Drupal for commercial sites.

Did you remember to run update.php?

Also, Drupal 7.11 and 7.12 are both security updates. 7.12 includes bug fixes, while 7.11 only addresses the security problems. You might try 7.11 and see how it goes.

Also 2: Here's an issue thread about it.


Front class not included in body tag in my custom module We are trying to make a Drupal mini bootstrap for our language selection module.
We implemented hook_boot(), in this function, we included path.inc and common.inc from core.

The language selector always redirects to the frontpage of the according language.
Now the problem is that, when loading the new page, the class of <body> is not-front. This means that front-specific styles, and template are not used; it just uses the default ones.

We are guessing that we missed something in the Drupal bootstrap process.

Do you have any idea?

If memory serves me correct the "front" class will only be set on the body, if the URL you are on matches what is set in the "Site Information" > Front Page field.

My guess is that you'll need to override the string or array of body classes in the template.php file of your theme. To do this you'd want to use the template_preprocess_html function provided by Drupal core.

Here is a quick and dirty example of how to add the class to the body of your theme:

function THEMENAME_preprocess_html(&$variables) {

  if (theme_get_setting('my_variable') == 0) {
    $variables['classes_array'][] = 'front';
  }

}

From there you'd need to figure out what classifies the home page as the home page with some conditionals or custom functions.


Leaflet Map disappears when selecting term in views exposed filter I'm using leaflet in a content view with a page having an exposed filter on taxonomy terms.

Problem is whenever a term/filter is selected and applied the map disappears and turns grey.
I'm using Leaflet More Maps and this seems to happens with any map.

You must use global area views from other block with generic map, should not have results always show you the map.


Automatically add class to images added through CKEditor I'm trying to add classes automatically to images which are added through CKEditor, I have spent considerable time trying to research this and found How to add class or attribute automatically to img tags in CKEditor? & Create new dom elements using dataProcessor.htmlFilter which hint at solutions that I can't get working.

I'm using the CKEditor module rather than WYSIWYG and found it's possible to add a new plugin using hook_ckeditor_plugin and my new plugin appears as a selectable option in the CKEditor admin, based on the 2 documents provided I managed to put together:

( function() {
  CKEDITOR.plugins.add('imageclass', {
    init : function( editor ) {
      var rules = {
        elements: {
          img: function( element ) {
            console.log(element);
          }
        }
      };

      // It's good to set both filters - dataFilter is used when loading data and htmlFilter when retrieving.
      editor.dataProcessor.htmlFilter.addRules( rules );
      editor.dataProcessor.dataFilter.addRules( rules );
    }
  });
})();

The problem is that nothing get's written to the console, I changed the line img: function( element ) { to $: function( element ) { which then writes all the elements at the root to the console, but all images, spans, etc. don't get written to the console as they are children of other elements (p, div, etc.) and I think this is something to do with the way CKEditor is integrated with Drupal and the options available via text formats.

I just don't understand enough about CKEditor and the documentation isn't easy to follow on how to move through more than just the elements at the root, unless trying to create this as a plugin is the wrong way to go.

Ok, I got the answer.

Forget about the simple image plugin. Let's use the default image plugin from CKeditor.

Go to sites/all/modules/ckeditor/ckeditor/plugins/image/dialogs

Open the image.js file in notepad.

Search for c.lang.common.cssClass beside it you should see a "default": "",

So just type your class in between the default quotes.

For Example: "default": "MyCustomClassName",


Menu items with Userpoints total Is it possible to show the current total userpoints a user have next to menu item?

example menu: Home | Downloads | My Points (24) | Logout

if it's possible, how would one do this (beginner)

This snippet will return you user points :

<?php
print userpoints_get_current_points($user->uid);
?>

But to Place this PHP snippet in menu link, you may need Menu views and PHP Menu Modules


How to create forms similar to admin block forms I want to create a form similar to Admin Block Settings form.
So far I have created draggable table, how can I add Enable and Disable sections to the form ?
I checked out Draggable Views module but it does not work out for me as I am creating a custom form.

Here you have two examples to learn how to build a custom module with drag and drop elements:

http://coffeeshopped.com/2010/09/drupal-drag-and-drop-tables-in-custom-modules

http://www.computerminds.co.uk/quick-guide-using-drupal-add-tabledrag-and-enjoying-jquery-drag-and-drop-loveliness

Oskar


Entityqueue - Get field values from the queue First off, i'm very new to Drupal. Kindly help me and forgive if im being a noob.
Im using the module - Entityqueue https://www.drupal.org/project/entityqueue
Im created a view block for a entity queue that gets specific blog articles.
The problem im facing is that, this view only gets the blog title, and not the other custom fields within each blog.
Is there anyway to get the custom fields also ?
Thank you for your support.
EDIT: Please see below for screnshot of what i've done.
Entityqueue

View Block

If i select fields below, it doesn't get the custom field that are in the blog article.

I have found a solution.
After you create the entity queue, go to view and create/edit a view block.
Select Relationship as Content queue, now you can get the fields in the fields section.
Hope this helps.


Can a sidebar span two zones in omega 3 theme? I'm a bit of a newbee with Omega 3. I am having trouble arranging a grid which has a vertical sidebar span two zones. See the attached  diagram to understand the design requirements. I need to have a left sidebar and content block both appear under the header, and a right sidebar that spans both the the header and the content.

I would like to know if it is possible to create such a grid within the standard Omega UI, or if not how can this be accomplished.

Thanks!

No, with the way the HTML is built, it goes

zone-wrapper div (if used)

zone dov

region div

In your case, I would leave the Header zone empty (make sure the checkbox for forced rendering is off), and then move all of your regions to the Content zone.  In the grand scheme of things, there is nothing special about the Header zone.  I am looking at one of my sites now, and I left Header empty.

With the default templates, the Content zone also contains the Breadcrumb and Messages, so you may need to tweak this a bit to output the regions specifically to get these in the proper place.