Site dead after Devel Module and Library sethtmldom After installing Devel Module (and Library simplehtmldom), the Drupal7 site is completely dead. Have already set the module to 0 on System table in database, and the module files removed by FTP. But still no recovering. How to remove simplehtmldom Library? What else to recover the site? Thanks.

You can try using Registry Rebuild

Project page says..

  THIS IS NOT A MODULE. YOU CAN'T ENABLE IT. FOLLOW THE INSTRUCTIONS.

  Make a backup of your database before running this. It won't break
  your database, but we can't improve this unless we have broken
  databases that it doesn't quite do the job for.

  There are times in Drupal 7 when the registry gets hopelessly hosed
  and you need to rebuild the registry (a list of PHP classes and the
  files they go with). Sometimes, though, you can't do this regular
  cache-clear activity because some class is required when the system is
  trying to bootstrap.

  When would you need Registry Rebuild? You might get something like:

  PHP Fatal error:  Class 'EntityAPIControllerExportable' not found in
  ...sites/all/modules/rules/includes/rules.core.inc on line 11

Look in the error log to see an actual error. Put the modules you deleted back in the folder. Try uninstalling them with Drush.

Also, Drush can help you diagnoze - it can print error messages even if the whole site goes WSOD.

Basically, devel + htmldom won't ruin your site, unless you are tight on memory. If that's try, set max memory in php.ini to 256M or 512M.

And on the contrary, you can try deleting these modules folder manually and seeing of the site runs. Also, you can try to remove all the contrib modules folder as a whole and seeing if that helps.

Some more things - check if error messages are disabled (should be enabled) for development in php.ini. I fyou have little memory and no error messages enabled, that any case like htis will be a nightmare ;)


Is it possible to preserve image quality when uploading images? Is it possible to preserve image quality when uploading images through Drupal7?

For example, I take this image:
http://f.cl.ly/items/0L3j21030C3O2A3x2w0b/thumb.jpg

I upload it using an Imagefield, which has no min/max resolution set, and it looks like this:
http://f.cl.ly/items/2B2q2a1H402T1Z1j3w2j/baboon-onesie-costume-thumb.jpeg

So already we're seeing a loss in quality. Then it's displayed using a view, which scales the image (which it should do IF) it's larger than 190x280 (which it isn't), and now it looks like:
http://f.cl.ly/items/2n023q1Q331J3E2d3a3I/baboon-onesie-costume-thumb-1.jpeg

The quality difference is massive - there's a huge loss of colours and severe artefact creation around the image edges.

The GD image settings are JPEG quality: 100%.

Is there anything that can be done to prevent this ridiculous loss of quality?

There's two solutions to this. The easiest is:

Upload images with a "jpeg" extension instead of a "jpg" extension. For whatever reason, images with a jpeg extension are not mangled by Drupal.

However, the best solution if you have control over your hosting environment is:

Install the imagemagick module.

Under the display settings for content types image field you could set the format to none:original image
And a CSS rule to display the image at the desired size

caveat
this probably would lead to problems as users could upload images with extreme max/min image resolutions.


How do I add an external link in a module? I'm attempting develop a module in drupal-8 that provides a link to an external password reset system. Specifically on the login page I'd like a reset my password link that points to a link such as https://reset.my.password/

I've tried adding my module.links.task.yml file. What else do I have to create to add an external link?

There seems to be very little information on this matter, maybe it's not that common to try to achieve something like this, but I stumbled across this thread while searching for a solution and I'd like to add my thoughts.
The comments stating that links.task.yml is for local tasks is right, but when it comes to external links, it's not that simple. As far as I know, you need routing to add links that way, and routing is for internal links, right?
So in the end I did it this way in Drupal 9:
  function my_module_menu_local_tasks_alter(&$data, $route_name) {
    $data['tabs'][0]['node.extra_tab'] = array(
      '#theme' => 'menu_local_task',
      '#link' => array(
        'title' => t('Extra tab'),
        'url' => Url::fromUri('https://theurl.com', array('attributes' => array('target' => '_blank'))),
        'localized_options' => array(
          'attributes' => array(
            'title' => t('Extra tab'),
          ),
        ),
      ),
    );
  }

You can also add something like if ($route_name == 'entity.node.canonical') to narrow it down and also if (\Drupal::routeMatch()->getParameter('node') == 'my_content_type') in case you want this to work only on certain content type(s).

You can try hook_menu_local_tasks_alter

/**
 * Implements hook_menu_local_tasks_alter().
 */
function mymodule_menu_local_tasks_alter(&$data, $route_name, RefinableCacheableDependencyInterface &$cacheability) {
  foreach ($data['tabs'] as &$tab){
    $tab['routing_name']['#link']['url'] = Url::fromUri('https://reset.my.password/');
  }
}


Javascript/CSS from module not loading I am using a custom module (copied from a site where it is working)

The module's .info file is as follows:

name = jCarousel Rotator
description = An image rotator implementing the jCarousel jQuery plugin
package = mymodules
core = 7.x

stylesheets[all][] = css/jcarousel_rotator.css
scripts[] = js/jquery.jcarousel.min.js
scripts[] = js/jcarousel_rotator.js

But none of these files are loading.  The theme I'm in is made from scratch.. is there something that needs to be added to the template.php for those include hooks to work?

I searched all the code of the old site and the files are not being explicitly loaded elsewhere.

I have been able to load the files by adding the code manually to the footer, but this is not a great way to have a module integrated.

As requested, my html.tpl.php is as follows:

<?php include 'header.php'; ?>
<?php echo $page; ?>
<?php include 'footer.php'; ?>

Based on your edit including html.tpl.php, I agree with Chapa that's it very, umm, "Un-Drupaly".  This is the default system rendering of html.tpl.php:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN"
  "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language; ?>" version="XHTML+RDFa 1.0" dir="<?php print $language->dir; ?>"<?php print $rdf_namespaces; ?>>

<head profile="<?php print $grddl_profile; ?>">
  <?php print $head; ?>
  <title><?php print $head_title; ?></title>
  <?php print $styles; ?>
  <?php print $scripts; ?>

<body class="<?php print $classes; ?>" <?php print $attributes;?>>

    <?php print t('Skip to main content'); ?>

  <?php print $page_top; ?>
  <?php print $page; ?>
  <?php print $page_bottom; ?>

You see where it says:

<?php print $styles; ?>
<?php print $scripts; ?>

That's where Drupal dumps your JavaScript and CSS files.  If you're not making those calls chances are you're not going to get any included files.  I guess to verify this you'd also have to edit in your header.php and footer.php files so we can see what they contain.  This is where you want to start looking.

I recommend backing up your existing html.tpl.php file to somewhere, and then overwriting it with the system version of it, which can be found at modules/system/html.tpl.php relative to the root directory of your site on your system.

It will be better if you post the modulename.info file here. As it seems the code in the info file is correct.

About a proper way, If you use hooks then this is what you can do.

drupal_add_css() & drupal_add_js().

drupal_add_css(drupal_get_path('module', 'module_name') . '/style.css', array(
    'group' => CSS_DEFAULT,
    'every_page' => TRUE,
));

Then you can call it in hook_init().
Hope that helps you.


Access Drupal globals in Twig As documented here, there are some global variables defined by Drupal. How can I access them in twig?

These variables are not available to template files, but you can easily add it to every template file by implementing hooks.

You need to prepare variable for twig files. To use the global variables in twig files you need to set it.

Prepares variables for the page template:

You will get details  template_preprocess_page.

function template_preprocess_page(&$variables) {
  $variables['base_path'] = base_path();
}

Injecting variables to twig templates from a custom module, for example the 'module path' :

function custom_module_preprocess(&$variables, $hook) {

  $module_handler = Drupal::service('module_handler');
  $path = $module_handler->getModule('amu_http_status_code_display')->getPath();

  if($hook == 'page') {
    $variables['module_path'] = $path;

  }

}


Adding icons to field labels How do I add icons next to field names, like adding a phone icon in front of the mobile phone field?

i tried the patches shown in https://www.drupal.org/node/2050257, but they do not seem to work.

I have seen this on some websites, so I guess it should be possible.

You can change the label using the template_preprocess_field hook.

For instance, if your field was named "phone" and the content type was "business", you could add this to your template.php:

template_preprocess_field (&$variables) {
  $content_type = $variables['element']['#bundle'];
  $field_name = $variables['element']['#field_name'];

  if ($content_type == 'business' && $field_name == 'phone') {
    $variables['label'] = '<img src="http://www.carloancentre.ca/wp-content/uploads/2014/03/Contact-Methods-Phone-icon.png" height="16" width="16"/>' . $variables['label'];
  }
}

I will advice to fix this issue by using the CSS injector module to add the necessary CSS styles to show an icon before the field label.

  Allows administrators to inject CSS into the page output based on configurable rules. It's useful for adding simple CSS tweaks without modifying a site's official theme. The CSS is added using Drupal's standard drupal_add_css() function and respects page caching, etc. The 2.x brach leverages CTools so CSS can be included with Feature changes (ie. CSS that improves the look of a View can be packaged with the View).


How do I print a menu with links generated by my custom module? If I use

theme('links', array('links' => menu_navigation_links('main-menu'),
'attributes' => array('class'=> array('links', 'main-menu')) ));

It will print the links in my Main Menu. I need to print the links that are created by my custom module, but I do not know what the system menu name is.

For instance:

 //hook_menu
 function custom_menu() {

     //admin page
     $items['admin/custom'] = array(
     'title' => t('Custom Admin Page'),
     'description' => t('Manage Custom Module'),
     'page callback' => 'custom_admin_page',
     'access arguments' => array('access toolbar'),
     'type' => MENU_NORMAL_ITEM,
     );

     //add event
     $items['admin/custom/add'] = array(
     'title' => t('Add Custom'),
     'decription' => t('Add custom'),
     'page callback' => 'custom_add',
     'access arguments' => array('add custom'),
     'type' => MENU_NORMAL_ITEM,
     'file' => 'custom_add.inc',
     'file path' => drupal_get_path('module', 'custom') . '/includes',
     );

The page 'admin/custom' automatically goes into my administration menu, and the page 'admin/custom/add' is seen under the admin/custom link when viewing all of the links in the administration menu, but I want to print that menu (admin/custom) on the 'admin/custom' page so that I can see the link 'admin/custom/add'.

Menus and paths are slightly different things...in hook_menu() you're defining paths that can be consumed; menus create the links to those paths - the two concepts aren't necessarily related (a path can exist without a menu link).

You can assign a particular router path to a menu using the menu_name property in your hook_menu() items, but that menu needs to exist already.

Fortunately Drupal provides a method for adding links to the top of a page through hook_menu(), and you only need to change one line:

$items['admin/custom/add'] = array(
  'title' => t('Add Custom'),
  'decription' => t('Add custom'),
  'page callback' => 'custom_add',
  'access arguments' => array('add custom'),
  'type' => MENU_LOCAL_ACTION, // <-- This one changed
  'file' => 'custom_add.inc',
  'file path' => drupal_get_path('module', 'custom') . '/includes',
);

That will put a link to 'Add Custom' at the top of the 'admin/custom' page; if you're using the Seven theme for administration it'll look like the 'Add Content' link on the content admin page:

You should see hook_menu path added to navigation menu not showing up.

You need to change the following line of code.

'type' => MENU_NORMAL_ITEM,


Configuration form settings I would like to create a settings page for a user which allows them to save the options of a list which is to be used in a custom form. The list is called marketing source and it is added to a form which gets submitted with plain text values to an external API.

I know in field config for select lists you can do this but I want to do it on a custom config page for that specific list.

Foe example I would have a textfield in the config that had values like this

1|google
2|magazine

Then I need to convert that into a seralised array and store with variable set.

Is there a function that does that already for the field form?

Cheers Dan

This is how I achieved what I wanted, rather than use key value pairs I just used an empty textfield and used one line for each option and then when retrieving the textfield for the form I used the following.

$raw_marketing_options = explode(PHP_EOL, variable_get('marketing_sources_sources'));

I then just used the variable directly in the form.

$form['Marketing_source__c'] = array(
  '#type' => 'select',
  '#title' => 'Marketing source',
  '#options' => $raw_marketing_options,
);

There may be a safer way to do it as I am not sure how secure variable_set() is when storing plain text but only the administrator will see the textarea anyway.

Cheers

You can use a system_settings_form this is a 'shortcut' creates a form that saves input data via a variable_set(). The tutorial also explains how to create a page for the form.

Tutorial on settings form

variable_set/variable_get always serialize/deserialize any array you pass to them.


How to re-enable content notifications for Notify? I turned off content notifications for all users for Notify some time ago because it was sending duplicates. There was a checkbox somewhere that I unchecked. It is not in notification settings.

This is Drupal 6.

Reading your comment on my question above, I guess you're using Actions & Triggers in Drupal 6.

To see which actions you have defined or to define new actions, go to Administer > Site Building > Actions. There e.g. you can define an action for sending an email. From your question I think you already have done that (in the past).

To assign this action to an event, you have to go to Administer > Site Building > Triggers. There you can choose (under Content) to assign an action to an event, such as published or updated content.

The documentation I was looking for is here:
https://drupal.org/documentation/modules/notify

The "master switch" appears to be a feature of the D7 version of the module.


Change Text of Create an Account in Login Block I want to change text of Create an account to

something>
Click here

When I print the form I got these values

[links] => Array
        (
            [#markup] =>

Create new account

Forgot your password?

        )

Also, I gave a try in settings.php like

$conf['locale_custom_strings_en'][''] = array(
  '"Create a new user account' => '
somethifn>
Click here',
);

But this prints as a text.

Anybody can help?

The above mentioned problem can be easily solved by using hook_form_alter hook_form_alterhook_form_alter(&$form, &$form_state, $form_id) . You can use that function in our template.php of your custom theme .

In template.php write..

function custom_theme_form_alter(&$form, &$form_state, $form_id){
  if( $form['form_id']['#value'] === 'user_register_form'){// For registration form on 'user/register' page
    $form['actions']['submit']['#prefix'] = '
';
    $form['actions']['submit']['#value'] = '--your text--';
    $form['actions']['submit']['#suffix'] = '
';
  }
  if( $form['#id'] === 'user-login-form' ){  // For login block that comes with drupal core blocks and can be assigned to any region.
    $form['links']['#markup'] = '

--your text--

Request new password

';
  }
}

This will change your text from 'Create a new account' to your custom text. And don't forget to clear the cache :).

Reply on this thread if you still find some problem.

I have solved the same problem with just two lines at the top in my page.tpl.php file,

<?php if($title == 'Create an account'):$title='whatever title you want';endif;  ?>

You can also include html tags to modify the title.

Thank you.


How to get a parameter value from the current URL in views-view-fields.html.twig? I need the argument value in the theme templates and using the views-views-fields--view_name--block_1.jhtml.twig.

I'm current getting the current URL like that:

{% set url = url('current')%}

Which outputs:

https://example.com/questions/12225

But I need only the 12225 value from the current url. How can I get the last parameter from the current URL in Twig?

You could use Twig's split filter, though I don't recommend scripting too much inside templates.

Instead I recommend to pass the value over to Twig from a preprocess function from inside your theme or a custom module via template_preprocess_views_view_fields.

/**
 * Implements template_preprocess_views_view_fields().
 */
function MYTHEME/MYMODULE_preprocess_views_view_fields(&$variables) {

  // Retrieve an array which contains the path pieces.
  $current_path = \Drupal::service('path.current')->getPath();

  if ($current_path[0] == 'questions') {
    $variables['question_id'] = $current_path[1];
  }
}

And then inside your template print it for example like so:

{% if question_id %}

Question ID: {{ question_id }}

{% endif %}

To fetch the current path with query string in views you can also use the Views Current Path (Global: Current Path) module.

  Provides a Views field that displays the URL of the current page being viewed.


hide the author information from the non-member I use Drupal-7.14 and the default theme,Bartik 7.14.
I added "my content type" as a new content type.
Then I could see a new content foo by the url hostname/content/foo.

The content foo shows the author and the date
because I checked

Structure > Content Types > my content type > edit > Display Settings > Display author and date information.

Only the date should be shown from logouted users.
The author should NOT be shown for logouted users.

How can I hide the author information from the non-member.

If you copy the node.tpl.php file from the templates directory and create a node--mycontenttype.tpl.php file you should see the following around line 91:

<?php if ($display_submitted): ?>

    <?php print $user_picture; ?>
    <?php print $submitted; ?>

<?php endif; ?>

Simply change it to this:

<?php if ($display_submitted): ?>

    <?php print $user_picture; ?>
    <?php if ($logged_in == TRUE): ?>
      <?php print $submitted; ?>
    <?php endif; ?>

<?php endif; ?>

The $logged_in variable is a node template variable that has the value of TRUE if a user is logged in.

In this snippet you're just saying if the user is logged in, then display the submitted information.

Don't forget to clear your caches!

EDIT

Apologies, I've read the question properly now.  The following should do what you want.

<?php if ($display_submitted): ?>

    <?php print $user_picture; ?>
    <?php if ($logged_in == TRUE): ?>
      <?php print $submitted; ?>
    <?php else: ?>
      <?php print $date; ?>
    <?php endif; ?>

<?php endif; ?>

This will display the entire submitted by text for authenticated users, and just the date for anonymous users.

In D7 navigate to admin/people/permissions

Find View user profiles permissions and grand it as you wish to be.


Enabled Panels In-Place Editor module but cant see the edit icon I am using Panels and have enabled the Panels In-Place Editor module but cannot see the edit icon on the page, the one that should be in top rhs corner.

What am I doing wrong?

you need to select the Renderer mode:

Standard or   In-Place Editor

Standard
Renders a panel normally. This is the most common option.
  In-Place Editor
Allows privileged users to update and rearrange the content while viewing this panel.

You need to see the permissions of the use "in place editor."


Browser specific javascript inclusion It seems like the browser conditionals:

  drupal_add_js(drupal_get_path('module', 'cufon') . '/js/cufon-drupal.js',
 array('group' => JS_THEME, 'browsers' => array('IE' => 'gte IE 9', '!IE' => TRUE),
'weight' => 999, 'preprocess' => FALSE));

included in template.php (or a module) are not working due to the fact browsers option is supported for drupal_add_css() but not for drupal_add_js().

Can one state a not-hackish/patchy solution to exclude this file cufon-drupal.js on older browsers?

A solution like

<!--[if gte IE 9]>
<script src='<?php drupal_add_js(drupal_get_path('module', 'cufon') . '/js/cufon-drupal.js'); ?>'>
</script><![endif]-->

in html.tpl.php
is not working.

Seems like there is a non-drupal solution:

if(jQuery.browser.version.substring(0, 2) != "8.") { alert("not ie8"); }

It is not very handy as I have to paste inside the brackets the content of cufon-drupal.js content.


CSS class for view display not being applied I have a view set up with a block display. Its style is set to HTML list, which it does with no problem. But it doesn't seem to be applying the CSS class listed in the setup. What do I need to do to get this to apply?

Edited to add: Drupal 6, Views2

I said IF its D7 bc I could not find what version. I was reading it on my phone. But here's your Drupal 6 answer:

But here's the template suggestions for D6:
http://drupal.org/node/1089642

You can download devel module to get template suggestions as well.

-OR-

Download this module to add css classes to specific blocks:

http://drupal.org/project/block_class

If its Drupal 7 you need to theme your blocks. You can override that by creating a block.tpl.php file & place it where your html.tpl.php file resides.

Next goto http://drupal.org/files/issues/Core_templates_and_suggestions.pdf
to see what template suggestions you might need. You can also search drupal.org for more, bc your block.tpl.php file might be named block--%--.tpl.php < % denotes wildcard.

Next you will have to theme you block. You can control the HTML output with the $output variable, as well as classes and ID's. You have the option of generating classes and UD's statically or dynamically.

You could also do a theme preprocessing function (your_site_name HTML &vars function) in the template.php file.

Example for block.tpl.php

/* more code here, below outputs whatever you code here  */

$output .= ''   .   $links['title']   .  ''";


Cron stopped running; logs say: "Attempting to re-run cron while it is already running." What are the steps to troubleshoot and resolve this issue as per title?

When I try to run manually, I get a  page immediately, and the error message "Attempting to re-run cron while it is already running."

Summary

The error message you are seeing would happen if the following two conditions are met:

You cron jobs do not finish (error) or take more than 4 minutes to finish ;
You invoke cron more often than every 4 minutes (According to your crontab setting, not the setting in Drupal)

This error message is therefore a symptom of a cron tasks that is either failing or taking too long to run. (Note: I realise you have already found the culprit, but I wanted to add an answer for people who find this page via searches, as I did)

Background

The first thing to understand is how Drupal cron tasks are run. The Drupal cron is invoked at regular intervals - either through a cron job on your server, or after every page load if you use the poor man's cron which is Drupal's default.

The cron tasks are not necessarily run every time cron is invoked however - there is a setting in Drupal (default is 3 hours) which says how often cron tasks should be run. But this delay of 3 hours only applies if the cron tasks have finished successfully.

In Drupal 7, cron uses Drupal's locking mechanisms, which provides a cooperative, advisory lock system. One of the features of this lock system is that locks expire after a certain time. In the case of cron, it expires after 4 minutes - so if your cron is invoked every 3 minutes and the previous cron job hadn't finished by that time (either it crashed or was very slow), you would indeed get this error message.

The fact you set the cron to be every 12 hours does not make a difference - because the Drupal cron task is failing/taking too long, Drupal assumes it hasn't been run so tries to run it again as soon as cron is invoked. The twelve hour delay only applies to successful cron runs.

The cron semaphore variable does not exist any more in Drupal 7 - this was for an older version of Drupal. In Drupal 7 there is no reliable way to manually release a lock, because the locking backend might change - however if you are using the core locking mechanism then you can release cron locks by editing the database:

DELETE FROM semaphore WHERE name = 'cron';

But by doing this you would only be fixing the symptoms - the problem that needs addressing is why is cron failing / taking so long to run.

I've come up against this a few times. In Drupal 6 If you don't use drush you can fix it like this:

1 Remove the cron_% variables from the variables table.

SELECT * FROM variable WHERE name like "cron%";

DELETE FROM variable WHERE name like "cron%";

2 clear Drupal cache at:
/admin/settings/performance

by pressing the 'clear cached data' button at the bottom of the page.

3 run cron from admin panel /admin/reports/status/run-cron
don't run it from comand line as this can cause problems.

4 Check that the next automatic cron run completes as normal.


Facet API : How to change some behaviors like having input radio instead of checkbox I need to change some default behavior from the facet API.

I am searching for documentation about the hook from the Facet API module, but I have not found anything for now, except a very good tutorial about Apache Solr and Facet API.

I downloaded the Facet API bonus module because I thought it would help me.

There are some very good features like Rewrite facet items via callback function, but it seems it only works for the markup; I can't change the input.

function custom_facet_facet_items_alter(&$build, &$settings) {
  dsm($build);
  dsm($settings);
  if ($settings->facet == "field_produit_dev_durable") {
    foreach($build as $key => $item) {
      $build[$key]["#markup"] = drupal_strtoupper($item["#markup"]);
    }
  }
}

I tried to use the Devel modutle o see the content of the variables build, and setting, but there is nothing interesting for me.

So I need two things

Understand how to change the checkbox input
Understand how to remove the count number aside the Yes or No

I made my module and use this, but weirdly it doesn't remove the number.

$build[$key]["#markup"] = drupal_strtoupper($item["#markup"]);

I used the fist tutorial I linked at the beginning of my post, but I found a problem I don't understand.

When I used my code on two different facets I got an error:

  An illegal choice has been detected. Please contact the site administrator.

My code is the same code shown in this article, but I replace the select field with a radio field. I think there is a conflict between the two form, when I validate.

What you're doing to change the markup should just work, here's a working example I have from a project that does just that:

function foo_facet_items_alter(&$build, &$settings) {
  if ($settings->facet === 'my_facet') {
    foreach($build as $key => $item) {
      $build[$key]["#markup"] = drupal_ucfirst($item["#markup"]);
    }
  }
}

I can confirm that it works as expected.

As far as switching the select for a radio, the error you get is pretty common and you're probably not removing/adding extra Form API options that aren't allowed for one of the types.

Radio buttons behave a bit different than selects, you might not be able to just switch the #type and have it work, if this is still relevant, please post the code you're using to alter that form... thanks!

On this page you find a paragraph about creating a custom facet api widget:

http://www.trellon.com/content/blog/apachesolr-and-facetapi


How do I create a download link knowing the uploaded file ID? I've a column in database containing the IDs of the files uploaded using a managed file form field.

How do I create a link to the uploaded file knowing its file ID?

EDIT :
The obvious solution doesn't work for me , i'm using another table where i put my Fids .

this is the warning i got everytime :
Notice: Trying to get property of non-object in Affichage_form() (line 188 of C:\wamp64\www\Gestion_tickets_licences\sites\all\modules\Recherche\Recherche.module). << 188 : $uri= $file->uri; >>

Solution : Thank you for you help .
my solution for my problem is , Once I upload the file , I create the url. Instead of saving Fid , I save the url , It worked .For the download link , I used Alen syntax and it worked great .

First, load the file using file_load(FILE_ID) and get URI like below:

$file = file_load(1);
$uri = $file->uri;

After that generate link using file_create_url();

$url = file_create_url($uri);

Get file name also:

$filename  = $file->filename;

And finally, create a link using l().

l(t($filename), $url);

and output will be like picture-6.png

You can load file with id with file_load function and then you need to write <a href='file_path' download > file_name </a>


Core doesn't update with Composer We use commands:

composer outdated drupal/*
drupal/core 8.6.10 8.6.13 Drupal is an open source content management platform powering millions of websites and applications.

It does show 8.6.13.

We run either composer update drupal/core --with-dependencies or composer update drupal/core:8.6.13 webflo/drupal-core-require-dev --with-dependencies and we get nothing, it does update some dependencies and that is it. Our site is built with composer.

Here's the rest of the log:

composer update drupal/core:8.6.13 webflo/drupal-core-require-dev --with-dependencies
> DrupalProject\composer\ScriptHandler::checkComposerVersion
Package "drupal/core:8.6.13" listed for update is not installed. Ignoring.
Dependency "drupal/core" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Dependency "twig/twig" is also a root requirement, but is not explicitly whitelisted. Ignoring.
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 0 installs, 5 updates, 0 removals
  - Updating symfony/css-selector (v3.4.22 => v3.4.23): Loading from cache
  - Updating symfony/phpunit-bridge (v3.4.22 => v3.4.23): Downloading (100%)
  - Updating symfony/dom-crawler (v3.4.22 => v3.4.23): Downloading (100%)
  - Updating symfony/browser-kit (v4.2.3 => v4.2.4): Downloading (100%)
  - Updating squizlabs/php_codesniffer (3.4.0 => 3.4.1): Downloading (100%)
Package phpunit/phpunit-mock-objects is abandoned, you should avoid using it. No replacement was suggested.
Writing lock file
Generating autoload files
> DrupalProject\composer\ScriptHandler::createRequiredFiles
root@dev /var/www/example.com # composer update drupal/core
> DrupalProject\composer\ScriptHandler::checkComposerVersion
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Package phpunit/phpunit-mock-objects is abandoned, you should avoid using it. No replacement was suggested.
Generating autoload files
> DrupalProject\composer\ScriptHandler::createRequiredFiles
root@dev /var/www/example.com # drush status
 Drupal version   : 8.6.10
 Site URI         : default
 DB driver        : mysql
 DB hostname      : localhost
 DB port          : 3306
 DB username      : root
 DB name          : example
 Database         : Connected
 Drupal bootstrap : Successful
 Default theme    : seven
 Admin theme      : seven
 PHP binary       : /usr/bin/php7.2
 PHP config       : /etc/php/7.2/cli/php.ini
 PHP OS           : Linux
 Drush script     : /usr/local/bin/drush
 Drush version    : 9.4.0
 Drush temp       : /tmp
 Drush configs    : /var/www/example.com/vendor/drush/drush/drush.yml
                    /var/www/example.com/drush/drush.yml
 Install profile  : standard
 Drupal root      : /var/www/example.com/web
 Site path        : sites/default
 Files, Public    : sites/default/files
 Files, Temp      : /tmp

Drush is still reporting 8.6.10

First time we did get the WSOD from https://www.drupal.org/project/drupal/issues/3039408 so we ran composer require twig/twig:1.37.1 to fix it.

So after we ran regular update (current version was 8.6.10), our website crashed. We followed this fix to recover from WSOD https://www.drupal.org/project/drupal/issues/3039408#comment-13018093

After website was restored we tried running all kinds of composer commands to update (like mentioned in question) and it would just spit out "Nothing to install or update".

Solution:

remove "twig/twig": "1.37.1", from composer.json
Run again composer update drupal/core webflo/drupal-core-require-dev --with-dependencies

Updating twig/twig (v1.37.1 => v1.38.2): Loading from cache
Updating drupal/core (8.6.10 => 8.6.13): Downloading (100%)

So, not sure what's going on.

We came across the similar issue while upgrading from 8.6.10 to 8.6.13, try deleting the core and then run

composer update drupal/core --with-dependencies

It should upgrade it to 8.6.13


Form API AJAX refreshes page I need to add some AJAX functionality to a node form. Using hook_form_alter I'm overriding form elements. In this particular case I need to add a callback on the 'language' element provided by the translation module (Core, Content Translation).

However, when selecting a different option in the 'language' listbox, the page refreshes. What could trigger this behaviour?

This is the code I'm using:

function foo_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'bar_node_form') {
    $form['#prefix'] = '
';
    $form['#suffix'] = '
';

    $form['language']['#ajax'] = array(
      'callback' => 'bar_form_callback',
      'wrapper' => 'bar-form-wrapper',
    );

    if (isset($form_state['values'])) {
      drupal_set_message('ajax callback');
    }
  }
}

function bar_form_callback($form, $form_state) {
  return $form;
}

What exactly are you trying to do? Is the page refreshing or the entire $form? What you're asking it to do is by attaching #ajax to the select is that when it changes a value resubmit the entire $form, which would probably include any submit handlers. Typically #ajax would be directed at a form element rather than the entire form.

When you specify 'callback' => 'bar_form_callback', it's not referring to a PHP callback per se. Callback in this case refers to a hook_menu() callback, in other words, the URL that JavaScript will call when the AJAX trigger is fired.

You need to define a bar_form_callback path in your custom_module_menu() function. That menu callback then call function bar_form_callback().

D.O. FAPI reference.


Site search not picking up all pages I've only so far added 5 or so nodes to my site. I've noticed that not all nodes are coming up in the search results. What I mean is searching for their title doesn't find them :S
It works for some but not others. Why would this be the case>

The search table is created on cron job. So the sites that are added before the cron job would be displayed. Could you try running the cron and then try to do the search.

Your site is probably not indexed 100%. You can re-index the site by visiting admin/config/search/settings and clicking re-index.

This will re-index your site on cron run and you will be able to search the content.


Is it valid to use entries in #default_value if they are not in the #options? I have a form. On this form I have a select element, like this:

  array(
    '#type' => 'select',
    '#title' => t('Animals'),
    '#multiple' => TRUE,
    '#options' => array(
      'rat' => t('Rat'),
      'cat' => t('Cat'),
      'dog' => t('Dog'),
    ),
  );

I also have a function called get_suggested_animals($user_id). Let's assume that this code works:

global $user;
print_r(get_suggested_animals($user->uid));

// Array
// (
//    [0] => lizard
//    [1] => cat
// )

Would it be OK to just write:

array(
    '#type' => 'select',
    '#title' => t('Animals'),
    '#multiple' => TRUE,
    '#options' => array(
      'rat' => t('Rat'),
      'cat' => t('Cat'),
      'dog' => t('Dog'),
    ),
    '#default_value' => get_suggested_animals($user->uid),
  );

without testing if default options are on the list of available ones? I know it works (in this example - only 'cat' is selected by default), it does not generate any warnings or anything, but I still feel uncertain if it's legit, or if there are hidden traps I simply don't know yet.

Reading through the code of form_process_select it is obvious that the situation where #default_value is set, but the value isn't a valid option, is not being handled properly:

This piece of code may "fail" in that case:

// If the element is required and there is no #default_value, then add an
// empty option that will fail validation, so that the user is required to
// make a choice. Also, if there's a value for #empty_value or
// #empty_option, then add an option that represents emptiness.
if (($required && !isset($element['#default_value'])) || isset($element['#empty_value']) || isset($element['#empty_option'])) {
  $element += array(
    '#empty_value' => '',
    '#empty_option' => $required ? t('- Select -') : t('- None -'),
  );

In your sample code, you don't set #required for the select field. That is why you don't observe any effect.

However, in the general case, you can't supply a bogus value for #default_value and always be sure that theFAPI will treat it just the same as not set or NULL #default_value.

If change your example and set #required to TRUE, and #multiple to FALSE, you should be able to reproduce a situation where having a bogus default value (such as "lizard") behaves different from the default value being NULL or absent.

I would use something like the below:

  '#type' => 'select',
    '#title' => t('Animals'),
    '#multiple' => TRUE,
    '#options' => array(
      0 => t(' - Select - '),
      'rat' => t('Rat'),
      'cat' => t('Cat'),
      'dog' => t('Dog'),
    ),
    '#default_value' => !empty($default = get_suggested_animals($user->uid)) ? $default : 0,

Using the ? and : in for #default value says that if the first condition is true (the default value is not empty), use that. Otherwise, default to 0 (the select option).


How do I render a form? What is the alternative to drupal_get_form('user_login'). in Drupal 8?

I am using the following code in theme_name.theme, but it doesn't work.

// Include namespace for userLoginForm.
use \Drupal\Core\core\modules\user\src\Form;

function MYTHEMENAME_preprocess_page(&$variables) {
  $form = UserLoginForm::create();
}

drupal_get_form() has been replaced by the form builder service, e.g.:

$form = \Drupal::formBuilder()->getForm(\Drupal\user\Form\UserLoginForm::class);

See the Change Record for more details.

Actually, don't - that change record is incorrect. It'll tell you to pass the form ID, when in fact you need to pass the class string.

Assuming the below is your form class

namespace Drupal\demo\Form;
use \Drupal\Core\Form\FormBase;
class MyForm extends FormBase {
}

You have to create a new instance from your form class first, and pass it to formBuilder's getForm.

$form_obj = new \Drupal\demo\Form\MyForm();
$form = \Drupal::formBuilder()->getForm($form_obj);


How do I link an image field to an pdf file I have a challenge in linking my image to a pdf file. I have a content type with 2 fields, image field which will contain the cover picture and an attachment field which is file of type pdf.

In my view am trying to link an image to attachment so that when a user clicks on the image it open a pdf file.

In some instances where am just using description to link to a pdf file, this what I have put in my Global PHP(Description) output code in my view.
nid, 'filename.pdf');
?>
As soon as click on the description my pdf opens. works fine

But I need to do the same thing with my image, to just click on image then should open my pdf file. Any idea???

Hope this will help you,

In Drupal 7 you can use VIEWS Rewrite results to link an IMAGE to a PDF file.

Steps:

In PDF field, exclude it and change the format to "URL of file"

Go to your VIEW -> Image field and under Link image to select NOTHING
And then go to Rewrite results and check Output this field as a
link and give the path of the PDF file.

You can also use TOKENS by using Replacement patterns for PDF file  path name

You can go to your view>Click on the fild name(image) >After you select from list Link image to the option File.

And that's it.


When/where to include my own function library (like common.inc)? When, hence where, should I include my own library of functions that I will use throughout my whole project.

Drupal has it's common.inc that is included in drupal_bootstrap during the fase DRUPAL_BOOTSTRAP_FULL. I also have a common.inc with functions that I use all the time, in different modules. I want to include this file once so I can use it everywhere without having to include it in each file separatlely.

So what is the right location/hook to do it?

Probably best to put it in it's own custom module, e.g

sites/all/modules/custom/mymodule_common

and enable it as required.

You can make it a dependency of other modules by adding it to those module's .info file, e.g

dependencies[] = mymodule_common

You could also use subfolder and standalone file in sites/all/libraries/common though the module route is recommended.

As requested by Randell here is my own solution:

Make a subdirectory in you site directory, call it "includes" (for example).
Put your file with general functions in this directory (for example common.inc).
Now, in one of your existing modules (I have a module called 'main', where I do all of the general things) add a hook_init function.
In this init function you include your general function file, like so:

require_once DRUPAL_ROOT . '/' . conf_path() . '/includes/common.inc';

The common.inc functions will be available throughout your project.


Draggable views module doesn't sort content I wanna sort my view with Draggable Views Module , but my view display content not field.
is there any solution to sort my views ?

Only solution that worked for me was the following:

go to your content type/vocabulary
add a weight field (label: weight | machine name: weight | field type: integer
edit your sorting view and add sort criteria for your newly added weight field
edit your draggable views field and change "Handler" from Native to FieldAPI
under Field select your weight field
go to your content view and add the new weight field as you sort criteria

This is the only thing that worked for me. If it doesn't work immediately, just reorder a few items on your draggable view so that the ordering values are reset.

Hope this works for you too.

http://www.metaltoad.com/blog/custom-sort-drupal-content-draggable-views-module

see this I think its may be helpful..


Create dependent dropdown in views exposed filter I've created a view of users. It includes two exposed filters as drop downs to filter the list. One is for the city and the other for the squadron. The squadron drop down is related to the cities as cities is a taxonomy vocabulary that gets added to squadrons. I would like to find out if it is possible, that when someone selects a city, to automatically filter the squadron drop down filter by that term.

I did this in a form for creating squadrons using ajax (node/add - with help here: see Dynamic select list in the form (dependent dropdown)) but don't know how to do it (or if it is possible to do) in a view exposed filter.

Many thanks in advance

(edit: I'm using D7 and Views 3)

I haven't check but

{
  $form['computer_stats']['os'] = array(
    '#title' => t('Operating system'),
    '#type' => 'select',
    '#options' => drupal_map_assoc(array('', t('OSX'), t('Linux'), t('Windows'))),
    '#ajax' => array(
      'callback' => 'input_os_verify_ajax_callback',
      'wrapper' => 'input_os_verify_wrapper',
     ),
  );

  // Setting an empty element with a wrapper to be populated.
  $form['computer_stats']['os_verify'] = array(
    '#type' => 'markup',
    '#prefix' => '
',
    '#suffix' => '
',
  );

  // When submitted, check for value of OS, and populate os_verify.
  if (isset($form_state['values']['os'])) { // Fixed this line, was throwing an error in the original video code.
    $form['computer_stats']['os_verify']['#type'] = 'checkbox';
    $form['computer_stats']['os_verify']['#title'] = t('Are you sure you are using @os?', array('@os' => $form_state['values']['os']));
  }

  ...
}

function input_os_verify_ajax_callback($form, $form_state) {
  return $form['computer_stats']['os_verify'];
}

from How to Build Beautiful Forms in Drupal 7 (Video Presentation) might help


How add a custom page template for an article node Hi I want to create an article then define a alias path for it then change template of that page. For example I add an article with title "categories" and no other content like body or image. Then I define "categories" alias for it. Now when I add "page--categories.tpl.php" in my theme template folder nothing happened to page
    http://example.com/categories
and I just see a white page in content region.

Refer this url http://drupalknowledge.blogspot.in/2012/01/different-page-template-for-different.html

You can print  $vars['node'] variable and get the particular node path to give different template.

I hope this will help you.

In template.php theme_preporcess_page() if this fuction exist in template.php otherwise you need to create it .

then function themename_preprocess_page($variables) { you need to print_r($variables); }

for node you can do similar  function themename_preprocess_node($variables) ;

then this array find [theme_hook_suggestions] variable .here in array given page template suggestions ..


How to ajaxify webform submit in Drupal 7? I have tried to alter the webform rendering using hook_form_alter() and hook_node_view() in a custom module so I could add '#ajax' somewhere.

Has anybody already had some experience working with webform and ajax on D6 or D7 ?
I guess the logic would be the same for D6 and D7 then just the implementation changes.

The Ajax Module works for me in Drupal 6.

For Drupal 7:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
      // see if webform_client_form_ is in the form_id
      if(strstr($form_id, 'webform_client_form_')) {
        // get the nid so we can use it in the wrapper value
        $nid = $form['#node']->nid;
        // add the ajax properties to the submit button
        $form['actions']['submit']['#ajax'] = array(
          'callback' => 'mymodule_webform_js_submit',
          'wrapper' => 'webform-client-form-' . $nid,
          'method' => 'replace',
          'effect' => 'fade',
        );
      }
    }

function mymodule_webform_js_submit($form, $form_state) {
      // define the $sid variable (submission id from webform)
      $sid = $form_state['values']['details']['sid'];
      // if we have a sid then we know the form was properly submitted, otherwise, we'll just return the existing $form array
      if ($sid) {
        // first we have to load up the webform node object
        $node = node_load($form_state['values']['details']['nid']);
        // create an array up with the confirmation message, retreived from the webform node
        $confirmation = array(
          '#type' => 'markup',
          '#markup' => check_markup($node->webform['confirmation'], $node->webform['confirmation_format'], '', TRUE),
        );
        // return the confirmation message
        return $confirmation;
      }
      else {
        // return the form
        return $form;
      }
    }

See if the Ajax module can help you with that.  See the documentation as well


How to put google map field in my form of my custom module? i like to build a form field based on google map, where user can put in their address, city and country, then the map will automatically search for it.
and then you can put a pin to define the exact location, which the expected output is latitude & longitude which will be saved during form submit.

how to approach this? is there any module in Drupal 8 that i can use during form generation?

maybe something like:

 $form['map'] = array(
      '#type' => 'gmap',
      '#otherProperty' => propertyValues,
 );

Thank you,
AnD

use this
it works for me
https://www.drupal.org/project/google_map_field
.
.
.
.
.
.


How to add block-like visibility settings to nodes? I have created a custom content type 'campaign' in my module using hook_node_info() and added fields using hook_field_group_info(). This campaign content type will be shown to users site wide in modals/pop-ups using CTool modal on page load (hook_init()).

What I'm looking for is, to give an option to admins to restrict this pop-up/modal for different roles or paths. Same like block section is doing. For example whether to show a block on node/104 or not, or wether to show a block for (anonymous) users only or not. Like shown in the screenshot below.

My aim is that, while creating 'campaign' nodes, admins should be able to select pages or roles to show that particular campaign or not.

Can you please guide me how can I use Drupal block logic here? Or do you maybe can make some code suggestions I can start with in my custom module?

Block visibility rules are kind of fundamentally different from nodes in that nodes are intended to always show up using the "full" or "default" display mode in the main content block/region of the specific node's unique URL. On the other hand, blocks go hand-in-hand with the ability to be placed in any region on any page.  Block visibility can group permissions (ie role based rules)  along with path-or-url-based rules, but nodes cannot natively do this.

I can think of three possible alternatives (there might be more):

1) Embed Nodes in a block using one of these modules, and then use block visibility rules to place it.  This has the drawback that you have to tie things together quite manually in two places.

2) If you're showing campaign nodes on other nodes, then you can use an entity_reference field to reference the campaign node from another node (or vice versa)  and then just set the entity reference field's display settings to render the entity as if it were a field on the node.

3) Write a completely custom solution to mimic block visibility rules for nodes.  I'd start with a Text (long) field (call it field_campaign_urls),  then in a node_form_alter() hook alter the display to show up in a vertical tab (or you could use Field Group module to do this in the UI).  Then you'd need to implement a hook that gets called on all pages, e.g. hook_page_alter test the internal Drupal URL (and optionally also the pathauto alias) for a match against all values in the field_campaign_urls database table. The challenge here will be writing the wildcard functionality, you'll need to figure out how to convert  some/url/* into a database condition LIKE 'some/url/%'  This is also where you might want to start digging into the block.module code to find out more about the internal structure of how block visibility query logic works.   Finally, you'll need to combine this logic with your custom node access logic as well.  And indeed figure out which block region you want to add your node to.  You may leverage drupal_add_region_content to add your rendered node to a specific region.

For any content which is created by custom/added from drupal admin UI, Access control can be enabled from Content Access module.


How to count the number of calls to a rest service? I created a rest service which every user on the site calls from a product we are selling.

How do I count the number of calls for every user so I can generate a report of this.

D8

Do your REST service needs authentication?

If yes, you just log each access attempt by users:
One attempt per one record per user or one record per user and updating the count column always.

If there is no authentication, you will have harder time to achieve this.
It would be also good to know HOW they are making this rest calls (eg: clicking on a button which resolves into a rest call?).

You could still try to check session and find out which user made the requeset.

You can create a new Content Entity. With this entity you can save all calls on the rest service (p.e. user, url or product, time, ...).

Drupal creates a database table for each entity and with the ContentEntityBase it is easy to save new entries, read all entries, read part of the entries, search or whatever you want to do.

There exists a big introduction & documentation

Addition

When you save all the calls you can easy read the calls out with the entity. And based on the informations you have saved, you can count the number of calls to your rest service and you can generate the report.

Code Examples

Create the module-folder example_module in modules/custom
Add the info-file:

modules/custom/example_module/example_module.info.yml

name: EXAMPLE MODULE
description: YOUR DESCRIPTION
package: YOUR PACKAGE

type: module
core: 8.x

Add the Class to create your entity

modules/custom/example_modules/src/Entity/ExampleEntity.php

<?php
namespace Drupal\example_module\Entity;

use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityTypeInterface;

/**
 * Defines the Example Module entity.
 *
 * @ingroup example_module
 *
 * @ContentEntityType(
 *   id = "example_entity_name",
 *   label = @Translation("Example entity"),
 *   base_table = "example_entity_name",
 *   entity_keys = {
 *     "id" = "id",
 *     "user_id" = "user_id",
 *   }
 * )
 */
class ExampleEntity extends ContentEntityBase {

  /**
   * {@inheritdoc}
   *
   * Define the base fields.
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {

    // Standard field, used as unique if primary index.
    $fields['id'] = BaseFieldDefinition::create('integer')
      ->setLabel(t('ID'))
      ->setDescription(t('The ID of the entity.'))
      ->setReadOnly(TRUE);

    // Save user_id as a string
    $fields['user_id'] = BaseFieldDefinition::create('string')
      ->setLabel(t('User'))
      ->setDescription(t('The associated user.'))
      ->setSettings([
        'max_length' => 255,
        'text_processing' => 0,
       ]);

    // You can replace the fields or add more. Feel free!

    return $fields;
  }
}

Enable the module: $ drush en example_module
Use the entity to save or load content. For example in a Controller of the rest service.

// Somewhere above the Controller
use Drupal\example_module\Entity\ExampleEntity;

// Create a new entry
$user_id = Drupal::request()->get('user');
$entityContent = array(
  'user_id' => $user_id,
);
$exampleEntity = ExampleEntity::create($entityContent);
$exampleEntity->save();

// Load entries by user_id
$entityTypeManager = Drupal::entityTypeManager();
$exampleEntityStorage = $entityTypeManager->getStorage('example_entity_name');
$entries = $exampleEntityStorage->loadByProperties($entityContent);
// Now you can count the entries.

Be careful, there are different ways to work with Drupal and different ways where to place your own code. Without seeing your code base I can only help with this "default way".


How to disable 'promote to front page' and 'sticky' options? Two possible methods that I have explored:

Use hook_form_alter to unset both options on node edit forms. But on the main admin content page, the options still appear under 'Update options' dropdown.

Use Override Node Options module. This provides granular control, but it means disabling the 'Administer content' permission. Users then can't see the 'Update options' at all, which they still need in order to bulk publish, delete, etc.

There are 3 places, where those options can be seen:

on admin/structure/types/manage/article, for the "Article" content type

on node/2/edit, for the node with ID equal to 2

on admin/content, between the "Update options"

If you need to remove the options from those setting/administrative pages, then you need to alter the following form builders:

node_type_form()
node_form()
node_admin_nodes()

node_admin_nodes() is the form builder for the node administration overview in admin/content, which includes the "Update options" field that allows the users with the right permission to promote/demote a node from the front page, and to make a node sticky. The field lists all the node operations implemented by modules; in the list of the operations obtained with $operations = module_invoke_all('node_operations'), those operations are represented from $operations['promote'], $operations['demote'], $operations['sticky'], and $operations['unsticky'].

I suspect you could implement a hook_node_presave and set those to 0.  This should override any possible way to set these.

You could also try to hook_form_alter the form used on that admin page and remove those options.


Region on specific page Is it possible to set a region on a specific page? I've created a page and I only want it to display it there and not elsewhere.

Create View Block.

Go to Home » Administration » Structure » View

Add New View.

Create a Block with View (Not Create a Page)

Then, Select that block on the specific page.

If you have created that page with Panels or Node Template (By Adding New Variant)
You can set View Rule.

Add Visibility Rule in View Block

Select String: URL Path as an Option

Then, set path to your page where you wanted to display your block.

I hope this will help you..

You can restrict the display of the blocks to pages, content types, roles, languages.


How to do simple subtraction in Computed Field? I'm trying to calculate the price difference between old price and new price, and if the price has dropped to display by how much, both Nominally and in Percent.

So, basically these are 2 simple formulas that should look like this:

  NOMINAL PRICE DROP = field_price_original - field_price_new

  PERCENTAGE PRICE DROP =  ( (field_price_new - field_price_original) /
  field_price_original ) * 100

I tried setting this up through Rules (unsuccessfully), but it seems that doing it through Computed Field will not be so heavy on the server.
Using Computing Field I have the following formula:

  $entity_field[0]['value'] =
  array_pop(array_pop(field_get_items($entity_type, $entity,
  'field_price_original'))) -
  array_pop(array_pop(field_get_items($entity_type, $entity,
  'field_price_new')));

The number is set as float, 10.2.   But for some reason it doesn't work.

Can someone please help and provide the correct syntax for Computed Field?

As per the documentation of computation field module to calculate the difference of two fields you need to use the PEAR:

$path = '/pathToPearsParentDirectory/pear/PEAR';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);

require_once 'PEAR.php';
include_once "Text/Diff.php";
include_once "Text/Diff/Renderer.php";
include_once "Text/Diff/Renderer/inline.php";

$diff = &new Text_Diff('auto', array(array($node->field_nameOfOneFieldToCompare[0]['value']), array($node->field_nameOfOtherFieldToCompare[0]['value']))); $renderer
= &new Text_Diff_Renderer_inline();

$node_field[0]['value'] = $renderer->render($diff);

More info about it available here http://arencambre.com/blog/2009/05/17/how-i-got-field-diffs-working-with-drupal-pear-text_diff-and-dreamhost

$entity_field[0]['value'] = $entity->field_price[LANGUAGE_NONE][0]['value'] - $entity->field_cost[LANGUAGE_NONE][0]['value'];


Dealing with node language when manually updating node I'm trying to manually update a node and I'm not sure how the language works.

The node is in English, so $node->language = 'en';

However, all my fields data are organized like this in the node:

$node->field_name['und'][0]['value']

I thought 'und' means "language undefined", so shouldn't it be 'en' instead?

I'm trying to automate the process so is it safe to assume fields will always use 'und' in nodes?

Yes - it is safe to assume this. The locale module will deal with this by setting it to the language code of the default language, ex 'en'.

Citing from: http://drupal.org/update/modules/6/7#drupal_language_none

In Drupal 7, the LANGUAGE_NONE constant should be used for nodes or other items that do not have a specific language associated with it.

http://api.drupal.org/api/drupal/includes--bootstrap.inc/constant/LANGUAGE_NONE/7

Instead of specifying a language, I prefer to just use entity_metadata_wrapper().

For example:

$node = entity_metadata_wrapper('node', SOME_NODE_ID);
$value = $node->field_something->value(); // returns field value
$node->field_something->set('new value'); // sets field value
$node->save();

Source: https://www.drupal.org/docs/7/api/entity-api/entity-metadata-wrappers


From local server to web hosting I have created a website on local with bitnami. Now I want to upload it to a web server (probably on hostgator).

I don't care about content. The site is empty and I will add content only when I upload it.

I just want to keep the settings, permissions, content types and modules. So, I can start add content on air.

If I copy paste the htdocs folder with ftp in the server, this will work?

The simple way, (used to do all this useless stuff before GIT and capistrano...)

Copy/upload all (hidden) the contents of your Drupal folder in the public_html or whatever your server document root is for that site.

Export your local database in a dump file.

Create a mysql database on the live server, import the local dump.

Edit the sites/default/settings.php file on your live server to serve your new database credentials.
Edit the .htaccess file on the live server to your needs.

Visit your site.Clear the cache tables.

Set the correct permissions on settings.php (check status reports for errors) and the desired setUp on sites/default/files etc for file uploads

That's all

If I copy paste the htdocs folder with ftp in the server, this will
  work?

Not without the database; You have to import the database too, and then (if you really don't need the contents) delete them manually (there are a lot of ways to do that in bulk, like views bulk operation or a custom module that delete all contents you don't need).

Otherwise you can try Features module, where you can export all your fields/settings on a fresh install; but if the site has a bit of complexity I dont know if it will do the trick.


Drush enable module | not working | Drupal 7 on WAMP with PostgreSQL Based on
Drush on windows - Command pm-enable needs a higher bootstrap level to run, i have the following question.

I have the same problem found here https://drupal.org/comment/8533097 except I am using Postgresql and this solution did not work for me.

My Drupal installation is at: C:\SiteData\WebDev\gitproject (aka DrupalRoot). I successfully ran drush status in "[DrupalRoot]\sites\site1.example.com, but when I try to enable a module using drush en ccl and I get the following.

  Command pm-enable needs a higher bootstrap level to run - you will
  need to invoke drush from a more functional Drupal environment to run
  this command. The drush command 'en ccl' could not be executed.
  Drush was not able to start (bootstrap) the Drupal database.

  Hint: This may occur when Drush is trying to:

  bootstrap a site that has not been installed or does not have a  configured database. In this case you can select another site with a
  working database setup by specifying the URI to use with the --uri
  parameter on the command line. See drush topic docs-aliases for
  details.
  connect the database through a socket. The socket file may be wrong or the php-cli  may have no access to it in a jailed shell. See
  http://drupal.org/node/1428638 for details

  Drush was attempting to connect to:

  Drupal version         :  7.26
  Site URI               :  http://site1.example.com
  Database driver        :  pgsql
  Database username      :  user
  Database name          : site1dev
  Default theme          :  garland
  Administration theme   :  garland
  PHP executable         :  php
  PHP configuration      : "C:\Program Files (x86)\Drush\Php\php.ini"
  PHP OS                 :  WINNT
  Drush version          :  6.0
  Drush configuration    :
  Drush alias files      :
  Drupal root            : c:/SiteData/WebDev/gitproject
  Site path              : sites/site1.example.com
  File directory path    : sites/site1.example.com/files

My settings.php file looks like this.

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'site1dev',
      'username' => 'user',
      'password' => 'secretpw',
      'host' => '127.0.0.1',
      'port' => '',
      'driver' => 'pgsql',
      'prefix' => 'dev_',
    ),
  ),
);

if (php_sapi_name() == 'cli') {
  $db_url = 'pgsql://user:secretpw@127.0.0.1/site1dev';
 }
 else {
   $db_url = 'pgsql://user:secretpw@localhost/site1dev';
 }

I have used both the "Drush Command Prompt" and "MINGW32" git command line tool and both work for "drush status" or "drush dl " but not for "drush en "

One last comment.  looking at the settings.php file permissions in MINGW32 they show the unix permissions of -rw-r--r--.. Tried changing this in using chmod but doesn't work on a windows file (not even sure that makes a difference).

I'm not on Windows or using postgres today, but I can suggest how to debug:

What you've got right now is that your cli environment seems to be failing to connect to the database correctly.
Checking your database-level access from drush, using verbose (-v) debug (-d) feedback may provide clues.

For instance, given your current failure, I would run

  drush -v -d sql-cli

that will, among other things, show you the exact database connection command being attempted that is failing.

You can then copy that yourself, run it again,  and see what variations of that
   command will and will not work. One of the more common issues seems
   to already be covered (the difference between 'localhost' and
   '127.0.0.1' depending on installation and version issues. There may
   be other issues such as 'cannot locate postgres.exe in the current
   $PATH' or whatever.

This is not an answer to the question, but a suggestion on how to get clueful when a (any) drush command just doesn't work. You can also use the -vd flags on your 'en' command, though I don't know how conclusive the feedback you get there will be.

Add mysql to global path. Worked for me.


Drupal Hook_Mail_Alter Custom Template fields We have a Drupal 6 contact us Webform with e-mail.  There is a custom template with the following fields:
Facility: %value[facility]
First Name: %value[first_name]
Last Name: %value[last_name]
Email: %value[email_address]
Phone: %value[phone_number]
I wish to be contacted: %value[contact_user]
Subject: %value[subject]
Comments: %value[comments]
The results of this submission may be viewed at:
%submission_url

I want to access both the subject and the facility field.  I'm not sure my keys are correct using "headers".  Is this the correct way to access both the subject and facility fields?

Here is my code in the custom module test:

test_mail_alter(&$message)
{

    if (($message['id'] == 'contact_us'))
    {
        $mail_listing = array();

        // pick up subject e-mails
        $subject = str_replace(' ','',$message['headers']['subject']);
        $subject_listing = explode(',',$subject);
        foreach ($subject_listing as $s){

            if (preg_match('/[a-zA-Z0-9_-.+]+@[a-zA-Z0-9-]+.[a-zA-Z]+/',$s)){
                array_push($mail_listing,$s);
            }

        }

        // pick up facility if it exists and combine it with the subject listing
        $facility = str_replace(' ','',$message['headers']['facility']);
        $facility_listing = explode(',',$facility);
        foreach ($facility_listing as $f){

            if (preg_match('/[a-zA-Z0-9_-.+]+@[a-zA-Z0-9-]+.[a-zA-Z]+/',$f)){
                array_push($mail_listing,$f);
            }

        }

        $message['headers']['to'] = implode(',',$mail_listing);
    }
}

In Drupal 6, you can specify further settings:

Navigate to the Contact Form settings page (http://example.com/admin/build/contact/settings)
In the "Additional Information" section, enter the text to display with the contact form.
In the "Hourly Threshold" list, select the maximum number of submissions that a user can make per hour.


Form handler submit don't work I have a submission handler for my custom form that doesn't work. I tried many solutions, but nothing works.

My_Custom.module

 [...]
function tournament_menu() {
    $items['tournament/newteam'] = array(
        'title' => 'Créer une nouvelle équipe',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('form_newteam'),
        'access callback' => TRUE,
        'file' => 'form_tournament.inc',
    );
}
 [...]

form_tournament.inc

function form_newteam ($form, &$form_state) {

 [...]
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Créer',
    );
    $form['actions']['submit']['#submit'][] = 'form_newteam_submit';

    return $form;
}

function form_newteam_validate($form, &$form_state) {
    //Validation logic
}

function form_newteam_submit($form, &$form_state) {

    drupal_set_message("Bla bla submit !");

}

My validation function works.

I try all this code In form_newteam() function.

$form['actions']['submit']['#submit'][] = 'form_newteam_submit';
$form['#submit'][] = 'form_newteam_submit';
$form['#submit'] = array('form_newteam_submit');
$form['submit'] = array(
 '#type' => 'submit',
 '#value' => 'Créer',
 '#submit' => array('form_newteam_submit'),
);

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => 'Créer',
  '#submit' => 'form_newteam_submit',
);

Go back and scrutinize your validation function. The code you are showing here actually works, so the problem is something you did not include in your sample.

For the reference, the working implementation over here is:

function form_newteam ($form, &$form_state) {
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Créer',
    );

    return $form;
}

function form_newteam_validate($form, &$form_state) {
    drupal_set_message("valid");
}

function form_newteam_submit($form, &$form_state) {
    drupal_set_message("submit");
}

Please note that your function names do not conform to the drupal coding standards. Function names must be prefixed with the module name. Therefore you should name your functions like this: tournament_newteam or tournament_newteam_form. If those are administrative forms, stick them into tournament.admin.inc otherwise place them into tournament.pages.inc.

try

function form_newteam_submit(&$form, &$form_state, $form_id = 'form_id') {

    drupal_set_message(t('Bla bla submit !'), 'status');

}


Difference between $form_state['values'] and $form_state['input'] Can someone please tell me the difference between these two variables?

$form_state['values']
$form_state['input']

Optionally some example of action they are used with. I'm wondering especially about using with ajax in drupal form. Which of these should I use in ajax callback to get input values from the form?

The crucial difference here is that in most cases you should be using $form_state['values']; since the data on the $form_state['input'] array is raw and unvalidated.

$form_state['input'] is useful for multi-step forms, assuming you are familiar with how to safely handle raw input.... See form_builder for more information...

In the drupal_form_submit function, you can see the following code :

// Populate $form_state['input'] with the submitted values before retrieving
// the form, to be consistent with what drupal_build_form() does for
// non-programmatic submissions (form builder functions may expect it to be
// there).
$form_state['input'] = $form_state['values'];

So it is exactly the same.


How can I have the JS/CSS cache refresh on every page load? How to clear cache on every page load?

I am doing CSS & JS theming and currently having to manually clear cache (using devel module) every time and then reload the page again to see my changes?

How do I do it so that in every page load cache is cleared?

As long as you don't have JS or CSS aggregation turned on, you shouldn't have to clear cache to see your changes to existing files. You can see this settings by going to;

Admin->Config->Development->Performance(admin/config/development/performance).

If you are adding new CSS or JS files, you'll probably have to clear cache to register them with the theme system.

If you really want to clear cache on every page load, you should create a custom module that implements hook_init() and runs drupal_clear_css_cache() and drupal_clear_js_cache() (or any other cache clearing functions you may want), but this should be unnecessary.

This is not a perfect solution.
But you can use this in dev stages

Copy/Paste this code in your themes template.php

function YOURTHEME_preprocess_page(&$variables) {
  global $base_root
  include_once $base_root.'/includes/bootstrap.inc';
  drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
  drupal_flush_all_caches();
}

Try and let me know the status.


Alter checkboxes values in a webform How can I alter the key/value items of a checkboxes component in a webform?
I've followed this answer and I successfully altered a select list component for both render and submission.
I'm trying to do the same with a multiple choice component, but although the form is rendered correctly, the values are not saved on submission.
This is my code:

function my_form_webform_client_form_30_alter (&$form, &$form_state) {
    $form = mycustom_form($form);
}

function mycustom_form($form){
     $form['#validate'][] = 'mycustom_webform_validate_form';
     $form['#submit'][] = 'mycustom_webform_submit';
     dpm($form['submitted']['code']['#options']); // ('0'=>'a value', '1'=>'another value');
     $codes = array('foo', 'bar');
     foreach ($codes as $key => $value) {
        $form['submitted']['code']['#options'][$value] = $value;
     }

return $form;
}

function mycustom_webform_validate_form($form, &$form_state) {
dpm($form_state['values']['submitted']);
// selecting all checkboxes I get all the four values
}

function mycustom_webform_submit($form, &$form_state) {
  drupal_set_message('<pre>' . print_r($form_state, true) . '</pre>');
// only 'a value' and 'another value' are submitted
}

UPDATE
I even tried to add some values to the initial form and manipulate them programmatically.
The submission result is like no manipulation was done.
I update my code for a better explanation.

UPDATE 2
I've tried dumping the submitting form.
I updated my code with the results.

UPDATE 3
I confirm that removing the "Multiple" flag from the component, causes the issue to be fixed.
Unfortunately I need a multiple answer, so I can't remove it.

UPDATE 4
This is another solution I'm trying, using hook_webform_select_options_info():

function mycustom_webform_select_options_info() {
    $items = array();

   if (function_exists('_mycustom_users_options')) {
        $items['code'] = array(
        'title' => t('User codes'),
        'options callback' => '_mycustom_users_options',
      );
 }

  return $items;
}

function _mycustom_users_options() {
  $output = array();
  $codes = mycustom_user_codes(); // <- these values are based on logged user
  foreach ($codes as $key => $value) {
    $output[$value] = $value;
  }
  return $output;
}

function mycustom_user_codes() {
      $result = // a db query based on user id;
      while($usercode = db_result($result)){
         $output[] = $usercode;
      }

      return $output; // array({[0] => 'a value', [1] =>'another value'})
}

I've just tested the following code out locally and it "works", with the exception that when I view the submission results as an administrator, I see the original keys and not the keys that were altered when the form was displayed (which is what I would expect).

function my_custom_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'webform_client_form_12') { // yours is different
    // 'options' is the component name for a multiple-checkbox component.
    $form['submitted']['options']['#options'] = array(
      1 => 'Foo',
      2 => 'Bar',
    );

    $form['#submit'][] = 'my_custom_submit';
  }
}

function my_custom_submit(&$form, &$form_state) {
  dpm($form_state);
}

dmp($form_state) showed me that the checkbox I had picked was indeed the one that was checked, and when I look in the database in webform_submitted_data I can see that the record  shows the proper value that I checked:

nid sid cid no data
12  12  2   0  2

where data = 2 shows the checkbox that I picked in my altered options (I picked "Bar").

Since the subsequent submission display is going to show the keys as they currently exist, it's showing me that I picked the original value for option #2. If I change that to "apples" in the component and then refresh the submission, it shows the 2nd option as "apples". So I could follow this up with another hook_webform_submission_render_alter() or hook_webform_submission_load() to change the options being displayed on submission view so as to be appropriate to who the user was that filled out the webform.

My suggestion would be to instead build your own form, since it sounds like you have more than one dynamic aspect for what you need, and store the data that will be dynamic as a serialized array in a 'data' column in your own table.

YOu need to pass $value by reference   not by value, you should do it with &$value
read more.

foreach ($codes as $key => &$value) {
              $form['submitted']['code']['#options'][$value] = $value;
            }


How to use Services Basic Authentication? How to use Services Basic Authentication module?

I want to add http basic auth for my service. I have installed it and enabled it on my end point configuration. I got this "HTTP basic authentication Services_basic_auth has no settings available" in my end point configuration. where is the setting page?

The module authenticates a web service call against drupal accounts.

Enable the module
Setup a drupal user
Make the web service call with the credentials of the user.

Note that with basic auth, the credential can be intercepted if SSL isn't used.

The module uses the standard PHP authentication headers and submits the standard drupal login form, without checking for any specific roles or permissions. So any drupal user will work.

Make a test web-service call with curl or wget to test it. There are also instructions in how to call with PHP in the call with curl stackoverflow answer.

Don't forget to use content access module.

Adding additional details per MPD's request.

If you are not using the content access module then the user will see all the content including created by others which they were not supposed to see.  For example, user A has stored personal data that user B is not supposed to see or wise versa.   The Services Basic Authentication module enables the auth but doesn't enforce the content access.  Content Access module enforces that.   If you are not using the content access control then there is no point in authenticating a user.


How to get the product id on hook form alter I am currently working on drupal 8 commerce. I need to form alter some of the expose fields but need to get the product id first so I can get my condition on the product fields. I used this kint($form_state) on my form alter to show the attached image. But when I try use this $form['storage'] im having wsod. Thanks

If You alter 'Add to card form', try this code

$form_state->getFormObject()->getEntity()->getPurchasedEntity()->product_id->getString();

I figure it out. Since it is a product page I used this code instead
$product = \Drupal::routeMatch()->getParameter('commerce_product')) && is_object($product);


language back to default language after Ajax reload To simplify the question and maybe reproduce the problem, I made a simplier version of what I am doing. I have a form field with ajax. When it triggers it reloads a small piece of html. In it is t('text in one of tree languages'); If I open the page for the first time the same html is loaded and it is in the correct language. But after the reload from the ajax call it is in the website's default language. This only happens when logged in. It is possible that this has to do with the administrator language module. Any help would very much be appreciated.

Ajax Code at hook_form

function hook_form($form, &$form_state) {
  $form['update'] = array(
    '#value' => t('Update'),
    '#type' => 'button',
    '#ajax' => array(
              'callback' => 'callback_function',
              'wrapper' => 'div-to-replace',
              'method' => 'replace',
              'effect' => 'fade')
  );

  // Other form elements

}

Ajax callback function

function callback_function($form, $form_state) {
    return t('test string that should get translated');
}

The ajax callback should return the dynamic form element (and not directly the value). I've created some sample code where the translated content / string is correct after an ajax reload.

function YOURMODULE_form($form, &$form_state, $file_group)
{
    $form['update'] = array(
        '#value' => t('Update'),
        '#type' => 'button',
        '#ajax' => array(
            'callback' => 'YOURMODULE_form_ajax_cb',
            'wrapper' => 'ajaxWrapper',
            'method' => 'replace',
            'effect' => 'fade'
        )
    );

    $form['ajax'] = array(
        '#type' => 'container',
        '#attributes' => array(
            'id' => 'ajaxWrapper',
        ),
    );

    $form['ajax']['text'] = array(
        '#type' => 'markup',
        '#markup' => t('My translated string'),
    );

    // Rest of the form
}

function YOURMODULE_form_ajax_cb($form, &$form_state)
{
    return $form['ajax'];
}

Having the same problem. On ajax callback t function is complealty ignored and strings are not even on TI.  I can enforce them to appear in TI using locale function, but then I also need to pass language to it. What is the real problem is that I can't pass language to ajax callback, whenever I try to pass it, it goes to default english.


Where do I put a custom function for multiple themes I have two 2 themes so two template.php. I have a function that I use in both themes. I don't want to write it twice.
Where do I put it ?

You can put it in a module, or set up your themes so that they are sub themes of a main theme.

What about creating a function.php and in default/settings.php writting "require 'function.php';" ?


How to get node id from URL? I want to pass a URL to a function. This function should get the node ID from the URL.

How to do this?

You can try the following code (please note that about-us is merely an example page - you can put whichever page you want here):

$url = 'about-us';
$path = drupal_lookup_path('source', $url);

if ($path) {
  $node = menu_get_object('node', 1, $path);
  return $node->nid;
}
else {
  //Error handling in case path provided does not exist
}

The code above returns a whole node object though, which might be expensive depending on how often you run it - another option would be to run explode() on the output of drupal_lookup_path() and just take the NID that way.

References:

drupal_lookup_path();

menu_get_object();

Pass the variable (node id) appending it to url like this:

    <?php
    $nodeid = $node->nid;
    ?>

<a href="http://www.mysite.com?nodeid="<? php print ($nodeid) ?>">

and then in  get the value from url like:

<?php
$nodeid=$_GET["nodeid"];
?>

And then pass the value to the function.

http://php.net/manual/en/reserved.variables.get.php


Drupal Image and GalleryFormatter I am using the Image and the Galleryformatter module. I am getting these two errors on configure media page:

Warning: Division by zero in theme_image_style_preview() (line XXX of /.../modules/image/image.admin.inc).

Warning: array_intersect_key(): Argument #1 is not an array in theme_image_style_preview() (line XXX of /.../modules/image/image.admin.inc).

I found @Sohail to be almost right. I did:

chmod 777 drupal/sites/example.com/files/styles

and the error went away and my drupal 7 new image-style worked. I did not have a styles or even a files folder in druapal/sites/all/files

Found a solution. Just run the following on shell:

sudo chmod -R 777 files

http://drupal.org/node/873838


How do I retain the query string after login? I need the user,opening a certain page of my site (www.foo.com/page_to_visit), to login and then go to the requested page, so I set up an hook_menu for this specific page and a callback. In the callback I added this code which works

drupal_goto('user', array('query'=>drupal_get_destination()))

but if the url contains query strings (www.foo.com/page_to_visit?id=12&od=12) they are removed. I mean that, after login, the user gets redirected to www.foo.com/page_to_visit instead of www.foo.com/page_to_visit?id=12&od=12. How do I avoid this behaviour?

UPDATE: Drupl_goto has something supporting this. Produced this code, following documentation

$args = array();
$params = $_GET;
$args[] = $params['q'];
unset($params['q'], $params['destination']);
if (count($params) > 1) {
  $pippo['query'] = $params;
  $args[] = $pippo;
}
drupal_goto('user', array('query'=>$args));

$args results in --->
Array
( [0] => page_to_visit
  [1] => Array
    ( [query] => Array
            ( [id] => 12
              [od] => 12
            )
    )
)

The result is odd for the redirect looks like
    http://www.foo.com/user?0=page_to_visit&1[query][id]=12&1[query][od]=12

I think, my suggestion is :-

alter login form
add a hidden field for destination URL.
add submit handler  like $form['#submit'][] = 'destination_redirect_handler'
use drupal_goto('destination_redirect_url') in this destination_redirect_handler

Modify your call to drupal_goto() like this:

drupal_goto('user', array('query'=>drupal_http_build_query($args)));

drupal_http_build_query() builds a formatted query string from an array.

Hope this helps.


Create a pager with "Yesterday", "Monday", "Sunday" etc I have a view which through contextual filters show content created on the current day, and I would like to add a pager to allow users to go back in time one day at a time.

Say we visit the site on a Tuesday. So when viewing today's posts there is one link to the left which says "Yesterday" and no link to the right (since there are no future posts), and when this link is clicked we are show yesterdays content (Monday). The links are now "Sunday" to the left and "Today" to the right. Again we click the left link and are shown the content created on Sunday, and the links now show "Saturday" to the left and "Yesterday" to the right.

I've tried using exposed filters but they only output drop downs and only let me sort by asc/desc.

Is this possible?

Contextual range filter module ( https://drupal.org/project/contextual_range_filter ) seems to be the most suitable option as per the above requirement, or you can try the views day of week module ( https://drupal.org/project/views_dow ).

I have created a view for day archive by using the contextual filter of view (without using the above modules) as below below:

but as your requirement seems to be creating a archive on the basis of week day therefore the best would be to use the above(Contextual range filter module, or the view day of week module), and than you can found the filter in the contextual filter of your view.

Yes it's possible. Just create a new views pager plugin as the default ones:

http://api.drupal.org/api/views/plugins!views_plugin_pager.inc/group/views_pager_plugins/7

I will need some custom coding to figure out the day of the week but it seems not really hard.


Why I not get value from $form_state['values']['field_form_name'] I created module_templat with code:

<?php

 function module_template_menu(){
    $items = array();
    $items['them-noi-dung'] = array(
        'title' => t('Khai báo hóa chất'),
        'page callback' => 'drupal_get_form',
        'page arguments' => array('module_template_select_form',2),
        'access callback' => true,
    );
    return $items;
    }

function module_template_select_form($form, &$form_state){
    $form = array();
    $form['select'] = array(
        '#type' => 'radios',
        '#title' =>'Lựa chọn hình thức khai báo',
        '#options' => array('0'=>t('Khai báo lần đầu'), '1'=>t('Đã từng khai báo')),
        '#default_value' => '0',
    );
    $form['ma_so_thue'] = array(
    '#type' => 'textfield',
    '#size' => '20',
    '#title' => 'Vui lòng nhập vào Mã Số Thuế',
    '#states' => array(
        'visible' => array(':radio[name="select"]' => array('value'=>'1'),
                    ),
            ),
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Tiếp tục'),
    );
    return $form;
    }

function module_template_select_form_submit($form, &$form_state) {
    $select = $form_state['values']['select'];
    $masothue = $form_state['values']['ma_so_thue'];
    if(isset($select)){
        $masothue = $form_state['values']['ma_so_thue'];
        $form_state['redirect'] = 'node/add/khai-bao-hoa-chat';
        }
    }

function module_template_form_alter( &$form, &$form_state, $form_id ){
    $masothue = $form_state['values']['ma_so_thue'];
    if ($form_id == 'khai_bao_hoa_chat_node_form') {
        $form['field_ten_to_chuc']['und'][0]['value']['#default_value']= $masothue;
        }
    }
function module_template_theme($existing, $type, $theme, $path) {
    $items = array();
    $items['khai_bao_hoa_chat_node_form'] = array(
        'render element' => 'form',
        'template' => 'khai-bao-hoa-chat',
        'path' => drupal_get_path('module', 'module_template'),
        );
    return $items;
    }

Why I  can not get value of $form_state['value']['ma_so_thue'] in module_template_form_alter(&$form, &$form_state, $form_id) when form submited?

The code you are showing is wrong for two reasons:

hook_form_alter() is invoked for every form Drupal is showing; this includes Drupal core forms, as well as forms implemented by third-party modules. It is not invoked for the forms of your own module. So, you first need to check for which form the hook is being invoked, then you can access the form fields the form of your module is using.
hook_form_alter() is not invoked when the form is submitted, but before the form is rendered. So you cannot use $masothue = $form_state['values']['ma_so_thue']; there. You need to add a new submission handler from hook_form_alter(), and in that submission handler you can get the submitted values, but then you cannot alter the default value for a form field in a submission handler.

$store_name = $form_state->getValue('name')[0]['value'];

Some input files are multi-value, so you can just use getValue('field_name').


Views contextual filter if field value is X then show this in views page Y I have content type Ads.
I have multiple views pages.
I have Views which shows this content type Ads as a view block. Views has multiple block displays, each display for each views pages.

Admin need to choose when adding new node Ads where he want this ad to be shown. He need to choose it from the list. List has for example values X, C, Z

In the Views which shows these Ads as a view block. How to configure contextual filter to check field value? Contextual filter should be set on PHP code - but how to code it?

For example:

If field value is X -> show this view block on the path: categories/x (which is Views page, not node!)

** Solution **

I found my own solution to do something like this.

Added custom manual list field type (field_category). For example: X, Y and C
Add view block for each ad category and set filter field_category for each category. (field category = X)
Then in admin/block edit view block: Show block visibility, set PHP format and added this code:

<?php
if (arg(0) == 'products' && arg(1) == 'categoryX') {
return TRUE; }
else { return FALSE; }
?>

As my views pages path are: products/categoryX.

This sounds like a job for Page Manager (part of C-Tools).
Create variants that activate on content type AND field value.


Extending form validation functions How do I pass additional values to #element_validate so they can be used for validation?

I'm using hook_form_alter() and Drupal 7.

//Example 1
function my_validation_function($form, &$form_state) {
    //Validation Code
}

I would like to use:

//Example 2
function my_validation_function($form, &$form_state, $additional_values) {
    //Validation Code with access to $additional_values
}

This works for example 1:

$form['field']['#element_validate'] = array('my_validation_function');

How do I pass $additional_values to example 2 using $form['field']['#element_validate']

function where_ever_extra_data_originates_from() {
  $extra_data_to_pass_on_stored_here = &drupal_static(__FUNCTION__);
  $extra_data_to_pass_on_stored_here = $actual_extra_data
}

function my_validation_function($form, &$form_state) {
  //Here's our extra stuff now
  $extra_data = &drupal_static(where_ever_extra_data_originates_from);
}

You can't alter(add to) the number of parameters that are passed to a hook function. You could declare the variable that you want passed into the function as "global" -> Variable scope when you define it and again in the function which would give you access to the value.


Is There a way to search non drupal solr index? I have a huge solr index. I'd like to build my UI within a Drupal site. I tested the apachesolr module but it only focuses on a Drupal node. Does anyone have a similar project?

The Sarnia module is the only solution I'm aware of. It leverages the Search API, but unlike the other SOLR modules, it is designed to expose the content of any index rather than index Drupal content. It also has some pretty decent documentation, here.

However, I'm having trouble getting it to actually work properly. Latest dev version is not working for me, at least at the moment.

[UPDATED] Most of my troubles arose because my SOLR index does not use the standard handler names, and so some manual configuration was required (hacking service.inc). Once done, it certainly works, although it does not cope with grouping/collapsing results, and I'm not sure how to expose facets.

Check out search_api.  It allows you to use multiple search indexes (of which solr is one).  In Drupal 7, you can search on any entity type (users, taxonomy terms, nodes, etc) and can even limit your search to particular node types.  Used in conjunction with Facet API, you can create custom facets, too.


How to add filter on node list in a custom module? I am developing a module. In that module I have a page to list all the nodes of a specific type to user.

I need to:

1- show the nodes each on a row with ' Edit | Delete ' link in each row.

2- I also need to show a dropdown to give the user ability to filter the nodes by one of the node field.

I've created the first one but I don't know how to add a custom filter to the output.

Would you help me ?

I am working on Drupal 6.

Thank you.

If you are using Views 3 and within CCK you have listed allowed values for the field in question, you can set it up like this.

Select the field in question with the allowed values option, eg, in Filters, select 'Content: Field Name (field_name) - ALLOWED VALUES'
Click on EXPOSE.
Click in the values and select them all.
Click Limit list to selected items.
Save it.

You should now have an exposed filter with a drop down that limits the view to that field.

You can use views for listing nodes of specific types.
Also, in views, you can use Contextual filters for other options.
Please explore more options of views and you will find every option there.
Thanks.


Custom links in Views For a Taxonomy Vocabulary on my Drupal 7 site, I have added several custom fields for each Taxonomy Term, and want to have two different ways of viewing the Term information: a summary and a detailed view.

I've created the two Views for summary and detailed (myterm-summary/% and myterm-detail/%). But now the question is how to create a link between them. I'd like a link on myterm-summary/% to link to myterm-detail/% as a "Read More..." link. Is there some View element I can add to the View to create a custom link, using the dynamic URL variable  in the process?

I know I can create a Rich Text block header or footer for the View, but can I refer to the URL variable in that text block somehow?

I've found a solution that you can use the Replacement Tokens to this effect. In order for the field you want to show up as a possible Replacement Token, it must be in the Fields list. So I did:

Set Format to "Unformatted List"
Set Show to "Fields"
Add the "Term ID" field to Fields list.
During creation (or edit it afterward), check the "Exclude from display" box.
Create a new Footer element that's a "Global: Text Area" type.
Check the "Use replacement tokens" box
Insert More Info... in the box.

You can use the "Global : Text Area" in the Header or Footer of the view to add the link. You can get the URL variable using a PHP snippet and use that to create a link. The following should work :

<?php
$view = views_get_current_view();
print 'args[0] .'\'>Read More..';
?>

Make sure you are using the PHP code text format.