Does Drupal automatically unlink() orphaned files? Does Drupal 7 have a way to automatically remove images that are no longer linked to an entity, or do they need to be unlinked manually?

For example, how would Drupal react to the following detachment of a file from a node:

$nid = 7;                      //A node containing an image field.
$node = node_load($nid);       //$node->field_image is a populated Imagefield.
$node->field_image = array();  //$node->field_image is set to an empty array.
node_save($node);              //$node is saved.

Will the orphaned fid sit in the files directory indefinitely or will Drupal remove it automatically?

The images will be automatically deleted if they were added through a regular image upload field. In that case Drupal understands that that image is related solely to that one node/entity.

In case you are using some other module for inserting the images, it depends and might not be deleted.


7 mysql workbench get the values of entity reference fields of a content type in a node page I am using MySQLWorkbench queries to update some values. Those values are entity reference fields of a content type.

 foreach ($node->field_media_types['und'] as $mt) {
    $media_types[$mt['field_media_type']['und'][0]['value']] = $mt['field_media_file']['und'][0]['value'];}

The code above is how it is access on a script. I want using MySQLWorkbench  or just MySQL CLI acces those values on quick queries.

select entity_id, field_media_file_value from field_data_field_media_file order by entity_id desc;
(0 rows return)

How do I do it? Is it possible?

Yes it is absolutely possible, and your query you posted is written correctly. If you are returning 0 rows that means there are no records inside the table field_data_field_media_file. Your query literally says to return everything in that table, and 0 things come back.

Review all of the tables in your database and make sure "field_data_field_media_file" is what the field is actually called. Either you are looking at an old/wrong field OR there is simply no nodes with this entity reference field populated.

for your reference the tables relate like this:

The parent node that has the reference

{Node}.nid => {field_data_field_media_file}.entity_id

The node that is being referenced

{field_data_field_media_file}.field_media_file_value => {node}.nid


Alter menu link if logged in I have a regular node in my main menu that:

if an anonymous user clicks on it, the node should be shown regularly
if a logged in user clicks on it, there should be a redirect to an external website

I tried

HOOK_menu_link_alter
but that only is invoked on edit-and-save (if menu item is created via web)

HOOK_node_view
that seems to work but does not seem like a good solution to load the complete node and check for the user just to redirect

Instead of altering the menu link per role (which is tricky considering the process with which menus are built and cached), I would suggest you go for adding redirects per role.

The Url Redirect module should be able to help you achieve it.

  Url Redirect is a simple, flexible module for allowing user(s) / role(s) to redirect from one
  path to other.
  Url Redirect is also handy to add / edit / delete url(s) , specify role(s) / user(s) for url
  redirect, set a message for url redirect, enable / disable.


Adding a new user directly in database I've been given the files to a Drupal site so I can create a new theme. I haven't, however, been given the Drupal admin user/password date so I can't sign in to the admin area. Is there a way I can create a new user directly in the database or some other way?

There's a much easier way.

Go into the DB and change the email address field of the user with id 1 and set it to your email address.
Go to http://mysite/user and click on the password recovery link.
Enter your email address and you'll get a password recovery link.

Of course this assumes that your dev systems allows drupal to send mails out of the box. This is true for most linux and osx boxes but not for Windows.


Drupal 7 Commerce - How do you style the Please wait loading message/icon when you select an attribute? I'm trying to style the please wait loader icon when you select an attribute for a product in drupal 7 commerce. I'm using chrome and i can't figure out a way to right click inspect element fast enough as it loads to fast. Or is there another way to expose this? I just need the HTML and classes associated with it.

For example:

/* Custom ajax throbber style */
.ajax-progress .throbber {
  /* New icon */
  background: transparent url(../images/ajax-loader.gif) no-repeat 0px 0px;
  /* icon is 15px square */
  height: 15px;
  width: 15px;
  /* Alignment, may tweak to suit */
  float: left; /* LTR */
  clear:both;
  margin: 2px 2px 8px 2px;
}
.ajax-progress-throbber .message {
  /* Hide the "please wait" msg */
  display: none;
}


Open views content in new window? Is there a way to open content in new window or add back button to it in views?

When you click on a content title from Views list there needs to be a quick way to navigate back to that list after viewing content.

In views there is an option called Rewrite out put. You can use the rewrite out but as link and Provide the link as well as the target.

If everything is going through views then you can change the path of your content to reflect the path of your view using the pathauto module and use a breadcrumb module that would allow you to create breadcrumb from the path this way the path to the main view would be displayed in the breadcrumb for better navigation. You can take a look at the breadcrumb module


"Really" disable entire cache during development (also routing, twig templates, css+js libraries) I have followed the community documentation page at https://www.drupal.org/node/2598914 (Disable Drupal 8 caching during development). Now I expect that the caching in my Drupal 8 site is entirely switched off. However, for setting up an new route, a twig template or any css/js library in mymodule/mymodule.libraries.yml, I still need to run

drush cr

to get my stuff recognized by Drupal 8. How can I "fully" disable caching? It is annoying to run "drush cr" dozens of times and repeatedly guess if the specific item is either cached or not..

I asked this on twitter and @renebakx replied:

  @stevepurkiss check how devel modules handles this, it worked for
  templates and added css/js to the theme's library. Not for added
  routes


How can I format the content in horizontal tabular form? I'm using Drupal 7 and below you can see an example of what I want to achieve. Basically I have a specific content type that I want to display as seen in the image.

On the left I want to list some fields of my content type and on the right some content
elements. Basically it's a horizontal table. Also I would like to be able to format each row individually.

I already know that I could do it with the Panels module by creating a variant in the Node Page with a selection rule for my content type and by then adding the nodes manually to a Panel Page.

But that doesn't feel like the most elegant solution. Isn't there a possibility to arrange the content in a view as I want to do it? What approaches would you suggest me?

Do you really care to have tables in the semantic meaning of it?
I mean, you can just print your fields to divs and use float: left for the 3 content elements and for the labels print it manually on a div on the header.

Might not be the most elegant solution but will work and be easier than making it with panels...

The best way to do it would be to print
First Field: Label | Line 1 | Line 2 | Line 3
Second Field: Label | Line 1 | Line 2 | Line 3
But that's not how Views works.

You could also retrieve all the information in a custom module and then manage it however you want. But then, you wouldn't need to use Views module...


Custom jQuery scroll I'm new to drupal 7 and I'm having issues getting the smooth div scroll to work. What I'm going for is this! I also need it to be on every page of the site.

I downloaded the Zip file which is actually for this! I figured I'll alter the js and css files later. I placed in both sites/all/libraries and sites/all/modules. I copied the jquery-ui-1.8.23.custom.min file to /modules folder.

I then pasted this code to my template.php :

function best_responsive_preprocess_page(&$vars) {

//  if we are at frontpage, add some jquery code to do the animation
   if ($vars['is_front']) {
      drupal_add_js('sites/all/modules/jquery-ui-1.8.23.custom.min');
      drupal_add_js('sites/all/libraries/SmoothdivScroll/js/jquery.smoothdivscroll-1.3-min.js');
      drupal_add_css('sites/all/libraries/SmoothdivScroll/css/smoothDivScroll.css');
       $vars['script'] = drupal_get_js();
       $vars['styles'] = drupal_get_css();
   }
}

But that didn't do the trick.

What could be the issue here, or perhaps there is an another way to achieving this?

Many thanks.

is your function called ?
put a drupal_set_message('hello'); in it to see.

remove these to lines, they're not needed

$vars['script'] = drupal_get_js();
$vars['styles'] = drupal_get_css();

then - you need to add some custom JS, where you tell which of your div should be modified:

drupal_add_js('jQuery(document).ready(function () { $("#logoParade").smoothDivScroll({
    autoScrollingMode: "always",
    autoScrollingDirection: "endlessLoopRight",
    autoScrollingStep: 1,
    autoScrollingInterval: 25
});

// Logo parade event handlers
$("#logoParade").bind("mouseover", function() {
    $(this).smoothDivScroll("stopAutoScrolling");
}).bind("mouseout", function() {
    $(this).smoothDivScroll("startAutoScrolling");
}); });', 'inline')

is this div already setup ?

else - add it in page.tpl.php or whereever you like to ..


How can I automatically apply a shipping service and skip shipping selection during checkout? In certain circumstances, you may want to automatically add a particular shipping rate to an order. For instance, you might want to:

use a particular service for estimation purposes
force a particular shipping service based on business logic (e.g. it might be free or fixed cost)
have the customer skip the shipping pane in checkout

You can use Rules for this. You can modify the rule export below and either import it directly into Drupal or include it in MYMODULE.rules_defaults.inc:

/**
 * Implements hook_default_rules_configuration().
 */
function MYMODULE_default_rules_configuration() {
  $configs = array();

  $configs['rules_auto_add_shipping_service'] = rules_import('{ "rules_auto_add_shipping_service" : {
      "LABEL" : "Auto-add shipping service",
      "PLUGIN" : "reaction rule",
      "OWNER" : "rules",
      "TAGS" : [ "Commerce Shipping" ],
      "REQUIRES" : [ "rules", "commerce_order", "commerce_shipping", "entity" ],
      "ON" : { "commerce_order_update" : [] },
      "IF" : [
        { "data_is" : { "data" : [ "commerce-order:type" ], "value" : "commerce_order" } }
      ],
      "DO" : [
        { "commerce_shipping_delete_shipping_line_items" : { "commerce_order" : [ "commerce_order" ] } },
        { "commerce_shipping_method_collect_rates" : {
            "shipping_method_name" : "flat_rate",
            "commerce_order" : [ "commerce_order" ]
          }
        },
        { "commerce_shipping_rate_apply" : {
            "commerce_order" : [ "commerce_order" ],
            "shipping_service_name" : "standard_shipping"
          }
        }
      ]
    }
  }');

  return $configs;
}

In the example above, the rule fires when an order is updated. When an update occurs it:

Removes all shipping line items from the order. (commerce_shipping_delete_shipping_line_items)
Collects rates for the specified shipping method. You can edit the shipping_method_name from flat_rate to any service you are using (it doesn't have to be Flat Rate).
Applies a particular rate. This rate must be collected during the previous step.

Now, your order will always have a shipping rate applied to it.

To skip checkout, you can disable the shipping pane using the UI or use something like the snippet below to handle it in code:

/**
 * Implements hook_commerce_checkout_pane_info_alter().
 */
function MYMODULE_commerce_checkout_pane_info_alter(&$checkout_panes) {
  // No need for shipping since it's auto-selected.
  $checkout_panes['commerce_shipping']['enabled'] = FALSE;
}


Batch removal of users and comments without causing excess load on server I have a basic shared hosting account and don't want/plan to upgrade anytime soon. Unfortunately, my site has been subjected to large scale attacks by spambots that have lead to the generation of thousands of spam comments and users. I would like to delete these, but deleting them in batches causes the server to crash, every time. What should I do to avoid these crashes?

Try setting up a View with VBO.

Add a new users view
Add a bulk operations field to the view
Add a "Delete item" operation to the field settings
Configure the field settings to process "1" per batch
Add any other required exposed filters.

That will delete one user per batch run until finished, so should be fine on your server.


How do I serve up a themed 500 error response page? Has anyone developed a custom themed page for 500 errors on a Drupal 8 site? There is no maintenance offline template equivalent, and core out of the box simply delivers an unstyled stack trace. We've been toying around with a solution in .htaccess, or by hooking into Symfony's exception events.

Anyone had success with either of these approaches?

You may create custom exception subscriber as it is shown below.
Notice that I did not use Drupal theming engine to render the error page. Uncaught exception indicates that something really wrong has happened on a site. There is a great chance that some Drupal services are not available so rendering error page may fail as well.
Also keep in mind that exception subscriber won't catch fatal PHP errors because they are handled differently.
src/EventSubscriber/ExceptionSubscriber.php
<?php

namespace Drupal\example\EventSubscriber;

use Drupal\Core\EventSubscriber\DefaultExceptionSubscriber;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;

/**
 * Last-chance handler for exceptions.
 *
 * This handler will catch any exceptions not caught elsewhere and send a themed
 * error page as a response.
 */
class ExceptionSubscriber extends DefaultExceptionSubscriber {

  /**
   * {@inheritdoc}
   */
  protected function onHtml(GetResponseForExceptionEvent $event) {
    if ($this->getErrorLevel() == ERROR_REPORTING_DISPLAY_VERBOSE) {
      parent::onHtml($event);
    }
    else {
      $content = file_get_contents(DRUPAL_ROOT . '/../500-error.html');
      $response = new Response($content, 500);
      $event->setResponse($response);
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    // Catch the exception just before default exeception subscriber.
    // @see Drupal\Core\EventSubscriber\DefaultExceptionSubscriber::getSubscribedEvents()
    $events[KernelEvents::EXCEPTION][] = ['onException', -255];
    return $events;
  }

}

services.yml
services:
  example.exception_subscribtr:
    class: Drupal\example\EventSubscriber\ExceptionSubscriber
    arguments: ['@serializer', '%serializer.formats%']

    tags:
      - { name: event_subscriber }

Note that you need to have error reporting set to something other than verbose for this to work (unless you alter the code above).  This can either be controlled in the CMS here: /admin/config/development/logging or it may be overridden in your settings.php file.  For example, you might need to set
$config['system.logging']['error_level'] = 'hide';

Also note, that if your file_get_contents throws a fatal error, you will get the standard error for uncaught exceptions: "The website encountered an unexpected error. Please try again later."
Here's two ways you can trigger a 500 error for testing:
use Symfony\Component\HttpKernel\Exception\HttpException;

throw new HttpException(500);

or
/** @var \Drupal\Core\Template\TwigEnvironment $environment */
$environment = \Drupal::service('twig');
$environment->loadTemplate('this-template-does-not-exist.html.twig')->render([]);


Alternative to drupal_goto() function? I need to use an alternative function to replace drupal_goto().
The reason is that this function is causing me a problem to run cron.php. The code is:

    if(is_int($order_id)) {
$path = 'admin/commerce/orders/' . $order_id;
drupal_goto($path);
}
else {
  drupal_goto('admin/commerce/orders/');
}

The problem is not drupal_goto() but your usage of it in a node. THere is a long standing issue in Drupal core to deal with this but I honestly think doing this is just wrong.

Instead of putting it in a node, you should create a custom module and put it in a page callback. See What are the downsides of using 'custom' PHP code in blocks, nodes, views-args, etc? why it's a bad idea in general to use PHP in nodes, blocks and so on. You've seen one of those yourself, namely that it can be extremely hard to find out where the problematic code is actually coming from.

That said, the last comment in the linked issue points to a Field redirection module that is however currently limited to user/node references and links. And it's not dynamic as your code is. But again, for something like that you really should be creating a custom module.


Hide the display of a field conditionally I have the following scenario:

I have many users created from People->Add user

I have a content type (named Project) with the following fields:

--Leaders (Type: Entity Reference to Users)

--Editors  (Type: Entity Reference to Users)

--Price (Type:  Decimal)

--Duration (Type:  Integer)

I want the Price field to be hidden from logged in users belong to Editors field.

The difficult point here is that one User could be Editor to “Project 1” (a node from content type Project) and Leader to “Project 2 ”.

I tried some things with the following modules:  Rules, Field formatter conditions, Views Entity rules, but with no results…

Could you please advise me, how to hide the display of a field considering if the logged in user belongs to “Editors” field for each Project?

You can alter Add Project content form using hook_form_alter and check for #options in Editors field and if Current User ID exists in #options and then conditionally show/hide price field.

You can also check Conditional Fields module, to see if you get current logged in users details in it. Not sure if it does.

NOTE: You can get current logged in user details in global $user variable.


Display Today's Birthday in Block I have a  Content Type 'Teams' which have name as Title field, Image field and Date of birth field using Date module.

I want to display Today's birthday in block. I've tried using views but could not achieve it.

Is it possible to display in drupal. Please Help

Working with Drupal 7 and Date module, if you enable Date Views sub-module, you may create a Views block with a filter criteria based on your Date field. There, you will just have to enter a relative date (now) and filter your nodes with your birthday's dates. (i.e. Date field value is equal to : now).

Hope this helps.


How do I print a link only if it doesn't lead to access denied My nodes have fairly complex permissions set on them.  I want to display a small edit link on the teaser for a specific content type, only if the user has the permissions required to edit that specific node.  I already customise the display with the file node--newsletter.tpl.php

I tried:

<?php
$quick_links['quick-edit'] = array(
    'title' => 'Edit',
    'href' => 'node/' . $nid . '/edit');
?>
<div class="links quick-edit-links">
    <?php print theme('links', array('links' => $quick_links, 'class' => 'links inline')); ?>
</div>

But that prints out the edit link no matter what.  What's the correct way to do this.  Ideally I'd like to have a solution that is reasonably generic and works for practically any link (e.g. node/id/delete, or admin/)  So I can use it elsewhere, but a solution which only works for this specific case would be OK.

Now I feel silly, found an answer myself straight away, although it does only work for this specific example, I'd still be interested to see something more general.

<?php if (node_access('update', $node)):
    print l('edit', 'node/' . $nid . '/edit');
endif; ?>


How to refer to a custom field in a node template? For the basic page content type I added a custom boolean field called field_login_required.

In my node template node--page.html.twig I have

{{ title }}

    {% if content.field_login_required %}
        {% if user == 0 %}

You must be logged in to view this page Please click here to login

        {% else %}

{{ content.body }}

        {% endif %}
    {% else %}

{{ content.body }}

    {% endif %}

However content.field_login_required is null no matter whether the checkbox is checked or not. To test what was available I used

{{ dump(content|keys) }}

However the result of this is

array (size=1)
  0 => string 'body' (length=4)

field_login_required is omitted. Is there anyway to refer to a custom field in a node template?

The issue occurred because

{{ content.field_login_required }}

was used. Node should be used in place of content. The proper code is

{{ node.field_login_required.value }}


Drupal 8 - Check if language prefix is present in url or not Is there a way in the drupal 8 api to figure out if a language prefix is present in the url or not? Cause I need this information in order to display a custom language switcher if no prefix exists in the url. So for language detection I only have the prefix enabled.

Unfortunately this code is not working for me:

$languagecode = \Drupal::languageManager()->getCurrentLanguage()->getId();

Cause it always returns me a language. When no prefix is present in the url it returns me (as excepted) the fallback language.

Has someone a similar situation or can help me here?

There might be something more elegant, but doing it the dirty way is pretty simple:

$languagecode = \Drupal::languageManager()->getCurrentLanguage()->getId();
$parts = array_filter(explode('/', \Drupal::request()->getRequestUri()));

$has_prefix = count($parts) && $parts[0] == $languagecode;


Re-write output on different images on Views Slideshow Using this - tutorial

I have a views slideshow that rotates images with a fade effect.
I know you can re-write output to show images and a text field below but so far I can just add one text block - I want each image to have its own text!

Image Field Caption

Adds an extra text area for captions on image fields.
Similar to the alt and title text fields available with an image
field, the caption text area can be used to enter text or html
descriptions of an image.

Has views integration.


drupal commerce browsable catalog I am finding some troubles how Views works with taxonomy terms. I hope you can help me. :-)

I am building an e-commerce site with Drupal Commerce since it has all features I need for my project requirements but I don't know how I can list terms and nodes belong to concrete taxonomy on Views.

I have a product hierarchy taxonomy with all the site product categories. I use Taxonomy menu in order to show this taxonomy in a menu block allowing the user to select any term. A product display node only can be referenced to a sheet term on the taxonomy tree.

I want to use Views by listing as terms as nodes, if the user click on a non-sheet term on taxonomy menu, the view should show the subterms from clicked term. But in the other hand, if the user clicks in a sheet term then the view should show nodes referenced to the clicked term.

For instance,

Let's imagine I have the next taxonomy menu:

products

term1

term1.1
term1.2

node1
node2

term1.3

term2

node3
node4

If the user clicks on term1 term the view should list term1.1, term1.2 and term1.3 but if he/she clicks on term1.2 it should list node1 and node2.

How can I do this on Views? How can I list two different types of entities depending what term is clicked?

Thanks in advance!!

I doubt this is possible in views but you could try a combination of menu block and display suite modules, if you can't custom-code it.

You might also need a module which creates fly-out menus. Display suite is capable of pulling in various entities into your display, and there is a great set of tutorials available on Youtube that will show you how to achieve this.

This site is built with Drupal commerce, display suite and menu blocks; although I didn't add nodes to my menu blocks, it is possible.


How to run code on every page request - after modules are loaded? I want to write a module that redirects visitors to another page based on the geoip module.

There is hook_boot() which runs on all page requests, but before the modules are loaded. There is also hook_init() which isn't run on cached pages. I'd need something that runs after all modules are loaded - but before cached pages are served. Did I miss another hook in the documentation?

Note: Turning off the cache is not an option for performance reasons.

I'd need something that runs after all modules are loaded - but before cached pages are served.

You cannot, as loading all the modules is the last phase of Drupal bootstrap, while cached pages are served in the second bootstrap phase.

See the code used by drupal_bootstrap().

  switch ($current_phase) {
    case DRUPAL_BOOTSTRAP_CONFIGURATION:
      _drupal_bootstrap_configuration();
      break;

    case DRUPAL_BOOTSTRAP_PAGE_CACHE:
      _drupal_bootstrap_page_cache();
      break;

    case DRUPAL_BOOTSTRAP_DATABASE:
      _drupal_bootstrap_database();
      break;

    case DRUPAL_BOOTSTRAP_VARIABLES:
      _drupal_bootstrap_variables();
      break;

    case DRUPAL_BOOTSTRAP_SESSION:
      require_once DRUPAL_ROOT . '/' . variable_get('session_inc', 'includes/session.inc');
      drupal_session_initialize();
      break;

    case DRUPAL_BOOTSTRAP_PAGE_HEADER:
      _drupal_bootstrap_page_header();
      break;

    case DRUPAL_BOOTSTRAP_LANGUAGE:
      drupal_language_initialize();
      break;

    case DRUPAL_BOOTSTRAP_FULL:
      require_once DRUPAL_ROOT . '/includes/common.inc';
      _drupal_bootstrap_full();
      break;
  }

If you look at _drupal_bootstrap_page_cache(), you will notice that hook_boot() is eventually invoked before the page is served from the cached data, while hook_exit() is eventually invoked after the page is served from the cached data. Those hooks are invoked if the value of the Drupal variable "page_cache_invoke_hooks" is TRUE.

  if (variable_get('page_cache_invoke_hooks', TRUE)) {
    bootstrap_invoke_all('boot');
  }
  drupal_serve_page_from_cache($cache);
  // If the skipping of the bootstrap hooks is not enforced, call
  // hook_exit.
  if (variable_get('page_cache_invoke_hooks', TRUE)) {
    bootstrap_invoke_all('exit');
  }

Notice that in Drupal 8, hook_boot()has been removed and so does hook_exit(). This means Drupal 8 will never invoke those hooks.


Alter view data return? I am wondering if there is a way to do the following.

I need to alter view return data and either remove entries or keep entires based upon running some PHP.

Is there any easy way to do that? I was looking at the theme stuff, but that would mean I would nuke my pagination, is there anyway I could remove results but regenerate my pagination.

Sorry if this is confusing...

Edit: It's a little difficult to explain, but I am using Commerce. And I need to get a list of discounted products. But commerce only discounts products before they are displayed (ie there is no database I can join/where on to get discounted products). So I need to get all the products, then remove those that are not discounts.

You can use hook_views_data to alter view data like Commerce discounted products. As suggested by Clive, here is the patch which is implementing related feature:

Allow Views to sort / filter based on pre-calculated prices

Other hooks to consider which can allow to alter the views data are:

hook_views_query_alter,
hook_views_pre_render.


Sub menu not displaying in Bartik Theme I am using Drupal 7.9.
I need to display main menu with sub-menu.

print theme('links__system_main_menu', array(
'links' => $main_menu,
'attributes' => array(
'id' => '',
'class' => array('menu'),),
'heading' => array(
'text' => t('Main menu'),
'level' => 'h2',
'class' => array('element-invisible'),
),)
);

That is the code I have used, but it does not show sub-menu items.

Then i have also tried following code :

if ($main_menu){
  $pid = variable_get('menu_main_links_source', 'main-menu');
  $tree = menu_tree($pid);
  $tree = str_replace(' class="menu"', '', $tree);
  $main_menu = drupal_render($tree);
  }
else {
  $main_menu = FALSE;
}
if ($main_menu): print $main_menu;
endif;

Even it does not display sub-menu.

Does anybody know a solution?

The main menu in Bartik only displays the first level.  Since it's hardcoded in page.tpl.php there's nothing you can do about it.

Here's how to get the menu to work properly:

In your theme settings (admin/appearance/settings/barti) disable "Main menu"
Go to admin/structure/block and add the "Main Menu" block to the header region (or wherever you want it)

Alternatively, you can also check out the excellent Menu Block module, which generates extra customizable blocks (1st level, 2nd level, etc) for each menu.


Unable to load autoload.php I've looked through all similar issues reported but none of them solves my problem. I always install drush with composer and installing 6.4.0 is working just fine, but when I install dev-master then I get the error

Unable to load autoload.php. Drush now requires Composer in order to install its dependencies and autoload classes. Please see README.md

Composer is at the latest version.

When I go to ~/.composer I never get a ./vendor/ directory as suggested by answers to other questions.

My environment is Ubuntu 14.04 and I'm using PHP 5.5 - any idea what else could be wrong?

you might try running "composer install" from inside your drush directory.


TrustedResponseRedirect failing - how to prevent cache metadata? I am getting the following when trying to redirect to an external site from my controller function defined in my routing file:

return new TrustedRedirectResponse($my_ext_url);

  LogicException: The controller result claims to be providing relevant cache metadata, but leaked metadata was detected. Please ensure you are not rendering content too early. Returned object class: Drupal\Core\Routing\TrustedRedirectResponse. in Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext() (line 159 of core\lib\Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber.php).

This is clearly related to cache metadata - but how do i switch this off for a trusted redirect?

Edit: There is currently no constructor on the controller and therefore no injection going on.
Routing looks like (obv with correct indents :):

tocyn_payment.paypal_checkout:
path: 'test/{order_id}'
defaults:
_controller: 'Drupal\my_module\Controller\MyController::handle'
_title: 'Test Tite'
requirements:
_permission: 'access content'

Thanks in advance

Mathew

You mentioned the URL generator, which is one of the two ways this happens.

In short, you need to do something like my patch in this issue: https://www.drupal.org/node/2630808

Pass TRUE to toString(), then you get a different object back that you need to add as a cacheable dependency. You can do that with such GeneratedUrl objects, entity and config objects and you should do that whenever your response depends on them.


How does Drupal 7 page/block cache work? I have a few questions about drupal 7 page/block cache.

If I enable the cache and set the expiration time for 15min., and the content in page A is updated within next 10min., will the cached version be updated? or will it only update every 15min.?

Does same apply to blocks?

From your question I get that you are trying to set the caching from the performance page admin/config/development/performance.

Cache pages for anonymous users only works for anonymous users, and the page markup is stored in database (to reduce the number of queries). And you can check the HTTP Header X-Drupal-Cache to see if this cache is HIT.

Cache blocks (if Page caching is disabled) works for anonymous and logged-in users. And again, the whole block markup is stored in database for the same reason.

Minimum cache lifetime is the amount of time before the Page cache gets cleared (the cache is cleared on cron run).

Expiration of cached pages works only if page caching is enabled and is only applied to external caching mechanisms (like the browser cache)


How can i load a specific CSS file for a specific View? What's the best way (best practice) to load a specific stylesheet for specific View. i managed to do it like this, in the template.php file but i'm thinking this is pretty awkward and there is a better way.

if($variables['theme_hook_suggestions'][0] == 'page__dvd_products') {

drupal_add_css(path_to_theme(). '/css/dvd-product-display-view.css', array('group'=>CSS_THEME));
} else {

drupal_add_css(path_to_theme(). '/css/dvd-product-display.css', array('group'=>CSS_THEME));
}

what is a better way to do this? i'm still kind of new at this. any feedback would be greatly appreciated. thanks

Looks like you need Code per Views Display module.


Setting a field readonly rather than invisible from hook_field_access()? I have a field that should not be visible when editing, in certain cases (depending on node state and user).
It works fine using hook_field_access():

function mymodule_field_access($op, $field, $entity_type, $entity, $account) {
  if ( ...conditions on $entity_type, $entity->type, $field['field_name'], $op...) {
    // → $op=='edit' && isset($entity->nid) so only when modifying existing content
    return FALSE;
  }
  return TRUE;
}

As said it works fine, and the field is not displayed at all when access is not granted.

But in some particular conditions I would like to let the field visible but readonly (grey-ed, or anything preventing to modify it) rather than hiding it.

I tried to return TRUE and before to set according attributes to the field, but until now I failed to make it works as expected. What I tested:

$tmp = mode_load($entity->nid);
$tmp->my_field['#attributes'] = array('readonly' => 'readonly'); // also tried to use 'disabled')
node_save($tmp);

I also tried:

$tmp->my_field['#disabled'] = true;

Thanks for any help.

Regards.

Try something like that :

Replace FORM_ID with the real form ID.

function MYMODULE_form_FORM_ID_alter(&$form, &$form_state) {

  if(!user_access(ADMIN_USER)){
      $form['your_field_name']['#disabled'] = TRUE;
    }

    $form['your_field_name']['#access'] = TRUE;
}


Compare two same fields with time difference in Views, using node revisions I'm trying to build a view containing two columns: first is the actual value of a (integer) field, second is the same field with its old value from two weeks before, using the revision. I suppose I would need a relationship for the second one but can't figure out how do to so.

The great Diff module help comparing one node at a time, but I would need to compare a list of nodes, reason why I want to do it in a view.

Any help would be more than welcome!

This is a bit of a hackish solution.

What you need to do it create a field which would be unique per node on all the revisions. You could use the Computed Field instead of the normal field to crate this field and use the code below to computed the field

if (!$entity->nid)
{
 node_save($entity);
}

$entity_field[0]['value'] = $entity->nid;

This would set the value of the computed field to the nid of the node so that you dont have to bother about setting a unique value.

Now in the views create a view of the type content revision. (This would be done by selecting content revision from the dropdown near Show

Add the fields for which you want the revision data. Use the one which says  (historical data) at the end of it.

Now add the contextual filter with the computed field we created earlier. make sure the select the one with (historical data) at the end of it.

In the filters you can choose Content revision: Updated date and select the date range you want. you can also provide relative values such as -7 days to get the all the values before 7 days.

The computed field was used because I was not able to get the nid of the revisions. If any one has a work around on that please do make the required changes.


Add block to form (before submit button) I'm having problems placing a block in my form. This is what I have now:

I have a register form and a fb button block. I say the block must be visible only when page is equal to user register page.

But the problem is that I don't want to have the form and underneath the block. I would like to add the block before the submit button of my form. How can I do this?

You can do something like this:

load the block content manually
control the order of fields withj #weight option

example:

function my_form()
{
  $block = block_load(MODULENAME, BLOCKDELTA);
  $block = _block_render_blocks(array($block));
  $block_build = _block_get_renderable_array($block);

  $form['FIELD_1'] = array(
    ...
    ...
    '#weight' => 1
  );

  $form['FIELD_2'] = array(
    ...
    ...
    '#weight' => 2
  );

  $form['FIELD_3'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
    '#markup' => render($block_build),
    '#weight' => 3
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'OK',
    '#weight' => 4
  );

  return $form;
}

if those forms are from other modules you can alter them with hook_form_alter(&$form, &$form_state, $form_id) function.

example:

function MYMODULE_OR_THEME_form_alter(&$form, &$form_state, $form_id) {
  // dpm($form_id);
  if ('user_register_form' == $form_id) {
    $form['actions']['#weight'] = 50;

    $block = block_load(MODULENAME, BLOCKDELTA);
    $block = _block_render_blocks(array($block));
    $block_build = _block_get_renderable_array($block);

    $form['fb_field'] = array(
      '#prefix' => '
',
      '#suffix' => '
',
      '#markup' => render($block_build),
      '#weight' => 49
    );
  }
}


How do I manually update without using Drush nor Composer? Is it possible to upgrade Drupal from 8.3.7 to 8.4 without Drush or Composer?

Even though I have used composer I am not comfortable with using terminal/console command lines operations. So far used composer to install and remove modules. That's about it.

Looked at manual update options. There are no instructions yet for this method.
https://www.drupal.org/docs/8/update/update-core-manually-via-gui-option-1

This is what I am planning on doing.

Download and extract Drupal 8.4 zip.

Backup database  through PHPMyAdmin and website before
proceeding.
Put site in maintenance mode by going to
configuration -> maintenance mode
Remove ‘core’ and ‘vendor’   directory project dir.
Upload the core directory from the Drupal 8.4 version
downloaded.
Upload .htaccess,composer.lock and composer.json files from the downloaded Drupal to project.
Upload vendor directory from the download
Drupal version to your project.
Go to site.com/update

Am I missing something? Or should I figure out the composer route?

The official update method is described in UPDATE.txt:

http://cgit.drupalcode.org/drupal/tree/core/UPDATE.txt?h=8.4.x

This is basically what you've described in the question. You don't need composer to update core.

If you want to switch your existing installation to composer a risk free way would be to start a new project, see Updating core with Composer doesn't work.


How to programmatically add/modify a rule? Hello,
I have the Rules module. I tried to programmatically create or modify a rule but it doesn't work. What I tried so far : I created the
MY_MODULE.rules_defaults.inc file and wrote this code :

function MY_MODULE_default_rules_configuration() {
$configs = array();
$rule = { "rules_name" : {
  "LABEL" : "rules ",
  "PLUGIN" : "reaction rule",
  "OWNER" : "rules",
  "REQUIRES" : [ "rules", "mimemail", "uc_cart" ],
  "ON" : { "uc_checkout_complete" : [] },
  "DO" : [
    { "component_rules_commerce_order_status_pending" : { "order" : [ "site:current-cart-order" ] } },
    { "mimemail" : {
        "key" : "[site:name]",
        "to" : "mail@mail.com",
        "subject" : "[site:name]",
        "body" : "Random text",
        "language" : [ "" ]
      }
    }
  ]
}
}
 $configs['rules_name'] = rules_import($rule);
  return $configs;
}

Yet it doesn't work.
I also tried with MY_MODULE_default_rules_configuration_alter() but to no avail.

You have to create new Rule via the provided APIs and HOOKs from the Rules module.

From creating rules through the UI you have seen their configuration attributes, such as

Rules Event
Rules Condition
Rules Action etc.

Now you have all the useful HOOKs to create new ones. If you want to add a new Rules event to your System then go for hook_rules_event_info()

/**
* Implementation of hook_rules_event_info().
* @ingroup rules
*/
function your_module_rules_event_info() {
  return array(
    'your_module_custom_event' => array(
      'label' => t('A custom event happened in your application'),
      'module' => 'your_module',
      'arguments' => array(
        'param1' => array('type' => 'user', 'label' => t('The user object')),
      ),
    ),
  );
}

You can invoke this event also from custom code in your module as

rules_invoke_event('your_module_custom_event', $param1);

If you want to add some custom conditions to a pre defined rule then use
hook_rules_condition_info()

/**
 * Implements hook_rules_condition_info().
 * Checks if the given user is male or not.
 */
function your_module_rules_condition_info() {
  return array(
    'user_is_a_male' => array(
      'group' => t('test'),
      'label' => t('If user is male'),
      'parameter' => array(
        'user' => array(
          'type' => 'user',
          'label' => t('Validate registered users if male'),
        )
      ),
    ),
  );
}
function user_is_a_male($user) {
  // your custom condition to return boolean TRUE or FALSE
}

To alter pre-defined Rules you might use hook_rules_component_alter or hook_default_rules_configuration_alter but again depending on needs these will vary. Go through via the link above and you will find all.

FYI, you can export Rules via Features module with your custom HOOKs as well.
And these custom HOOK's should be placed on a file as "your_module.rules.inc" so Rules module will include these automatically.


Is there a way to add new custom selection rules for panels? I find the pre-supplied list of selection rules to create panel variants to be quite lacking.  For instance, if I am using panels to override taxonomy term pages, and I have some arbitrary boolean field on each term (say, "Is Blog?"), then I would like to create a panel variant based on this field being equal to TRUE.

However there is no such flexibility when using Selection Rules to create variants.  Am I alone in thinking that this missing functionality greatly diminishes the power of Panels and panel variants?

How would a site builder, or developer, go about creating new "custom" selection rules?

We initially did it the way that you did. However, after a site security audit, we were told that we should not include PHP in that way (even though it's there and available). The solution is to create a custom rule using ctools access plugins. This page has an excellent breakdown of how to do it. We now have about 5 or so custom ones we use through custom modules.


How to inspected the file system to investigate if the image was uploaded After I upload an image, I see blank image. How can I inspect the file system to investigate if the image was uploaded or not?

Thanks,
M

If your file is not appearing after an upload via the field api then you might want to check if your files directory is writable by apache. Typically this would be sites/default/files.

NOTE: sites/default/files should ONLY be writable by apache and nothing else.


How to allow users to cancel their own account? I gave the permission cancel own user account to authenticated users.

Now they can see a Cancel account button on their profile edit.

But when they click on that button, a confirmation form opens. That is fine.

On the confirmation form, when they click on the Cancel account, they are redirected to their profile page with a message

A confirmation request to cancel your account has been sent to your email address.

I want to change this functionality. When they click on cancel account, they should not receive a confirmation cancellation email. Their account should be deleted immediately and they should be gets logged out.

I tried with this code but it is not working.

$form['user_cancel_confirm']['#default_value'] = FALSE;

Is this possible? How can I do this?

Seems the Cancel Account Separate Form module does exactly what you want. It provides a form that finally calls user_cancel with the current user's UID as parameter.

  This is a very simple, lightweight module that provides cancel user
  account separate form and adds it to user edit form by default if user
  has cancel account permissions and edits his own account.


Is it possible to allow duplicate usernames ? I'm working on a Community Website and 99% of the time a new user has an unique username. But for my requirement, it is required to allow duplicate usernames.

Is there a way to change drupal default behavior from unique username+email+pass to unique email+pass?

There is no setting or existing module that will do this for you.  I do not think it is a good idea to let two users share the same username, because there is so much in Drupal that depends on usernames being unique, and this will break if you make two usernames identical.

You do not tell us why you want to have this feature.  However, if you are content with letting users authenticate using their email address (which is guaranteed to be unique), rather than their username, the Email registration module may solve your problem.

However, the Email registration module does not let the user pick his or her own username, but generates an unique username based upon the email address.  I want my users to pick their own username, so I use a variant of Email registration that does this.  It is named RealnameReg.  It is a sandbox, but since it is based on Email registration it is stable. I am using it myself on several production sites.


How to rearrange user register form and still pass validation I've implemented a hook_form_alter to change order of fields on user registration form. i've moved mail and username fields inside a fieldset. on submit, drupal is returning an error of undefined mail and account index.
How should i handle this? do i create a submit function that defines $form['mail'] = $form['fieldset']['mail']?
Here's my code:
/**
 * Change the elements from registration form
 *
 * @return outputted form
 * @author
 **/

function userreg_form_alter(&$form, &$form_state, $form_id){
    if ($form_id == 'user_register_form'){

        if (current_path() == 'supplier/register'){
            unset($form['profile_main']);

            //move the whole form inside suppliers tab
            $supinfo = $form['account'];
            unset($form['account']);

            $form['profile_supplier']['account'] = $supinfo;

            //add our custom form_validate form to handle what we just changed?

            array_unshift($form['#submit'], 'userreg_form_submit');

        }
    }
}

function userreg_form_submit($form_id, &$form_state){

    $form_state['values']['mail'] = $form_state['profile_supplier']['mail'];

}

The error i'm getting is:

Notice: Undefined index: mail in user_account_form_validate() (line
1264 of /var/www/funa/d/modules/user/user.module).
Notice: Undefined index: account in user_account_form_validate() (line 1265 of /var/www/funa/d/modules/user/user.module).
Recoverable fatal error: Argument 2 passed to drupal_array_set_nested_value() must be of the type array, null given,
called in /var/www/funa/d/includes/form.inc on line 2602 and defined
in drupal_array_set_nested_value() (line 6695 of
/var/www/funa/d/includes/common.inc).

I would try defining the name of the field manually like so. This should overwrite the default naming of the variable in the values/input array in the $form_state.

$form['profile_supplier']['account']['#name'] = 'account';


Drupal 7 - Teaser trim ends after first  tag. How can I make it continue? I want to my teaser to trim to 400 characters, but the trim stops after the first <p> tag is closed.  Is there a way to override this behavior and make the teaser trim to the first 400 characters?

I have edited the teasers 'manage display' option and set it 400, then edited and saved any old content, but the teaser is still being cut off after the first <p> tag ends.

I have considered adding a body summary but it does not allow any formatting in the box, which I require. Any help would be greatly appreciated.

This solution works if you are using Views to display your content (if you aren't, it's up to you which is preferable in your case between using Views and getting its many other advantages, or installing Smart Trim and keeping things simple. Views is complicated but learning it is time well invested).

Choose "Summary or trimmed" as the field's "Formatter"
Set the "Trim length" value much too high - big enough that it will always cover the whole of all the elements you'll want trimmed (e.g. 1500)
Under "Rewrite settings", select "Trim this field to a maximum length". Tick "Field can contain HTML", keep "Trim only on a word boundary" ticked, and enter the real character count in "Maximum length" (e.g. 200). It's a good idea to keep "Add an ellipsis" ticked to, so incomplete sentances don't look like a mistake.

So in our example, Drupal will choose the summary if there is one, or the body text if there isn't. It'll count 1500 characters, and trims cutting out any incomplete HTML elements. Unless your article contains an excessively long insane paragraph from hell, this will be at least 200 characters. Then Views' filter kicks in, trims it to 200 characters by the nearest word. This gives the real desired length, without losing the option of showing a trimmed version of the summary if there is one.

With "summary or trimmed" or "trimmed", the trimming is based on whole HTML elements so that long paragraphs can be cut out entirely. I've found that sometimes, if there's one long introductory paragraph, the trimmed field would show up completely empty - this solves that.


Rewrite a text field in "Manage display" of content type This feels like it should be simple to do, but I can't work it out.

If I have a text field, how do I rewrite the output of the field on the "Manage display" tab of the content type? For example, I might want to add units, or convert a product ID into a link to an external website.

I know how to do this stuff in Views, but it would seem to make sense to be able to do it via the "Manage Display" tab for a content type. Am I missing something?

You have a couple of choice based on your needs:

Overriding the template file (twig) of the specific field
Using form_hook_alter
For complex and clean solution I suggest you to use a custom widget for your field type.


drupal_static and cache_set combo , is this overkill? I have been using this snippet lately here and there, but after re-thinking , it seems like it could be a good example of over-engineered code:

<?php
function my_module_function() {
  $my_data = &drupal_static(__FUNCTION__);
   if (!isset($my_data)) {
    if ($cache = cache_get('my_module_data')) {
      $my_data = $cache->data;
    }
    else {
      // Do your expensive calculations here, and populate $my_data
      // with the correct stuff..
      cache_set('my_module_data', $my_data, 'cache');
    }
  }
  return $my_data;
}
?>

Is this truly an optimal way to cache things? I am not clear on the low-ends of it all but it seems the drupal_static call is overhead since the static call would get only called once before the data would be cached. Maybe I am seeing it wrong, and rather the cached variable would be set static for the whole request, and static access is faster than cache access?

I am also not clear if the cache is global for all users or on a  per user basis. I would imagine the cache is global, but please correct me if I am wrong!.

I don't see this a overkill.

drupal_static() caches results over the lifetime of a single request.  It is typically used for things that may be needed several times during page generation, but will (likely) not change.  For example, if a node is loaded, it gets saved in memory in case multiple functions need it.

cache_set() / cache_get() caches things in the database (or another storage backend with the proper module), so the data persists (up to the TTL) between page requests.  This gets used for things that change infrequently, and is global for all requests.  As far as I can remember, the normal implementation always goes out to the cache backend and doesn't store results in memory with drupal_static() or static.

Given the overhead, I would be judicious as to whether caching really improves things.


Can't find html.tpl.php I'm editing a template of the Seven theme in Drupal 7. I want to change something in the html.tpl.php file, but I can't find where it is located.

Where is it the html.tpl.php file used by the Seven theme? Does the Seven theme have a html.tpl.php file?

There is none.  To override it, copy modules/system/html.tpl.php into your Seven subtheme and change that.  Remember to clear cache to make your changes visible.

(Don't hack Seven directly, next core update will overwrite your changes.)


How to change fieldset which is made via #theme_wrapper Drupal 7 I want to change fieldset settings on some form, I want to make it collapsed by default. The problem is this fieldset isn't made via usually form API. Its made via #theme_wrappers param. The question is how to alter #theme_wrappers output so it affect only certain form. Thanks!.

[#theme_wrappers] => Array(
  [0] => fieldset
)

I had to do this today on a Backdrop CMS site, but the problem and solution are exactly the same:

The problem is that most theme wrappers only add markup around the outside of something else. But a fieldset also has a process function, and process functions are not automatically added for #theme_wrappers.

The process function needs to run on the fieldset in order to take the #collapsible and #collapsed settings you add in the Form API to turn into the addition of the necessary CSS classes and JS library.

That means that not only do you need to set the values for #collapsible and #collapsed, but you also need to add the #process function. See below for an example.

/**
 * Implementation of hook_form_BASE_FORM_alter().
 * - Limits access to legacy fields.
 * - Collapses legacy fieldset.
 */
function mymodule_form_node_form_alter(&$form, &$form_state) {
  if (isset($form['field_images_inline'])) {
    $form['field_images_inline']['#access'] = user_access('administer nodes');

    // Add the collapsible and collapsed attributes.
    $lang = $form['langcode']['#value'];
    $form['field_images_inline'][$lang]['#collapsible'] = TRUE;
    $form['field_images_inline'][$lang]['#collapsed'] = TRUE;

    // Add the fieldset process function.
    $form['field_images_inline'][$lang]['#process'] = array('form_process_fieldset');
  }
}


Title field input not appearing when creating content type by module I have this problem, I'm creating a content type by creating a module, using the example 'node_example' of examples project as a code template. The thing is that I get it work, I create the content type successfully but when I create a new node of that content type, all fields appear but the title. I'm a little lost. I put by myself the propperty 'has_title' to true on hook_node_info() but it stays the same. Cleared drupal caches several times, removed previous nodes, nothing. Any idea? Thanks.

(Maybe I don't follow all the standards, I'm quite a begginer and I try to follow them as possible) Module name: ct_conversacion. Content type: conversacion.

-------------edit:

Ok, it was tough but I found the solution. The function 'ct_conversacion_form' that I wrote below should be 'conversacion_form' (the content type name preceding).

My code:

  /**
   * Implements hook_node_info().
   */

      function ct_conversacion_node_info() {

        return array(
          'conversacion' => array(
        'name' => t('Conversacion'),
        'base' => 'conversacion',
        'description' => t('Es una conversacion.'),
        'has_title' => TRUE,
        'title_label' => t('Title'),
        'locked' => TRUE,
      ),
    );
  }

  /**
   * Implement hook_form().
   */
  function ct_conversacion_form($node, $form_state) {
    return node_content_form($node, $form_state);
  }

  /**
   * Implements hook_node_type_insert().
   */

  function ct_conversacion_node_type_insert($content_type) {
    if ($content_type->type == 'conversacion') {

      $body_instance = node_add_body_field($content_type, t('Mi descripcion'));

      field_update_instance($body_instance);

      foreach (_conversacion_installed_fields() as $field) {
        field_create_field($field);
      }

      foreach (_conversacion_installed_instances() as $instance) {
        $instance['entity_type'] = 'node';
        $instance['bundle'] = 'conversacion';
        field_create_instance($instance);
      }
    }
  }

  /**
   * Define the fields for our content type.
   *
   */
  function _conversacion_installed_fields() { // Cambiar *****
    return array(
      'conversacion_field2' => array(
        'field_name' => 'conversacion_field2',
        'cardinality' => 3,
        'type'        => 'text',
        'settings'    => array(
          'max_length' => 60,
        ),
      ),
    );
  }

  /**
   * Define the field instances for our content type.
   */

  function _conversacion_installed_instances() {
    return array(
      'conversacion_field2' => array(
        'field_name' => 'conversacion_field2',
        'label'       => t('Field 2 de Conversacion.'),
        'widget'      => array(
          'type'    => 'text_textfield',
        ),
      ),
    );
  }

the error is obviously because you use a wrong base
change it to 'ct_conversacion'
see https://api.drupal.org/api/drupal/modules%21node%21node.module/function/node_type_save/7
base: A string that indicates the base string for hook functions. For example, 'node_content' is the value used by the UI when creating a new node type.


Reading a field collection I am trying to read a field collection and build an array in PHP.

The array I want to build goes like this:(it's in JS notation but you can easily imagine the equivalent in PHP)

highlights = [
{highlightTitle:A sample test title,
 highlightImage: a sample img url,
 highlightBody: a sample text body},
{highlightTitle:A sample test title,
 highlightImage: a sample img url,
 highlightBody: a sample text body}
]

As you can see it is just an array with objects inside, where each object represents a field collection entry. That field collection entry has 3 fields obviously, highlightTitle,highlightImage & highlightBody.

Now I want to read that field collection and build the array I described above.

  The thing I care about is best practises. What is the best possible
  way to do this?

Currently I use the following code dumped in <?php ?> brackets on the top of my layout's tpl files:
(I use Omega 4, and I have different layouts for different content types)

This is the code I use now:

  $highlightsArr; //this is the result array
  $highlightsCounter = 0;
  $highlights = field_get_items('node', $node, 'field_highlights');

  foreach ($highlights as $item) {

    $fc = field_collection_field_get_entity($item);
    $highlightSnippet = $fc->field_highlight_snippet["und"][0]["value"];

    $arr = $fc->field_highlight_snippet["und"][$i]["value"];
    $innerArray = entity_load('field_collection_item', array($arr));

    $innerCounter = 0;
    foreach ($innerArray as $item) {

      $highlightsArr[$innerCounter]["sectionItemTitle"] = $item->field_highlights_title["und"][0]["value"];
      $highlightsArr[$innerCounter]["highlightsImage"] = file_create_url($item->field_highlights_image["und"][0]["uri"]);
      $highlightsArr[$innerCounter]["sectionItemPrice"] = $item->field_highlights_body["und"][0]["value"];

      $innerCounter++;
    }
  }

The issue with the above code:

The code above returns undefined variables/indexes on things that are obviously defined. When I first create a content type and want to view it's node, it returns errors. But as soon as I refresh the page the errors go away which seems rather strange to me.

In any case I would like to know best practises for doing this kind of stuff.
Unfortunately I come from a strictly JS background (I'm a front-end dev), so Drupal and PHP is something new for me.

Many thanks in advance.

The code above returns undefined variables/indexes on things that are obviously defined.

As long as your PHP installation is not buggy, that's not possible. If the variable is defined, PHP won't tell you it isn't defined.

  as soon as I refresh the page the errors go away which seems rather strange to me.

It's not strange - messages are held in the session so if you're doing something that invokes them in a template file (when the messages for the current page have already been prepared), you should expect to see this delayed reaction. Logic should never been in a template file, always a preprocess or process function.

Best practice is really a matter of opinion, but these are the two standard options for accessing fields on any entity type, Field Collection included.

field_get_items()
EntityMetadataWrapper

Both alleviate the need to access the arrays directly, thereby decreasing the possibility of developer error.


theming a rendered entity in a view header I reference a node into a view header (rendered entity). I need to do some changes in the output of this referenced entity.

Does anyone know the filename for the needed template?

When an entity is rendered an entity view mode is picked. Each entity view mode can have different dispaly configuration. So, you may add a new View mode to your entity  and set up the appropiate display config in the entity display page.

Then, in your view, seleect this view mode when configuring the rendered entity.

If you need further output customization you can define your own template for your View mode.

To add anew view mode you can check this question: How to add additional display(view mode) for node?

To set up a template file for your custom VIewmod you can check this question: How to provide template for particular view mode?

You can also use the full view mode, but this affect all rendered entities of this type.


Build out a complete main nav menu for a module - not just adding one menu link I've been finding a lot of info about how to add a menu link as part of a module.  That works fine using the route/controller & links.menu.yml file.
But I am now trying to figure out how to add a complete main menu for my module (my module is a default data & structure module).
My goal is to have x level-1 menu items and each one of those will have varying numbers of sub-menus.
Any hints or references to guides/tutorials?

I've decided to go with the default_content technique in which it is possible to save off the menu items to a 'custom_module' then reload them into a new instance.


Change print $node_url To a Link Fields Value Hello i would like to change the destination of a url in a node.tpl (in a view) from this-

<a href="<?php print $node_url; ?>">

to something like this-

where the field viewslink is a link field in the node itself.

I know i could do it if the view used fields but it doesnt its using a content teaser.

Anyone got any advice?

Thanks

sites/all/themes/other_sub/templates/nodes/node--view--portfolio-block.tpl.php

<li class="<?php print str_replace(',-', ' ', str_replace(' ', '-',strip_tags(render($content['field_portfolio_category'])))); ?>">
    <?php print render($content['field_portfolio_image']); ?>

        <a href="<?php print render($content['field_viewslink']); ?>">

<?php print $title; ?>

<?php print strtolower(render($content['field_portfolio_category'])); ?>

If it is a field with in the node then you should be able to use the $node object.

The object contains all the fields associated with the node.

if you are not sure of the name of the field then you could try to print the object using the print_r function.

You could also try try the $content object which contains the fields as well.

print render($content['field_viewslink']);

That should render the variable.


Try this:

use Drupal\Component\Render\FormattableMarkup;

$src = $item->value;
$image = new FormattableMarkup('<img src=":src"/>', [':src' => $src]);
$elements[$delta] = [
  '#markup' => $image,
];


Filter the Node Locations view in the navigation menu I'm using Gmap Views to show where each Eastern Star Chapter in Maine is, both extant and historical. The automatic Node Locations map in the Navigation menu is displaying them correctly so far. What I would like to do is filter this so only nodes of type "chapter" are displayed, and preferably only ones marked as "active", although I won't generally have an exact geocode for the inactive ones. Thanks!

(This is very similar to a question I asked before, but it didn't get much input, so I'm asking it a different way this time.)

Set up a taxonomy vocabulary (eg Status) with the terms 'active' 'closed' etc, and attach a term reference to the node.

Then filter your view on the term. Have a look at Filter map to show single taxonomy or single content type.


How to save datetime field value in config? I have a custom module (mymodule) with a settings form. This form contains a datetime field (mydate) which I want to save in my modules config.

When I try to save this form I get an exception:

  Drupal\Core\Config\UnsupportedDataTypeConfigException: Invalid data type for config element mymodule.settings:mydate in Drupal\Core\Config\StorableConfigBase->validateValue() (line 160 of core/lib/Drupal/Core/Config/StorableConfigBase.php)

The form field:

$form['mydate'] = array(
  '#type' => 'datetime',
  '#title' => t('My date'),
  '#default_value' => $config->get('mydate')
)

The form submission handler where the error occures:

$config->set('mydate', $form_state->getValue('mydate));

I guess I have to set up my config schema to set up the "right type". Currently I have this one but it does not solve my issue:

mymodule.settings:
  type: config_object
  label: 'fancy module settings'
  mapping:
    mydate:
      type: datetime
      label: 'My date'

Any idea what I'm doing wrong or what is missing?

PS: using Drupal 8.2

There is no schema for data type called datetime.

Easiest solution is to store the date as the timestamp string.

Converting a drupal datetime into a timestamp:
The datetime form element holds an array value that contains three keys: date, time, object.
The object holds an instance of the [\Drupal\Component\Datetime\DateTimePlus][1] class. It has a _toString method which means it can be converted to string via normal casting (i.e. (string) $value).

Setting a default value on a datetime field:
Too do that you will need to create a new [\Drupal\Component\Datetime\DateTimePlus][1] object and set it as the value of $element['#default_value']


Webforms Ajax File Upload Issue with IE7 and IE8 The file upload fields in my webform work everywhere except IE7 and IE8. When I click the upload button I get a js alert that says the following

"An error has occurred while attempting to process /file/ajax/submitted/nameofmyuploadfield/form-reallylongrandomstring:"

I've tried several different versions of jQuery through the jQuery Update module but to no avail. I even tried the webform module right out of the box on a new drupal instance and got the same error. I'm having a hard time believing webform file uploads were never meant to work on IE7 and IE8 but that seems to be the reality of my situation. Please share some wisdom about overcoming this issue.

here is an example to the out-of-the-box webform file upload not working in IE7 and IE8
http://bonkmas.com/vids/node/4

I've managed to solve this weird issue, the root cause was relatively easy to find once you have the correct tools to debug. Which is an issue in IE7/8. My issue was related to Adaptive Image Styles, and it now works with that disabled.

The answer here: IE8 Debugging (stack overflow) helps equip us with a bit better debugging capability in IE8.

Set a watch on e, and check to see what the error throws to see if that gives any hints in where to look next.

Now the problem I specifically encountered comes from /misc/ajax.js so open up this file and make the following changes starting line 239:

//try {
    if (ajax.form) {
      // If setClick is set, we must set this to ensure that the button's
      // value is passed.
      if (ajax.setClick) {
        // Mark the clicked button. 'form.clk' is a special variable for
        // ajaxSubmit that tells the system which element got clicked to
        // trigger the submit. Without it there would be no 'op' or
        // equivalent.
        element.form.clk = element;
     // }

      ajax.form.ajaxSubmit(ajax.options);
    }
    else {
      ajax.beforeSerialize(ajax.element, ajax.options);
      $.ajax(ajax.options);
    }
  }
  //catch (e) {
    // Unset the ajax.ajaxing flag here because it won't be unset during
    // the complete response.

    ajax.ajaxing = false;

    alert("An error occurred while attempting to process " + ajax.options.url + ": " + e.message);
  //}

This removes the try/catch since they were obscuring where the error was coming from in the IE inspector. Now set breakpoints on each one of those variables and set a watch on ajax. Hit upload on your page and continue through the errors checking each variables, then as it hits an error the Console should take you to which ever file is throwing the error.

Hope this helps you.


Adding a cache tag to an entity view display doesn't do anything? I wrote a module that implements hook_entity_view_display_alter(). I modify the display settings of one of the fields depending on some configuration setting of my module.

/**
 * Implements hook_entity_view_display_alter().
 */
function ps_events_entity_view_display_alter(EntityViewDisplayInterface $display, array $context) {
  // Change the date formats of the date field on the full page display based
  // on configured settings.
  if ($context['entity_type'] === 'node' && $context['bundle'] === 'ps_events' && $context['view_mode'] === 'ps_full_content_no_lb') {
    $eventsSettings = \Drupal::config('ps_events.settings');
    $dateComponent = $display->getComponent('field_ps_events_date');
    if ($dateComponent) {
      $dateComponent['settings']['date_format'] = $eventsSettings->get('detail_page_date_format_day_and_time');
      $display->setComponent('field_ps_events_date', $dateComponent);
      $display->addCacheTags(['config:ps_events.settings']);
    }
  }
}

However, the cache tag I add doesn't seem to have any effect. When I inspect the cache_render table and look at the entry for this entity view display, my cache tag is not present. Changing the settings of my module does not clear the cache for this entity view display.

As a workaround, I also implement hook_entity_view_alter(), which operates on the complete render array of the entity view display. I add the cache tag here and it works.

This seems like either a bug in core, or maybe I misunderstand the purpose of cache tags on the EntityViewDisplay object?

For that to work, core would have to use getCacheTags() from that config entity, which it doesn't do.

I'm not sure if that should be changed, core currently does not add the cache tags of that entity on purpose, instead it it invalidates the generic {$entity_type}_ cache tag on saving such an entity in \Drupal\Core\Entity\Entity\EntityViewDisplay::postSave(). Consdering that this changes only very infrequently once a site is live, this is more performant as there are fewer cache tags to check on each request.


How to change Drupal's default "Unable to send e-mail." message? I wanted to override/change the text message that appears while sending Drupal mail.

This is the text "Unable to send e-mail. Please contact the site administrator if the problem persists."

What are the ways to change this message into my own custom message ?

You can use String Overrides modules for overriding any string that passed through t().
Here are some details about this module from its project page:

Provides a quick and easy way to replace any text on the site.
Features:

Easily replace anything that's passed through t()
Locale support, allowing you to override strings in any language
Ability to import/export *.po files, for easy migration from the Locale module
Note that this is not a replacement to Locale as having thousands of overrides can cause more pain then benefit. Use this only if you need a few easy text changes.


Using forms API - sending submitted data as an XML attachment to an email address I need to have a request form on a D7 site which does a few different things with the form data:

Writes to database table (standard);
Emails a copy of the form data to a site administrator on a pre-defined email address;
Creates a XML file attachment in a prescribed format (not valid XML, so possibly best being a template with placeholder values being replaced by form data) which is also attached to the email to administrator.

The generation of the XML is currently working fine in a bespoke PHP system and I'm thinking for ease re-using the functionality would make good sense.

However, is there a simple way to hook this into the submit process for the Drupal form? I believe using the Forms API may be the best approach?

Just implement the hook_form_alter or hook_form_FORM_ID_alter and add your custom submit handler.

See this article for an intro into hooking into forms:
http://websmiths.co/blog/very-introduction-drupals-hookformalter


How many child pages can be added under a book parent item? When using the Book module, is there any limit on the number of child items that can be added to a book parent node?

Yes, books in Drupal 8 and 9 have a maximum depth of 9, which is the value of the
BookManager::BOOK_MAX_DEPTH constant.
const BOOK_MAX_DEPTH = 9;


How do I use an older jQuery version? Drupal 8.5 requires jQuery 3, which has some site breaking features. I would rather like to use version 2.2.4. I have tried the libraries-override approach suggested in How do I use a jQuery version different from the default one used by core? After applying that answer, the theme.libraries.yml file content is the following one.

global-styling:
  css:
    theme:
      css/main.css: {}

jquery-custom:
  remote: https://github.com/jquery/jquery
  version: "2.2.4"
  license:
    name: MIT
    url: https://github.com/jquery/jquery/blob/2.2.4/LICENSE.txt
    gpl-compatible: true

global-scripts:
  js:
    js/plugins.js: {}
    js/drupal-main.js: {}
    js/vendor/modernizr-3.3.1.min.js: {}
    js/jquery-2.2.4.min.js: { minified: true, weight: -20 }

  dependencies:
    - core/drupal
    - core/jquery
    - core/jquery.once

The theme.info.yml file content is the following one.

libraries:
  - theme/global-styling
  - theme/global-scripts
libraries-override:
  core/jquery: theme/jquery-custom

However, it gives me a reference error saying that jQuery is not defined. I have checked the path and there is no problem there. What am I missing here?

Is there any other way to downgrade from jQuery 3 to jQuery 2 in Drupal 8?

I also tried using the following code, but I still getting a reference error.

jquery-custom:
  remote: https://github.com/jquery/jquery.js
  version: "2.2.4"
  license:
    name: MIT
    url: https://github.com/jquery/jquery/blob/2.2.4/LICENSE.txt
    gpl-compatible: true
  js:
    js/jquery-2.2.4.min.js: { minified: true, weight: -20 }

global-scripts:
  js:
    js/plugins.js: {}
    js/drupal-main.js: {}
    js/vendor/modernizr-3.3.1.min.js: {}

I had the same issue with some older Google tags plugins that did not work with jquery 3.0.  You basically have to use the D8 library override methods in your theme to do this.

This actually goes into the theme info.yml file.  You need to have the other version of jquery defined in your library.yml file as well.  Here's some excerpts from my theme files.

my_theme.info.yml

libraries-override:
  #downgrade jquery / force jquery into header
  core/jquery: my_theme/jquery

The core/jquery was found by searching thru the core to find the jquery library definition.

my_theme.libraries.yml

jquery:
  header: true
  remote: https://github.com/jquery/jquery
  version: "2.2.4"
  license:
    name: MIT
    url: https://github.com/jquery/jquery/blob/2.2.4/LICENSE.txt
    gpl-compatible: true
  js:
    js/jquery-2.2.4.min.js: { minified: true, weight: -20 }

Note: The header: true loads jquery in the header and not the footer.  Helps a bit with embedded jQuery code that complains that jquery does not exist.  I have a local copy of jquery in the js directory of my theme as well.

This technique can override any CSS or javascript included by any module or core.


How do I dynamically populate a select field? this question comes quite often but I couldn't make it work to that point.
My problem is simple, I have a 2 level taxonomy, I have 2 select fields, one is populated with the parent taxonomy and the second should be populated by its children when one parent is selected.

But I'm a bit confused. I followed the developer example with the check-boxes, but still. Also, this happens in hook_form_alter() and since I'm quite new to Drupal 7, I have to set the options with the ['und'] prefix, but that also troubles my mind because when I omit the ['und'] part when I try to save the node, an error says Illegal choice.

This is my first select field.

  //Field TYPE
  $form['field_type']['und']['#options'] = std_to_array($vocabulary_nudge_all);
  $form['field_type']['#ajax'] = array(
    'callback' => 'ajax_nudge_taxonomy_selected_callback',
    'wrapper' => 'select-target-div',
    'method' => 'replace',
    'effect' => 'fade',
  );

This is the AJAX callback function where I tried to get the field_type value, but I read somewhere that I couldn't use $form_state in a form hook.

function ajax_nudge_taxonomy_selected_callback($form, $form_state) {
  return $form['field_target_select'];
}

Using $form, all I could think of was using #delta.

$selected = $form['field_type']['und']['#delta']

In the second select with a prefix, a suffix, and a visible condition, I am using the following code.

//Field Target SELECT
$form['field_target_select']['#weight'] = '0';
$form['field_target_select']['#prefix'] = '
';
$form['field_target_select']['#suffix'] = '
';
$form['field_target_select']['und']['#options'] = std_to_array($vocabulary_nudge_all);
$form['field_target_select']['#states'] = array(
  'visible' => array(
    ':input[name="field_type[und]"]' => array(
      array('value' => 'carroussel'),
      array('value' => 'vitrine'),
    ),
  ),
);

I know there would be a solution by creating several select fields with visible conditions, but later more taxonomy fields could be added.

Right now it's not even doing the AJAX call anymore, and I can't manage to fix this, so any help would be appreciated.

I read somewhere that I couldn't use $form_state in a form hook

Not quite. If hook_form_alter() is being executed for the first time, then yes, $form_state can't be used to get a field's value because $form_state['values'] will not be set.

However, if hook_form_alter() is being re-executed, like from an #ajax callback, then $form_state['values'] will be set with the current form values, just like it would be in #submit[] and #validate[] functions. By the way, the $form['#validate'][] functions are also executed during an #ajax callback.

In your case, I believe you would get the current value of field_type from $form_state['values']['field_type'][LANGUAGE_NONE][0] (best to use the constant LANGUAGE_NONE instead of the string 'und'). Wherever you build the #options array for field_target_select during the execution of hook_form_alter(), you would do something like this:

$selected = 'some_default_value';
if (!empty($form_state['values']['field_type'][LANGUAGE_NONE][0])) {
  $selected = $form_state['values']['field_type'][LANGUAGE_NONE][0];
}
$child_options = my_function_to_get_child_options($selected);
$form['field_target_select'][LANGUAGE_NONE]['#options'] = $child_options;

What you have as your ajax callback function in your question looks correct:

function ajax_nudge_taxonomy_selected_callback($form, $form_state) {
  return $form['field_target_select'];
}


Remove filter formats help text In D6 and D7, with a simple form_alter you could unset $element['format'], but now the format help and the format tips are added in a #process method.

How can I remove them?

Apparently you can't hook into the #process phase, but you can still do a #pre_render, from /Drupal/Core/Render/Renderer.php

// If the default values for this element have not been loaded yet, populate
// them.
if (isset($elements['#type']) && empty($elements['#defaults_loaded'])) {
  $elements += $this->elementInfo->getInfo($elements['#type']);
}

// Make any final changes to the element before it is rendered. This means
// that the $element or the children can be altered or corrected before the
// element is rendered into the final text.
if (isset($elements['#pre_render'])) {
  foreach ($elements['#pre_render'] as $callable) {
    if (is_string($callable) && strpos($callable, '::') === FALSE) {
      $callable = $this->controllerResolver->getControllerFromDefinition($callable);
    }
    $elements = call_user_func($callable, $elements);
  }
}

For example, to hide the element format of the body field of an article:

/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form['#pre_render'][] = 'mymodule_form_pre_render_body';
}

function mymodule_form_pre_render_body(array $element) {
  foreach (Element::children($element) as $key) {
    if ($key == 'body') {
      foreach (Element::children($element[$key]['widget']) as $widget) {
        $element[$key]['widget'][$widget]['format']['#access'] = FALSE;
      }
    }
  }

  return $element;
}


Losing custom #theme settings set in hook_field_widget_form after an error I have defined a custom field in a custom module.  The new field applies a custom font to the options, and I have run into an issue with the widget form after an error. I have implemented hook_field_widget_form in a manner similar to the following:

mymodule_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  switch ($instance['widget']['type']) {
    case 'mymodule_custom_widget':
      $element += array(
        '#theme' => 'mymodule_checkboxes',
      );
      break;
  }
  return $element;
}

mymodule_checkboxes and mymodule_checkbox have been defined in hook_theme as follows

function mymodule_theme() {
  return array(
    'mymodule_checkboxes' => array('render element' => 'element'),

    'mymodule_checkbox' => array(
      'template' => 'mymodule_checkbox',
      'pattern' => 'mymodule_checkbox__',
      'arguments' => array('element' => NULL),
    ),
  );
}

To put it shortly, theme_mymodule_checkboxes calls theme(array('mymodule_checkbox'), array('element' => $current_element)); on every element in the #options array.

Everything is working great on the initial load of the form, the theme_mymodule_checkboxes function is called and the options are output using my custom template (the template isnt really necessary, I plan on replacing it with a theme function but havent gotten around to it. I don't think that particular oversite has any bearing on this issue but I may be wrong).  After I submit the form with an error - say I don't input a title or some such - the field is rendered using the default checkboxes theme.

Is there some hook I am missing in which I can define the default theme for the form widget before hook_field_widget_form?  One that hopefully fires even after a form fails validation?  I think I might be able to require a form rebuild in my custom field validation, but that forces extra work, and I would like to avoid that.

This one turned out to be a fairly simple fix. I had theme_mymodule_checkboxes living in mymodule.admin.inc which was not being included on every page. Moving the function to the mymodule.field.inc which is specifically included in the module file caused the theme function to be included and fixed the error.

Many thanks to the drupal user Ayalon who found this fix.


Change display of teaser based on content type of page in which it is displayed So I know you can define how to display a teaser for different content types using if($teaser) in node--content_type.tpl but how can I add logic to render the teaser in different formats depending on the content type of the page in which it is being displayed?

I want to do this

if($teaser && CONTENT_TYPE_OF_PAGE_THAT_TEASER_IS_DISPLAYED_ON == content_type)

within node--content_type.tpl is there a way to go about this?

For example I have teasers of content type blog. But I want these teasers to display different when they are on a page of content-type:blog, to when they are displayed on a page of content-type:level_3.

Thanks for your time

Have you tray display suit?

Display suit let you configure how you want to print the teaser and the full content type with a great UI

Oskar


change custom css class to block content When I create new block drupal auto create this html tags and default css class for block content:

now i need to edit css/class like this:

It is possible? If YES, How To?

You can override the template for the block.

To see what the template should be you can use the following in your themes template file.

/sites/all/themes/YOURTHEME/template.php

function YOURTHEME_preprocess_block(&$vars) {
   var_dump($vars['theme_hook_suggestions']);
}

Also make sure you have a copy of block.tpl.php in your themes template folder.
You can get this by going to /modules/block/ and copying the file to /sites/all/themes/YOURTHEME/templates.

This is handy because you can copy the code from the default block template to your custom block template and make any changes you want there. If you were to delete your custom block template it will default back.

Heres more on template (theme hook) suggestions
http://drupal.org/node/1089656


Access to preprocess variables in a custom block I have created a custom block to display some contact information.

I have a preprocess function that sets a contact variable like so:

function atstump_preprocess(&$vars, $hook) {
    $vars['contact'] = array(
        'name' => 'Doug Gillum',
        'business' => 'Portland Stump Grinding',
        /...
    );
}

I enabled the PHP filter, and set this as the text:

<?php print $contact['name']; ?>

<?php print $contact['phone']; ?>

<?php print $contact['email']; ?>

However it doesn't recognize $contact as a proper variable and generates the PHP error E_NOTICE:

Notice: Undefined variable: contact in eval() (line 2 of C:\xampp\htdocs\stumpgrinding\modules\php\php.module(75) : eval()'d code).
Notice: Undefined variable: contact in eval() (line 3 of C:\xampp\htdocs\stumpgrinding\modules\php\php.module(75) : eval()'d code).
Notice: Undefined variable: contact in eval() (line 4 of C:\xampp\htdocs\stumpgrinding\modules\php\php.module(75) : eval()'d code).

Is it even possible to access the preprocess variables in a PHP filter? if not, is there a better way than hard coding them? maybe variable_set and variable_get and how would I set that up via the theme, I'd rather not make a module for this.

It won't work.
If you use a preprocess function, the variables will be available in the template of the block.

I think that, in your case, you should edit the settings.php file and add the following line:

$GLOBALS['email1'] = 'example@email.com';

You'll be able to use the variable $email1 through the whole site.

Have in mind that it's not a good Drupal practice.


How do I get all available form field types? How do I get all form field types (e.g. "textbox," "select") available in Drupal 6?

The core fields are provided by hook_elements so you can just invoke that hook to get a list of all field types in the site using module_invoke_all():

 $all_types = module_invoke_all('elements');

The array keys of $all_types are the machine names of the elements, each of those points to another array containing the element information.


Restore blocks on Drupal 7 How can I restore the original position (order and initial regions) of blocks on Drupal 7?

I need to make a button that you can restore the block position on Drupal 7. What function or table can be used?

The information about the blocks are saved in the "block" table. The block information is saved in the admin form handled by block_admin_display_form() using the following code.

  foreach ($blocks as $i => $block) {
    $key = $block['module'] . '_' . $block['delta'];
    $form['blocks'][$key]['module'] = array(
      '#type' => 'value',
      '#value' => $block['module'],
    );
    $form['blocks'][$key]['delta'] = array(
      '#type' => 'value',
      '#value' => $block['delta'],
    );
    $form['blocks'][$key]['info'] = array(
      '#markup' => check_plain($block['info']),
    );
    $form['blocks'][$key]['theme'] = array(
      '#type' => 'hidden',
      '#value' => $theme,
    );
    $form['blocks'][$key]['weight'] = array(
      '#type' => 'weight',
      '#default_value' => $block['weight'],
      '#delta' => $weight_delta,
      '#title_display' => 'invisible',
      '#title' => t('Weight for @block block', array('@block' => $block['info'])),
    );
    $form['blocks'][$key]['region'] = array(
      '#type' => 'select',
      '#default_value' => $block['region'] != BLOCK_REGION_NONE ? $block['region'] : NULL,
      '#empty_value' => BLOCK_REGION_NONE,
      '#title_display' => 'invisible',
      '#title' => t('Region for @block block', array('@block' => $block['info'])),
      '#options' => $block_regions,
    );
    $form['blocks'][$key]['configure'] = array(
      '#type' => 'link',
      '#title' => t('configure'),
      '#href' => 'admin/structure/block/manage/' . $block['module'] . '/' . $block['delta'] . '/configure',
    );
    if ($block['module'] == 'block') {
      $form['blocks'][$key]['delete'] = array(
        '#type' => 'link',
        '#title' => t('delete'),
        '#href' => 'admin/structure/block/manage/' . $block['module'] . '/' . $block['delta'] . '/delete',
      );
    }
  }

Using $form_state['values']['blocks'][$key]['module'], and $form_state['values'][$key]['delta'], you can find the block information from that table, and set the form fields to the  values found in the database. In the submission handler for that button, you should also set $form_state['#rebuild'] to TRUE to rebuild the form with the restored values.


How to unpublished a node from a view? I have a list of all nodes (in my specific case Product Display, generated in Commerce kickstart) using a view. Is there a quick way I can have an unpublish/publish option right there in the view results list? I'd like to avoid the following everytime I need to perform this operation.

browsing to Node/Edit
selecting the publish options tab
(un)ticking Published
hitting Save

Does anyone know of a simple way?

I suppose you could use Views Bulk Operations (VBO) to achieve this. VBO lets you select various nodes in a list and then perform an action to all of them. VBO is highly customizable and extendible. VBO can be combined with other modules like mighty Rules and others. Bulk publishing and  unpublishing would (of course) also be possible.

ps: actually this could also be achived through the 'regular' content handling (/admin/content). Just set the content type filter to your content type and you can already bulk publish/unpublish. But I suppose you tried this already and would prefer to have the same nodes as you have in the view?


Adding autocomplete to title field of node form I created a small custom module to help users while creating a specific content type.  Basically the module just adds the autocomplete feature to the title field to show possible duplicate nodes to the user while filling out the form for "on-the-fly" feedback.

The problem is that the autocomplete only works for users with the permission 'Administer nodes'.  Is this normal or am I doing something wrong?  If it is normal, is there another way to achieve these results without handing out that permission?

Custom module:

<?php
/**
 * Implementation of hook_menu()
 */
function duplicates_menu() {
  $items = array();
  $items['duplicates/check'] = array(
    'title' => 'Check for duplicates',
    'page callback' => 'duplicates_check',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Implementation of hook_form_alter()
 */
function duplicates_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'company_node_form') {
    $form['title']['#autocomplete_path'] = 'duplicates/check';
  }
}

/**
 * Check for duplicates
 */
function duplicates_check($check) {
  $duplicates = array();
  if ($check) {
    $results = db_query('SELECT title FROM {node} WHERE type = "company" AND LOWER(title) LIKE LOWER("%%%s%%")', $check);
    while ($dupes = db_fetch_object($results)) {
      $duplicates[$dupes->title] = check_plain($dupes->title);
    }
  }
  print drupal_json($duplicates);
}

Avoid a custom implementation and use the Unique Field Module. Once this module is enabled, it adds a 'Unique field settings' section to each content type's administration page for specifying which fields (Including node title) for that content type must be unique.The administrator may choose whether the fields must be unique among all other nodes, among nodes of the same content type, or of the same language. You can also set it to display the nodes that match the title.


Alter cart unit price and total amount I need help on this code which is invoked on calculate sell price rules event
on cart view. Line items and order are properly modified. But nothing is displayed, old unit price amount and old total amount are displayed. Even after cart refresh. Any idea ?

/**
* Calculates the price when line item are dispalyed
* or created.
*/

function mymodule_calculate_product_price_cart($order) {
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
    // Iterates on line items and alter the price.
    $commerce_line_items = array();
    foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) {
      $line_item = $line_item_wrapper->value();
      $type = $line_item_wrapper->commerce_product->value()->type;
      if ($type === 'insurance') {
        $package_price   = $line_item_wrapper->commerce_product->field_package_ref->commerce_price->amount->value();
        $warranty_price  = $line_item_wrapper->commerce_product->commerce_price->amount->value();
        $amount = _mymodule_calculate_policy_price($warranty_price, $package_price);
      }
      elseif ($type === 'little_product') {
        $amount = $line_item_wrapper->commerce_product->commerce_price->amount->value();
      }
      else {
        $commerce_line_items[$delta] = $line_item;
        continue;
      }
      $qty = $line_item->quantity;
      // This sets the unit price by adding a component price 'base_price'
      mymodule_line_item_price_amount($line_item, $amount, 'commerce_unit_price');
      mymodule_line_item_price_amount($line_item, $qty * $amount, 'commerce_total');
      commerce_line_item_save($line_item);
      entity_get_controller('commerce_line_item')->resetCache(array($line_item->line_item_id));
      $commerce_line_items[$delta] = $line_item;
    }
    $order_wrapper->commerce_line_items = $commerce_line_items;
    module_invoke_all('commerce_cart_order_refresh', $order_wrapper);
    commerce_order_save($order_wrapper->value());
  }

I finally made it work.

function mymodule_commerce_commerce_cart_order_refresh($order_wrapper) {
  foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) {
    $line_item = $line_item_wrapper->value();
    $type = $line_item_wrapper->commerce_product->value()->type;
    if ($type === 'insurance') {
      $package_price   = $line_item_wrapper->commerce_product->field_package_ref->commerce_price->amount->value();
      $warranty_price  = $line_item_wrapper->commerce_product->commerce_price->amount->value();
      $amount = _mymodule_commerce_calculate_policy_price($warranty_price, $package_price);
    }
    elseif ($type === 'little_product') {
      $amount = $line_item_wrapper->commerce_product->commerce_price->amount->value();
    }
    else {
      return TRUE;
    }
    $qty = $line_item->quantity;
    // This sets the unit price by adding a component price 'base_price'.
    mymodule_commerce_line_item_price_amount($line_item, $amount, 'commerce_unit_price');
    mymodule_commerce_line_item_price_amount($line_item, $qty * $amount, 'commerce_total');
    commerce_line_item_save($line_item);
    entity_get_controller('commerce_line_item')->resetCache(array($line_item->line_item_id));
  }
}


Translated terms are not searchable with Search API While using Search API it does not index the translated/localized terms.

So does it mean translated terms are not searchable with Search API?

any clue?
thanks

I think that this is core issue that the search index does not add the localized term to the index, I solved that by implementing hook_node_update_index($node) and fetching the localized term name by querying it from database because I don't know why i18n_taxonomy_localize_terms function doesn't load the term properly. my code is below:

function mymodule_node_update_index($node) {
  $text = '';
  $tid = key($node->your_taxonomy['und'][0]['tid']);
  if($tid != 0) {
    $query = db_select('locales_target', 'lt');
    $query->addExpression('CONVERT(translation USING UTF8)', 'translation');
    $query->join('locales_source', 'ls', 'ls.lid = lt.lid');
    $query->condition('context', 'term:'.$tid.':name');
   $text = $query->execute()->fetchColumn();
  }

  return $text;
}

Note: in my case the text is Arabic so I converted the field character set from blob to utf8.