What function or $user variable do I edit to manually increase a user's session timeout? I'm using the simpleSAMLphp module which redirects the user offsite to login and then hits them back to drupal in a logged in state, but for some reason the sessions aren't getting applied. When the user closes the browser it causes the user to be logged out.

But when I login via the drupal login page, the user session persists even if the browser is closed.

What function should I look for in the simpleSAMLphp module where it logs the user in?
What might I need to know or edit to make a assign a session time to a user?
Is the session information stored in the $user variable and can I manipulate it from there? or is it a database edit?

There are several modules that can do this for you.

https://www.drupal.org/project/session_cookie_lifetime
https://www.drupal.org/project/remember_me
https://www.drupal.org/project/persistent_login

I've had some problems with remember me and am still testing the others, but they give you more control over the session lenght.

By default drupals session expire after about 3 weeks, according to

ini_set('session.cookie_lifetime',  2000000);

You should be able to override this variable at database level as well, if you want to.


External anchor link or map for attached images I'm looking to wrap the attached images (part of the content type) in an anchor. Typically we are putting together pages that are cross promotions so they go out to other non-Drupal sites

For now we are putting the images in via HTML with the a and img tags on the ones we need external links for. Now we are using views to have a grid page, block, views slideshow but these manually input images are not visually promoted in these new views.

Some had suggested having the link below the image in text (using the link module) but that solution is confusing users who see our standard 'click here to book' and 'book now' phrases on the image.

Simply how can I wrap the image with a link? (with or without the link module, which doesn't wrap)

You can copy the templates views uses to your theme and modify them so that a field returned in the view is used to theme another.  Views has this built in in its latest versions, but only allows divs, spans, etc, and you want an anchor.  Check out Exposing Individual Fields on Output for Styling here for an example of what I am talking about.  There they wanted to just wrap an in a div to set the color, but you could use the same concept to wrap it in an anchor.


Taxonomy: Too many tags? I have a serious problem with the core's taxonomy module (Drupal 7): I have some vocabularies containing all together about 140,000 tags. I do not show these tags anywhere or use them for filtering or anything like it. At this point they are used only for a solr search index. It would be nice to show all nodes that have a certain tag as well, but I am not using this feature yet.
Each node does not have more than 20 tags.

But nevertheless the taxonomy module eats all my memory so that the whole site is broken. I get the message

Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to
allocate 75 bytes) in .../modules/taxonomy/taxonomy.module on line 1022

Does that mean, taxonomy module is not capable to deal with vocabularies that big? What am I supposed to use instead of taxonomy module to deal with big vocabularies?

Nope, the taxonomy module can handle as many terms-per-vocab as your hardware will allow it to (within some reasonable theoretical bounds I'm sure, but certainly 140,000 terms would not be too much these days).

The 'problem' is in your server configuration. Quite simply you don't have enough available memory for the taxonomy module to process as many records as it needs to.

Try increasing the PHP memory_limit setting gradually and hopefully you'll be able to come to an acceptable compromise between your available memory and the size of your vocabularies.

Just to preempt what I think your response will be - you're already allocating 256MB, which might be a large (even outrageous) amount of maximum memory to give to a single PHP script, but the fact that you're getting out of memory errors means it's simply not enough for your site and needs to be increased (unless you want to optimise the core taxonomy module which I don't think would be much fun).

If you're on shared hosting, the first thing to do would be to get the site on a dedicated server/VM. That should make a good bit of difference.


CPU spike during image multiupload — how to optimize performance? I have an image gallery that allows users to upload a huge number of images at a time (this was a project requirement) and when an upload happens, the server's reported CPU usage spikes to 1000%. What modules, settings, or other modifications can be used to ease the load on the server or throttle the image processing (without delaying the loading of the next page so users don't think it's hanging)?

More than likely, the CPU spike is actually happening after the upload and the new gallery is being viewed.

When this happens, each of the new images will be loaded by the browser.  Drupal will detect that these images don't exist on the filesystem, and punt to Image module to render out the derivatives that you defined (ie, the images in each style).  If the user bulk uploaded a bunch of images, then the server may be rendering out a lot of new images in parallel.

To combat the CPU, you can try enforcing smaller max image dimensions.  Smaller images take less CPU to crop/scale/etc.

You can look through the MPM configuration options and see if there is anything you cal tweak.  ServerLimit may be your only option here; I don't recall per-client option in Apache for maximum parallel connections.

Otherwise, I think you may be better served on ServerFault for this issue.


Taxonomy Reference Based on Taxonomy Field I have a taxonomy with a custom field: field_uid

Users are able to create their own taxonomy terms, and when they do, field_uid is set to their UID.

I also have a content type which allows users to select terms from a common vocabulary, however, I only want them to have access to terms that they themselves created (IE terms with field_uid = current user's uid).

I've tried using entityreference and views to do this, but views seems unable to cope with taxonomy fields very well.

Thoughts?

Two things come to my mind:

For the view make sure to do a taxonomy or user view and add a relationship to each other.
You can also use the private taxonomy module: http://drupal.org/project/private_taxonomy


field_attach_form not working as expected I created an entity like this:

<?php
/**
* Implement hook_entity_info()
*/
function fy_teacher_entity_info()
{
    $entity['fy_teacher'] = array(
        'label' => t('teacher'),
        'controller class' => 'TeacherController',
        'base table' => 'fy_teacher',
        'uri callback' => 'fy_teacher_uri',
        'fieldable' => TRUE,
        'entity keys' => array(
            'label' => 'name',
            'id' => 'tid'
        ),
        'bundles' => array(
            'teacher' => array(
                'label' => t('teacher'),
                'admin' => array(
                    'path' => 'admin/structure/teachers',
                    'access arguments' => array('administer teachers')
                ),
            )
        ),
        'static cache' => TRUE,
        'view modes' => array(
            'full' => array(
                'label' => t('Full content'),
                'custom settings' => FALSE,
            ),
            'teaser' => array(
                'label' => t('Teaser'),
                'custom settings' => FALSE,
            ),
        ),
        'views controller class' => 'EntityDefaultViewsController',
    );
    return $entity;
}
?>

And this is the form I created to add/edit this entity.

<?php
/**
* teacher add/edit form
*/
function fy_teacher_form($form, &$form_state, $teacher)
{
    $form_state['fy_teacher'] = $teacher;
    $form['name'] = array(
        '#type' => 'textfield',
        '#title' => t('Name'),
        '#default_value' => $teacher->name,
        '#weight' => '-5',
        '#required' => TRUE
    );

    field_attach_form('fy_teacher', $teacher, $form, $form_state);
    //Save button
    $form['buttons'] = array();
    $form['buttons']['#weight'] = 100;
    $form['buttons']['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Save'),
        '#submit' => array('fy_teacher_form_submit')
    );

    // Delete button if on edit page
    if ($teacher->tid) {
        $form['buttons']['delete'] = array(
            '#access' => user_access('administer teachers'),
            '#type' => 'submit',
            '#value' => t('Delete'),
            '#submit' => array('fy_teacher_form_submit_delete')
        );
    }

    $form['#validate'][] = 'fy_teacher_form_validate';
    debug($form);
    return $form;
}
?>

I can add fields in the backed (admin ui) of this entity. But somehow the fields I added there aren't showing up.

Turns out that the bundle name must be same as entity type.

<?php
...
        'bundles' => array(
            'fy_teacher' => array(
                'label' => t('teacher'),
                'admin' => array(
                    'path' => 'admin/structure/teachers',
                    'access arguments' => array('administer teachers')
                ),
            )
        )
...
?>

For anyone who has this issue,

In your hook_entity_info, under entity keys, simply add the bundle property.
to get the above example to work, simply change the entity keys array to :

<?php
'entity keys' => array(
            'label' => 'name',
            'id' => 'tid',
            'bundle' => 'property_name' //The name of the property that contains the bundle name for the entity.
        ),
?>

for hook entity info reference, see https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_entity_info/7


How to display user picture programmatically in a rule (User Relationships) Starting from the code in a previous question, I am now trying to post a user picture in a rule that displays a relationship between two users (User Relationships module.)

It is the requestees's picture I am trying to display (the $requestee variable is allowed)

Here is the code I have so far:

$imgpath = file_load(($requestee->picture[und][0]['uid']))->uri;
$image = theme('image_style', array('path' => $imgpath, 'style_name' => 'thumbnail', 'attributes' => array('class' => array('RequesteesPicture'))));
$link = l($image, "user/$requestee->uid", array('html' => TRUE));
print $link;

I see the placeholder for the pic. The link to the requestee's picture is correct and the image style is also correct. But the pic does not show.

What do I need to do to make the pic show up?

Thanks. :)

Try something like this, just for grins. Make sure you're actually returning the URI, and maybe provide an alternative image if they don't have one for themselves. Also, your link might be messed up.

I'm not entirely sure how you're getting that URI for the profile image.

$imgpath = $requestee->picture[und][0]['uid']->uri; // Maybe? I would think the URI is in the picture array.
$vars = array(
  'style_name' => 'thumbnail',
  'path' => $imgpath,
  'attributes' => array(
    'class' => array('RequesteesPicture'),
  ),
);
$image = theme_image_style($vars);
$link = l($image, "user/" . $requestee->uid, array('html' => TRUE));
print $link;


How to Rebuild Registry On Admin Form Submit I would like to initiate theme registry rebuild(drupal_theme_rebuild) on a particular form submit. This is admin form for my custom settings:

function HOOK_menu(){
 $items['admin/some-url'] = array(
        'title' => 'Custom Settigns',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('my_admin_interface'),
        'access arguments' => array('administer users'),
        'type' => MENU_NORMAL_ITEM,
    );
 return $items;
}

function my_admin_interface($form, $form_state)
{
    $form['some_settings'] = array(...);
    return system_settings_form($form);
}

The form works well and the settings are being saved, however. The changes involve theme functions, so I need to rebuild the registry whenever the form is submited. What is the best approach? Can I attach to form element function drupal_theme_rebuild or there is hook I can use to call  drupal_theme_rebuild(). What is the best way rebuild theme registry after a form is processed and new settings saved. Thank you for your help

In order to fire a submit callback you have to add it to #submit array within your form. Here is an example.

/**
 * Form builder.
 */
function my_admin_interface($form, $form_state) {
  $form['#submit'][] = 'my_admin_interface_submit';
  return system_settings_form($form);
}

/**
 * Submit handler.
 */
function my_admin_interface_submit($form, $form_state) {
  drupal_set_message(t('Hey there!'));
}

Here is a link to the manual.


How would you incorporate a log out confirmation screen? Scenario: When users click the "log out" link, I'd like a confirmation form to pop up asking them to click again "yes" to confirm and continue logging out.

Is there module that does this? Or some kind of Rules workflow?

Use jQuery

Pop-up

(function ($, Drupal, window, document, undefined) {

    $(document).ready(function(){
        $('a[href="/user/logout"]').click(function(e){
            if(!confirm("Are you sure you want to log out?")) { e.preventDefault(); }
        });
    });

})(jQuery, Drupal, this, this.document);

Or text replace

(function ($, Drupal, window, document, undefined) {

    $(document).ready(function(){
        $('a[href="/user/logout"]').click(function() {
            $(this).removeClass('confirm');
            $(this).text("Are you sure?");
            $(this).unbind();
            return false;
        });
    });

})(jQuery, Drupal, this, this.document);

Simple Middle Page

One very simple way to accomplish this would be to create a new page with a simple confirmation message.

For example: Are you sure you want to log out?

Then link to your new page in whichever menu the log out link belongs.

Rules Link

There is a Rules Link module that can create links with JavaScript confirmations, as well as links that use confirm_form()  You could automatically attach a log out link with confirmation to the User entity.

The l() Function

You may also be able to implement the l() function to generate the link you need.

$logout_link = l("Logout", "user/logout", array( 'onclick' => 'return confirm( "Are you sure?" ); ' ) );

Form API

You could use the Form API with a custom submit handler/redirect.

$form['logout'] = array(
    '#type' => 'submit',
    '#value' => t('Logout'),
    '#attributes' => array('onclick' => 'if(!confirm("Really Logout?")){return false;}'),
);


how to reset taxonomy term ids after deleting all term from all vocabularies after deleting all terms from all vocabularies we are still left with the next available ID of last created term

is there any module that does such a thing ?
or one has to go manually and set the auto increment ?
are there are any side effects with using manual way?

Open up phpmyadmin and do a query

ALTER TABLE `taxonomy_term_data` auto_increment = 1

or using drush

drush sql-query "ALTER TABLE taxonomy_term_data auto_increment = 1"

But not sure that this is recommended.

NOTE: I am assuming that all terms have been deleted from within the UI


Is there incremental deployment module for Drupal 7? I can find Deploy module for Drupal 7 that achieves full deployment. Also, I can find Incremental Deploy module for Drupal 6. Is there incremental deployment module for Drupal 7? or even work around that achieves incremental deployment for Drupal 7?

There is no Drupal 7 version of Incremental Deploy. In fact, the Drupal 6 version is no longer supported.

You have several options to duplicate the functionality. The closest match is probably Data Export Import -  https://www.drupal.org/project/data_export_import

Other options are the Migrate module - https://www.drupal.org/project/migrate or migrate_d2d - https://www.drupal.org/project/migrate_d2d

Modules for migrating specific content types are also available. For example, for taxonomies, Taxonomy CSV import/export - https://www.drupal.org/project/taxonomy_csv


How to translate inline entity form nodes (or, product variations in kickstart) My parent nodes need to be translatable - so i'm slated to use the out-of-the box internationalization module for that. However, one of the fields in this content type is an inline entity field which references another content type. Both the parent and the referenced nodes need to be translatable.

Now, is this a job for entity translate? I've tried with no success - but perhaps i'm not using the right combination. Presently if I set both the parent and child nodes to entity translate types I get an ajax error when I try to add the first child node (regardless of which fields are setup).

I'm not 100% sure on the setup, but I just finished a site that dealt with a similar circumstance. It uses String Overrides to perform targeted text changes, and if it doesn't support Internationalization by default then there's a module that provides additional tabs at /admin/config/regional/stringoverrides for each enabled language.

For reference, here's the translation module list currently enabled on the site:

Locale
String Overrides
Entity Translation
Entity Translation Upgrade
Block languages
Contact translation
Field translation
Internationalization
Menu Translation
Multilingual content
Rules Translation
Synchronize Translations
Translation Sets
Views Translation
Variable

Not all of these modules are required to make this happen, but perhaps you can compare your own setup to this list and find some differences. Apologies for not remembering how to set this up.

UPDATE :: Process for enabling translation within String Overrides

== Modules ==

Internationalization :: link | download
String Overrides :: link | download
Variable :: link | download

Enable Modules:

Locale
Variable
Internationalization
String Overrides
String Translation

Add a new language

/admin/config/regional/language/add
Select, click "Add language"

Add translations for alt language strings

/admin/config/regional/stringoverrides, click desired language in top right
Add rows for each desired string, place original language text in left box and translated string in right box
Save, view on front end

The final interface should look something like the following cap:


How to style menu local tasks Problem

I'm trying to theme the menu local tasks that Drupal places without any unique css classes. How would I do this?

(Specifically I'm looking to hide certain links on certain pages by giving each one a unique css class).

Links Sample HTML

Which is generated by this line in page.tpl.php.

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

So Far

To do that I'm trying to use theme_menu_local_tasks however I can't get it to work. I've put this snippet in my template file but it doesn't print anything or show me any variables.

function tefltheme_menu_local_tasks (&$variables) {
  dpm($variables);
  print("hello");
  return theme_menu_local_tasks($variables);
}

I'm using Tao sub-theme which means it splits menu local tasks into primary and secondary.

function tao_preprocess_page(&$vars) {
  // Split primary and secondary local tasks
  $vars['primary_local_tasks'] = menu_primary_local_tasks();
  $vars['secondary_local_tasks'] = menu_secondary_local_tasks();

Could this be affecting anything?

theme_menu_local_tasks() will never be invoked using those two methods, so it makes sense that your dpm() fails.

Both functions do eventually invoke hook_menu_local_tasks_alter(), though, and that's where you can make your changes:

function MYTHEME_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  if ($some_condition) {
    // Grab the first tab.
    $first_tab = &$data['tabs'][0]['output'][0];

    // Add a class to the link element.
    $first_tab['#link']['localized_options']['attributes']['class'][] = 'some-class';
  }
}

If you want to add a class to the <li> element you'll need to go a step further, and override theme_menu_local_task().

The class attribute is hard-coded at the moment so that'll will need to be changed, based on a contextual variable you can pass into the theme function from the local tasks hook above.

That would look something like this in the alter hook

$first_tab['#extra_class'] = 'some-class';

And along these lines for the theme function

function MYTHEME_menu_local_task($vars) {
  // Copy the code from theme_menu_local_task() but change the HTML output
  // to include an extra class if $vars['extra_class'] is set
}

You might also need to implement hook_theme_registry_alter() to let it know about the new variable (can't remember if it matters but it can't hurt)

function MYTHEME_theme_registry_alter(&$theme_registry) {
  $theme_registry['menu_local_task']['variables']['extra_class'] = NULL;
}


URL to catch post data from off-site payment gateway in Drupal commerce We have to set up an Drupal 7 e-commerce site with Commerce module (Kickstart) that accepts payments via an off-site payment gateway. For which we are developing a commerce payment method that will accept payments from the payment gateway.

Now, We are stuck at this step where this page is shown to a user:

example.com/store/checkout/[transaction id]/review

After selecting the payment method (that we developed) on the above review page, the page redirects to the payment gateway site.
The Payment gateway site, after a payment attempt, sends the payment status to a response page via POST method.

Now, we don't know where to 'catch' the post data sent by the payment gateway in the payment method module.

Also, after the POST data is processed, how to update the order/transaction status in the database and show success/failure message to the user.

Any help would be appreciated.

You can catch it wherever you want. It's up to you to define the menu item and ensure it gets communicated properly to the gateway. See Commerce PayPal for examples - it uses an IPN listener that is always accessible (even in maintenance mode) and dispatches it to the appropriate payment method for processing.


Revision: "per node" version ID I have revisions active for a content type, called e.g. "procedures".

When a node of this type is revised, a new vid is assigned, which is a number independent of the number of revisions made on THAT node.

Given the nature of the node, I need to show/store in the node the revision number in a more meaningful way, for example version=1 for the original node, version=2 for the first revision and so on.
[edit]: I need to store this information in the database, so that it can be queried whenever it's needed. Also, it needs not to change when a old revision is deleted.

How can obtain such result in a easy, clean way?

You can add an integer field to your node, and set the default value to 0.

Then in a small module, use hook_node_presave to increment its value every time the node is saved (or if you detect a field change). Quick, easy and efficient way.

You can do the same with a computed field, by incremeting the value of the field by 1 when you submit the form,  but storing code in the database isn't advised.


Exposed filter show results I have a content type say sample. I've created a view page to slideshow all sample content type. I have an exposed filter at the top of the page, people search using id there, on searching it is giving the correct result with the slider but the slider is'nt working at the result page. I want it show the result first and then the others.

Is it possible.

Enable the Use Ajax option under the Other Tab..


Grouping galleries with Colorbox modules Since two days that i'm looking around to find a easy and simple gallery for Drupal 7.32 and it seems much more complicated that how should be.

I think Colorbox is exactly what i'm looking for but I cannot find a good tutorial or resource that explain how to create a page with thumbnails that groups different galleries.

So when click on them I should go in another page and see all those thumbs from one specific gallery and be able to click on that and see them as slideshow.

More or less like here:
http://www.hopkinsco.com/portfolio

Can you please point me in the right direction?

Of course if you want to suggest another module or method is fine as well.

The content-type "gallery"

First of all, I created a content-type "gallery" which has several fields of my choice and a field "image" with illimited number of images.

The View

If I don't want something too specific, I use the Views module to create a View of all my galleries. I hope you already know that module. If not, go read the basics.

Choose content of type gallery
Set the title and the path of the page, etc...

You can choose which fields to show. If you want something like the site you linked in your question, you can use this configuration:

Format: grid (with number of columns to 4)
Fields:

Title
Image

Image style to thumbnail or whatever you created
Link to content (to land on gallery page when you click on the image)
Multiple value fields settings: display 1

Normally, you have now the equivalent of http://www.hopkinsco.com/portfolio when you open your View page.

The gallery page

The page of the content-type gallery displays all the fields you created for this content-type, in the order you arranged them in the admin. If you want something simple with the Colorbox module, you can go to admin/content-types/gallery/manage display and set the image field config like this (sorry for the french):

Then go click on the little gear on the right to set the advanced config:

Now you've got the equivalent of http://www.hopkinsco.com/portfolio/colonial.

The template and/or the style

Now that you've got the right content in the right place, you can customize the rendering with a little template and/or CSS.


open node reference links in lightbox/ popup I want in my node view pages, node reference links open in popup window or lightbox window.
Does anyone have a solution?

In Views Use this code in "Rewrite the output of this field"

[title]

Note: add  "Node:Path" field before the Rewrite field.

You can also set the width and height of the popup window, see the read-me file in Lightbox2  module folder.

hope you will get idea from the above!!


Drupal Commerce: Allow anonymous users to choose their username on checkout The default setup includes a single option in the "Account Information" pane which allows for an email address. The user's username is then derived from that.

I would like to add another field for "Username" where the user can enter their own username, instead of having it generated for them automatically based off of their email.

Theres a sandbox project here that you will need to download with git that looks like a complete sign up form.

Theres also Commerce User Profile Pane that allows you to choose the fields in the pane. Ive not used it before, but looks like a good place to start.


Set a default text in an article Im looking for a way to create a text template or a way to make one, where, when you create a node of a specific content type, a text is preloaded into the node. (Similar to Word-Templates)

At the moment, whenever I habe to write a status report, I have to copy paste it, but I want this to happen automatically.

Any help would be greatly appreciated.

Best Regards.

Couple options come to mind,

if you don't want to code then you can use Node Clone module and have 1 unpublished template node, and everytime you want to create a new one just clone the template node.

Also without installing any modules, you can use the Default value in the field setting of the content type

The other way is a bit more tricky, you have to create a custom module and use hook_form_alter to set the default values of the fields for your specific content type.


I'm suddenly getting the error :EntityMetadataWrapperException I'm running a Drupal 7.21 site that uses the Entity Reference module (v.7.x-1.0) to support reusing image nodes in other node types. After several months of smooth sailing , I'm seeing a new error when I try to view image nodes on my site. The error is:

  EntityMetadataWrapperException: Unknown data property
  field_entity_image. in EntityStructureWrapper->getPropertyInfo()

The property named in the error, "field_entity_image", is the name of an Entity Reference field that exists on other node types (article, basic page). However, those other content types don't throw the error when I try to view them. What is new is the fact that I created a new node type (bio) that also uses the existing field_entity_image field.

I've seen this error discussed in relation to certain modules (Commerce being one) but not as the result of creating new content type or adding entity reference fields. If anyone has insights into this, all help will be much appreciated.

Your site has not been running on Drupal 7.21 for several months. You have recently upgraded.

There was a security fix in the drupal core image module in 7.20 which broke several contributed modules. 7.21 has a new variable to mitigate the problem, but if your issue involves images, it is probably related to the security fix. For more information read the release notes.


How do I show the result on same page after submitting the form? How do I show the result on same page after submitting the form in Drupal 8?

Request a rebuild in submitForm() and then display the result in buildForm():

public function buildForm(array $form, FormStateInterface $form_state) {

  // build form

  if ($form_state->isRebuilding()) {

    // display result

  }
}

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

  $form_state->setRebuild();

}


How do I add an ID to the ul tag of a menu? I am able to add unique ids to menu links by either adding code to my theme's template file or by using a menu module; however, I would like to add a unique id to the ul tag that encapsulates the menu li links.  The reason that I would like to implement this is to style the menu as a whole instead of the menu's individual links.   My ultimate goal is to take the whole menu and float it to the right in the header-top region of drupal.  I am rather new to Drupal so, perhaps there is another way to achieve this?

I originally attempted custom css styles using the skinr module without success.  The skinr module was able to move the menu's title to the right, but the menu's links were still located at the left of header-top.

My setup consists of Drupal 7

UPDATE
I was able to add a custom CSS class "user-menu" to the user-menu block.  Next I added a custom css to mix-and-match-style.css

css code:

.user-menu ul li {
     padding: 0;
     float: right;
}

The css code seems to float: right the menu, but the links are not ordered properly once floated to the right.  The correct order of the links should be "My account | Log out".  When the list is floated to the right the order changed to: "Log out My account |"

Is that a bug or am I not understanding something?

You can make use of theme_menu_tree

function theme_menu_tree($variables) {
  return '
' . $variables['tree'] . '
';
}

http://api.drupal.org/api/drupal/includes%21menu.inc/function/theme_menu_tree/7

You can print this menu tree

template_preprocess_menu_tree

hereis api

Pre process the menu tree OR Call the menu theme to print it as you want.
Thats all.


Store template in module I want to store a template for my content-type in a module. This module provides the content-type (via features). My template "node--my-content-type.html.twig" should be in this module, too. Not in the Themes templates/ folder.

I know there are some related questions yet. I think I got the first step already; Drupal is recognizing my template and is outputing its contents.

In Drupal 7 the approach was made with something like this:

function mymodule_theme($existing, $type, $theme, $path) {
  return array(
  'node__my_content_type_machine_name' => array(
      'render element' => 'elements',
      'template' => 'templates/node--my-content-typee-machine-name',
    )
  );
}

Drupal 8 recognizes the template when I change this a bit.

'template' => 'node--my-content-type-machine-name'

So far so good. But now I am trying to render a field in my template and here I am failing.

{{ content.field_body }} ==> This is doing **nothing**

In my theme´s template-folder this is working fine. Any ideas?

You are missing the base hook definition. See how system_theme() does it for block templates. So, add 'base hook' => 'node' and it should work.


How to change the text format of the body field of 200 nodes at once? I need to change the Text format of the body field of 200 node of the "flats" content type.

I guess I can do it in the database but I don't know where to look.

The query you suggested is great but if you want to make sure you're only including body fields from the content type you want to update you need to extend it slightly:

UPDATE field_data_body
SET body_format = REPLACE(body_format, 'plain_text', 'full_html')
WHERE entity_type = 'node' AND bundle = 'flats'

You'll also need to run the same query for the field_revision_body table or nothing will happen:

UPDATE field_revision_body
SET body_format = REPLACE(body_format, 'plain_text', 'full_html')
WHERE entity_type = 'node' AND bundle = 'flats'


Generic field.html.twig template for a custom Entity I have a custom Entity called custom_entity, along with a custom module which provides twig templates for my bundles and their fields.
How can I define a generic/base field template for all fields created under custom_entity?
For a specific field I could create the template:
field--custom-entity--field-my-field.html.twig

But I'm looking to do something more general, like:
field--custom-entity.twig

Where all my fields created on a custom_entity use this base template.
I don't want to modify field.html.twig in the theme. I want this template to only apply to my entity and its bundles.

Add your own theme suggestion:
mymodule.module
/**
 * Implements hook_theme_suggestions_field_alter().
 */
function mymodule_theme_suggestions_field_alter(array &$suggestions, array $variables) {
  $element = $variables['element'];
  // place the least specific suggestion at the beginning of the array
  array_unshift($suggestions, 'field__' . $element['#entity_type']);

}


How to hide product in drupal commerce with rules I have a Drupal site with drupal commerce on it and I created a product with 2 price field.

If a user have role 'simple user' he sees the default price.
If user have role 'friend user' he sees the second price value.

I already create this rule but now I'm trying to filter the product in this way:

If user have role 'friend user' and the product don't have the second price hide it to him.
I'm not seeing any option in rule to hide a content.

How can I achieve this content filter?

I believe there is not out of the box or ready to use solution. You should create a custom rule and trigger it when the product is being viewed.


How To Set Node Path/Alias Programatically I am creating some nodes in Drupal 6 programatically by creating an empty object, setting some properties and calling node_save() on the object.

When I print out the object again, I see new properties, since node_save() alters the node object by reference, but I don't see a path property, but from Drupal I can always view the node at 'node/NID'.

Is 'node/NID' the path?

Should I not set a 'user friendly' path property on the node itself, and just use path_set_alias() after node_save instead of mucking with the path property on the node itself?

The canonical URL for a node is http://example.com/node/<nid>; if you want to set a path alias, you need to set it with path_set_alias('node/' . $node->nid, $alias).


how to get all the values in an edit form I want to see all the values in my edit form, I tried
dsm($form_state->getValues())  but i dont get anything.
if I do dsm($form_state) I get a huge amoung of things too much to look through.

what is the correct syntax to get just values in my form in the edit page.

The form_state->getValues() only works during the validation and submit process. Instead you need to look to the $form variable for values. Unfortunately you cannot get all the values easily you must dig into the form itself:

$form['title']['widget'][0]['value']['default_value'];

EDIT
I was looking into this more and there may be a cleaner way.

First you must get the form object from the $form_state variable. From there you can use the function getEntity() to actually get the entity that the form is editing. Then if you want to get a value you can use the get('field_name') method or if you want all the values use toArray()

// Get the entire node as an array and will include all values
$node = $form_state->getFormObject()->getEntity()->toArray();

or

// Get the entity object
$node = $form_state->getFormObject()->getEntity();

// Get the field
$node->get('field_my_field');

// Get the field as a string (returns value)
$node->get('field_my_field')->getString();


Attach webform on each node of specified content type I am currently working on real-assets project in which user can add property using property-listing content type for listing and searching property on portal.

if any visitor is interested in any property than he/she can directly fill the form, which will be present in full view of property node and send it to admin and also admin will get to know for which property visitor fill the form same like as comment for node.

I had the same question and found answer in drupal community, that was using of Webform Default Fields module.

Here are a brief description about this module :

  Description

  With this module you can easily create a lot of nodes with same webform fields. It can be applicable in case of job vacancies with reply form, kind of quality feedback control or whatever your mind suggests you.

  Because you can create more than one webform-enabled content types, you respectively can attach different default fields for each of them.


Trying to make changes to page (post/article) text just before they are rendered I have a module that works fine but I cannot seem to get node_view hook to work - seems to never be called. As a test, I tried adding this to the dennis.module in sites/all/modules/dennis, but nothing happens (Drupal 7).

function dennis_node_view($node, $view_mode, $langcode) {

  echo "AAAAAAAAAA";

  $node->content['body'] = array(
    '#markup' => "bonjour!"
  );

  $node->content['body'][0]['#markup']="hello";
}

Ultimately I need to find keywords in the content and replace with other text. So easy in WordPress and Joomla but after days of trying I have got nowhere with Drupal. Please help!

I can't help with the code, but could you use the String Overrides module for this?

Features:

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


How can I use Metatag Module to set specific tags on specific nodes? I'm using the Metatag module to set tags on content generally throughout my project. But there is one group of content where I want to be able to set the metatags for specific nodes. Because these nodes have unique specific tags, I want to be able to set them at the node level.

Is there a way to do this?

In Drupal 7

When you configure Metatag, you can click on + Add default meta tags and this will allow you to set them up by Content Type.

If you need to alter only specific nodes, edit your node and scroll down to the end and select the Meta tags Tab


Calculating a shipping cost I am using the Commerce Shipping Rate Field to set a unique shipping rate per product.

However, I would like to use this value in calculating another shipping value/service (commerce_shipping_price x 0.5). I can't seam to work out how to pull this value/field into a Calculation Rule.

How do I create a calculation Rule of 50% of the Commerce Shipping Price?

The problem you're facing is that shipping rates are calculated at the order level while your field exists at the product level. You can loop over the line items on an order to inspect this field value and then make calculations to the price based on what you find, but what do you do when the field value is different for different products on an order?

In my opinion, this logic is going to get confusing quickly to try and reproduce in Rules. I would favor writing a custom Rules action that inspects and sorts the product data in code, adjusting the price directly via the API instead of through the Rules UI.


How do I access URL parameters from my custom module? I have set up a custom page with Panels.

In the Panel configuration I have set the page path to /products/%term.

I made a custom module which currently displays "Hello world" on this page, and all is well.

function product_tree_block_view($delta='') {
  $block = array();
  switch($delta) {
    case 'product_tree' :
      $block['content'] = theme('product_tree', array("greet" => "Hello world",));
      break;
  }
  return $block;
}

However; I would like to process the %term to fetch some additional information, relevant only to the current %term.

My question is: How can I access the %term? Is this variable accessible from my module at all?

The function arg() will do that for you. For example, in path http://siteurl/products/%items,

arg(0) will have the value products (first value after your $base_url)
arg(1) will have the value of %items (second value).

You might then just apply your logic, in this this case you could do the check arg(1).


Drupal 8. Error join() Twig function I try to print field_tags inline and comma separated. My code in node.html.twig:

<p>{{ content.field_tags | join(', ') }}</p>

This return error message: The website encountered an unexpected error. Please try again later.

Whats wrong? Help.

Anything in content is a render array, you can't use functions like that on those directory.

You can loop over it and print out each item, that works as it is then automatically rendered.


In the settings for payments, what is the meaning of "Test transactions in a live account"? What actually happens if I complete a transaction with the payments setting on "Test transactions in a live account"?
The only documentation I see is language like "Under Transaction mode, make sure 'Test transactions in a live account' is selected for testing purposes."
However, I can find no description anywhere of how the software behaves differently in this "Test transactions in a live account" mode compared with the two other modes available.
Also, what is required to submit the checkout form for a "test transaction in a live account"?  Does it have to be a real credit card number?

The language used varies by payment gateway, but they almost all include some sort of development environment that is completely separate from the production environment. Some will also permit test transactions in the production environment itself by letting you turn on test mode and use a test credit card number that passes the "Luhn algorithm" used to validate card numbers but is not a real number.
As this varies by payment gateway, you're going to have to consult the payment gateway's documentation. In Drupal Commerce itself, how you configure this differs between Commerce 1.x and Commerce 2.x. Make sure you're viewing module documentation that matches the version of Commerce you're running.


Submitting a form rebuilds (expensive) page upon submit I have a simple menu callback that draws a page with a form on it. The page callback does a very expensive operation (requests a bunch of data from an external API).

function test_menu() {
  $items = array();
  $items['test'] = array(
    'title' => 'Test',
    'page callback' => 'test_page_handler',
    'access callback' => TRUE,
  );
  return $items;
}

function test_page_handler() {
  $data = very_expensive_data_operation();
  $output = drupal_get_form('test_simple_form', $data);
  return $output;
}

function test_simple_form(&$form_state, $data) {
  $form['create'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  return $form;
}

function test_simple_form_submit(&$form, &$form_state) {
  // do something
}

The problem I am seeing is that when the form is submitted, Drupal will re-execute the page callback in the background, resulting in the very_expensive_data_operation() running again.

There are probably lots of great reasons for Drupal to do this, but how can I change my app so that the very_expensive_data_operation() doesn't have to run again when submitting the form (after all, that's why I'm passing $data to the form, rather than having the form run it directly.)

One workaround I can think of is to toss $data into a cache table, but it feels like I'm missing something that available to me in the Drupal+FAPI api.

You can also try using drupal_static

  Provides central static variable storage.

  All functions requiring a static variable to persist or cache data
  within a single page request are encouraged to use this function
  unless it is absolutely certain that the static variable will not need
  to be reset during the page request. By centralizing static variable
  storage through this function, other functions can rely on a
  consistent API for resetting any other function's static variables.

function test_menu() {
  $items = array();
  $items['test'] = array(
    'title' => 'Test',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('test_simple_form'),
    'access callback' => TRUE,
  );
  return $items;
}

function expensive_data() {
  $data = &drupal_static(__FUNCTION__);
  if (!isset($data)) {
    $data = very_expensive_data_operation();
  }
  return $data;
}

function test_simple_form(&$form_state) {
  $data = expensive_data();
  $form['create'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  return $form;
}

function test_simple_form_submit(&$form, &$form_state) {
  // do something
}

You might notice that the static variable technique only stores data for the duration of a single page load. For even better performance try this

function expensive_data() {
  $data = &drupal_static(__FUNCTION__);
  if (!isset($data)) {
    if ($cache = cache_get('my_module_data')) {
      $my_data = $cache->data;
    }
    else {
      $data = very_expensive_data_operation();
      cache_set('my_module_data', $my_data, 'cache');
    }

  }
  return $data;
}

If you want to refresh your cache from time to time you can try

cache_set('my_module_data', $my_data, 'cache', time() + 360);

OR you can manually rebuild your cache using

cache_clear_all('my_module', 'cache', TRUE);


How to get tid on behalf of node id (nid) in Drupal 8? I am new in Drupal 8. I have created a node with category (taxonomy). Now I don't understand how to get tid by using nid. I am using $node->body->value to get the body field value and use {{ body }}. But to get category id if I use $node->field_category->value, it will display Null in debugging mode.

function THEME_preprocess_node(&$variables) {
  $node = \Drupal::routeMatch()->getParameter('node');
  $variables['body'] = $node->body->value;    // Working fine
  $cat_id = $node->field_category->value;    // Its showing null
  kint($cat_id);
}

So can anyone please tell me how can I get the category id (tid) of a node?

A reference field doesn't have a property value. You can use entity to load the term or target_id to get the term id:

$tid = $node->field_tags->target_id;


How to get the entity that field belongs to in the case of an entity reference field Here is my use case:

I have created a media bundle (FILM IMG) to store a media entity (image) field. I can manage it at admin/structure/media/manage/film_img/fields

In a content type named "FILM" , I have added a entity reference field which reference my "FILM IMG" media entity bundle.

I am also using file_field_path module to rename the uploaded images.
When I am adding a new image for a new Film, I would like to use hook_filefield_paths_process_file to rename my image file name.

This hook is providing me the media entity ($entity) as a parameter, but of course it is not providing the Film entity that I need (I need it to get some info to rename my file name)

Here is my question: How to get the "parent" entity from the referenced entity;

In other words, with my use case: How to get my film node from the image media entity provided by the hook.

You can get that with an entity query:

// Get IDs of all film nodes that reference this entity
$nids = Drupal::entityQuery('node')
  ->condition('type', 'film')
  ->condition('field_foo.target_id', $entity->id())
  ->execute();

// Load the nodes
$nodes = Drupal::entityManager()
  ->getStorage('node')
  ->loadMultiple($nids);


Error migrating a Drupal 8 site from beta15 to final I have a site in development that is currently running Drupal 8 beta 15. As it is on shared hosting without shell access, I'm planning on moving it to a VPS. Updating Drupal 8 via FTP is just far too annoying.

But when I tried to move the site to a new server I encountered a problem. The new server is running  Ubuntu 14.04 with PHP 7 on it.

I installed the final Drupal 8 on the server, and then copied the sites, themes and modules folder from my beta site and restored the beta database on the new server.

But now I get the following error when trying to access the site:

  PHP message: Uncaught PHP Exception InvalidArgumentException: "$max_age must be an integer" at /var/www/html/drupal/core/lib/Drupal/Core/Cache/CacheableMetadata.php line 81"

I tried drush cr, but that didn't do anything. I also can't execute an updatedb, I get the following error then:

  Error: Call to undefined function drupal_get_installed_schema_version() in /var/www/html/drupal/core/includes/install.inc on line 80
  Error: Call to undefined function drupal_get_installed_schema_version() in drupal_load_updates() (line 80 of /var/www/html/drupal/core/includes/install.inc).

Any ideas on how to fix this particular error? Or alternatively, a better way to migrate my beta site that doesn't rely on shell access on the server?

This particular error comes, when your services.yml file is outdated. It contains the default cache max-age:

The relevant portion looks like this.

parameters:
  renderer.config:
    auto_placeholder_conditions:
      max-age: 0
      contexts: ['session', 'user']
      tags: []

This was added after beta 15, which is why you are seeing that error. Since some portions depend on the default max-age being defined, it will gives error when it isn't.

When updating your site, pre 8.0.0 you need to verify that your services.yml contains the required info.


How to display the total number of article/page on a term views? In Drupal 7. We created a Views to list all pages assigned to this particular TermA. But some of these pages can only be view by registered user. We would like to show the total number of pages in this TermA, so un-registered user know how many articles/pages they are missing without register. So how can I display the total number of pages in this TermA in View(not the term menu link)? It will be nice to show that number next to(or under) the Views title(see screenshots).

Current setting on views and display

wanna have total number of articles in this TermA like this

You could achieve this by creating view attachment or block which will calculate the total number of nodes per term. Do not add access rule for this case. This can be then called in the header of the Taxonomy Term View using Global:View where you can select the newly created view and its display.


Views - need to show 1 image on teaser I have a news page on my site, and I'm displaying it using Views and Display Suite so the image is along side by side to the description of the news. In Manage Display for News Content Type I want to display 1 image on the teaser view, then when the user clicks through it shows all images for that news item.

But when I set #1 in manage display, and click save, it doesn't save the setting. If I have more than 1 image for the news item, it displays all of them in the teaser when I only want to show 1. Can anyone advise?

In display suite manage display, put 1 (the number of image to display) instead of #1


arg(1) changed when doing AJAX I created a custom module named my_module.

In hook_menu() I define the following path.

$items['my-module/item'] = array(
  'title' => 'Item',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('my_module_item_form'),
  'access arguments' => array('access item content'),
);

This is the code for my_module_item_form().

$arg = arg(1); // Problem here! Should return "item", right?
...
// $form[...] = array('#ajax' => ...);

$form['arg'] = array(
  '#type' => 'hidden',
  '#value' => $arg,
  // I also tried '#default_value'
)

// Submit field

Basically, I really need to obtain item in arg(1) and nothing else.

When I edit fields (not fields with ajax) and click submit, I can obtain the correct arg(1) in my hook_submit which is "item". Now, when I edit fields with ajax and click submit, arg(1) returns "ajax" which I do not like.

How should I obtain "item" in arg(1) in in the form submission handler during an ajax call in my form?

When implementing AJAX in a form, it will send a callback to system/ajax, if you didn't set your path in the AJAX properties. So, when you use arg(1) in your code, it will return ajax, which is the value assigned to the hidden form field.


Products - Add to cart I need some advice.

My client has a website with loads of products.  Now the client want the ability to add products to a cart, and instead of buying, they want the products to be mailed.

How can I acheive this.  I took a look at the commerce module.  This module is amazing.  I did some research and found this article saying I can achieve  what I want with the rules module.

This is awesome.  But drupal commerce has its own set op products that you need to add inside the store.  I need to use products already created. As well as add options such as colors and sizes that also needs to be displayed in Select lists.

Is there a way that I can get this feature with existing products? Or just add the cart button to my nodes?

Thanks.

It depends on how your node 'products' are setup. In Drupal Commerce, 'products' are a fieldable Entity Type and each bundle of that entity type is a different product with different sets of fields.

One possible solution would be to check out the Migrate and its ecosystem of other modules to see if there would be a way to convert your product Content Type to a Product Type.

Note that in the native Commerce workflow, you also need a Product Display node to act as a container for products to display them to the end user. Think of the Product entity as a single product option [in the example of a t-shirt it could be "X-Large Blue"] and the Product Display node is the wrapper that contains all options to display as a single "product" to the user.


hook_page_alter to change title on user profile page? Right now I have the following function implemented in template.php:

function ccom_page_alter(&$page) {
  if (array_key_exists('#account',$page['content']['system_main'])) {
    $account = $page['content']['system_main']['#account'];

    if (isset($account)) {
      drupal_set_title($account->field_complete_name['und'][0]['safe_value']);
    }
  }
}

Is this the best way to set the title on a user page?  Or should I be doing this through a different hook?

EDIT: I've updated my template.php to use hook_preprocess_user_profile instead, and I have this:

function ccom_preprocess_user_profile(&$variables) {
  drupal_set_title($variables['elements']['#account']->field_complete_name[LANGUAGE_NONE][0]['safe_value']);
}

The page title changes (like the one the browser shows you on a tab), but the user profile Drupal page title remains the username.  Very annoying.  Still working...

EDIT 2: I ran an experiment.  I did the following:

function ccom_preprocess(&$variables, $hook) {
  dpm($hook);
}

Which gave the following output when viewing a user profile page:

search_block_form
block
region
block
region
user_profile
user_profile_item
user_profile_category
block
region
html
region
user_picture
page

So that's the order in which the preprocess hooks are called on that page.  I then created two functions:

function ccom_preprocess_user_profile(&$variables) {
  dpm($variables);
  drupal_set_title('mytitle');
}

function ccom_preprocess_page(&$variables) {
  dpm($variables);
  drupal_set_title('mytitle');
}

I first loaded the page with the ccom_preprocess_page function commented out.  The title in the browser tab changed to mytitle, but the page title stayed as the username for the user profile page being viewed.

I then commented out ccom_preprocess_user_profile and uncommented ccom_preprocess_page and reloaded the page again.  Both the browser tab title and the page title changed to mytitle.

This tells me that somewhere after the user_profile preprocess hook function and up to and including the page preprocess hook, the page title is reset.  Where that is I'm not entirely sure.

So, my thinking at this point would be to create a global variable and set it equal to the user account object available in the user_profile hook, and then in the page preprocess hook just set the title based on the complete name field available in the account object.  Thoughts?

This finally worked for me; it's essentially what was posted at http://drupal.org/node/1262070#comment-5038516, but with some function renaming and generalizing:

function YOUR_MODULE_menu_alter(&$items) {
    // Change the title of user profile pages to the user's name.  Gak.
    $items['user/%user']['title callback'] = 'YOUR_MODULE_user_page_title';
}

and then

function YOUR_MODULE_user_page_title() {
    if (arg(0) == 'user') {
        // Load uid from url
        $user = user_load(arg(1));
        // Get the full user name somehow; here, I'm calling a function of my own.
        $output = get_user_full_name($user);
    }
    // Fallback to username if no fields are present
    if (empty($output)) {
        $output = $user->name;
    }
    return $output;
}

But, come on.  It's nice that the hooks are there, but doing something like setting the title of a page REALLY shouldn't be this hard/obscure...


Image style generating hook I'm using Drupal 7. Is there a hook for generating image from image style?
For example. I upload an image. When image is displayed for the first time, drupal generates image style. Can I hook to that event somehow?

The image style hooks are documented here:

http://api.drupal.org/api/drupal/modules%21image%21image.api.php/7

hook_image_default_styles:     Provide module-based image styles for reuse throughout Drupal.
hook_image_effect_info:    Define information about image effects provided by a module.
hook_image_effect_info_alter:  Alter the information provided in
hook_image_effect_info.
hook_image_styles_alter:   Modify any image styles provided by other modules or the user.
hook_image_style_delete:   Respond to image style deletion.
hook_image_style_flush:    Respond to image style flushing.
hook_image_style_save:     Respond to image style updating.

Nothing for the actual image generation process, if that's what you're looking for.

See image_style_deliver for the details on the image generation


How to assign "Edit" permission per Webform? On Drupal 7, how can I assign the "Edit" permission per webform, beside using "Permissions per Webform"?

It actually can be done by "Enable per content node access control settings", which is under "Structure > Content types > Edit Webform > Access Control".


Slideshow caption when logged in displays in different location when logged out I've got a slideshow displaying on the homepage, and at the bottom of the images, I've got captions. I am using:

.views-field-body { margin-top: 250px; }

To position the caption, but the position is not consistent when logged in and out. For example, the code above displays the caption in the correct location when logged out, but when logged in, the caption is pushed further down.

What is the correct way to position the caption?

You are checking your CSS by log in as an administrator. Try those of you who have Google chrome installed.

Go to Option
Open a new incognito window (or shortcut Ctrl+Shift+N)

and check your css there when you logged in as an administrator. The extra space your slogan is getting is due to the edit this link and all other links which are for administrator use only.For a normal user these links are not available (which is the case when you logged out) so it works fine.


how to display Variables in User account page In the node template, I used to put the following code to find the variables:

<?php print_r($node) ;?>

What if this is a user account page (e.g. /user/1), what "$object" should I print to see the variables. I need to pre-fill the webform's fields with the profiler2's fields.

Try get_defined_vars

If you install the Devel Module there is a page for viewing and editing variables.

Also you can try

<?php
 dsm (array_keys(get_defined_vars()));
?>

See also:

get_defined_vars()

get_defined_constants()

get_defined_functions()


Can't enable dev module from Drush I am downloading a dev version of the Drush Search & Replace module via

drush dl sar-7.x-2.x-dev

And then trying to enable it

drush en sar

But returns contradicting options. First it says the project was not found, and then asks to overwrite the project that was downloaded previously

drush en sar
sar was not found.                                                                                [warning]
The following projects provide some or all of the extensions not found:                                                              [ok]
sar
Would you like to download them? (y/n): y
Install location /home/ubuntu/.drush/sar already exists. Do you want to overwrite it? (y/n):

Using drush 5.10.0

You need to clear drush cache.  I have seen this same thing before, where I try to do a drush action from a module and am told the action is not available.  Then a drush pm-list | grep "module" shows me it is enabled.

drush cc drush
drush en sar

As we say around my office daily, "When in doubt, clear cache."  If this is not working, then take a step back and verify your assumptions.

We assume the download succeeded, so we should be able to find the module in a "not installed" state.  Verify with drush:

drush pm-list | grep "sar"

We assume drush handled the download properly, try again with another folder.  Verify with drush:

drush dl sar --destination="sites/all/modules"

Solution:

I assumed, since you were asking about enabling, that this was a site module.  After downloading it on my local system I see that this is a drush command package, and that [user]/.drush/sar is correct.  Verify the module does not need enabled and is already working with:

drush help sar


How to theme the user picture to appear in lightbox I want to enable viewers to click on an image and have it displayed as a lightbox.

in my user-profile.tpl.php I have access to '$user_profile['picture']'. After I dsm($user_profile) I see an array of $user_picture with #markup and #weight elements.

I'm not quite sure if this is the right approach and how to go about altering the markup before it's displayed so i can add 'rel="lightbox"'

An alternative approach to wrapping the user picture around the necessary  tag for lightbox, would be to append a custom CSS class to the user picture. Then navigate to /admin/config/user-interface/lightbox2/automatic (D7), down to custom class images and type in the name of the CSS class you chose before.


drupal_set_message showing twice when called from hook_init Basically the issue is that drupal_set_message is showing the message twice on some pages when it is called from hook_init.

Can someone give some advice about this issue, please ?

It's likely that the first message you see is the left-over result of a previous AJAX call, and the second message is the one you're intending to see.

To test that, open a different browser and browse to the page in question. First time round you should see the message once; when you refresh the page, and on subsequent requests, you should see it twice.

It happens because hook_init() is also invoked for AJAX requests, but the messages added to the session are never printed-then-cleared - so there's an extra copy of the same message in the next normal page load.

For most (all?) modern browser/server combinations you can use something like this to detect whether or not the request is from an AJAX source, and react accordingly:

function is_ajax_request() {
  return !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}


Updating to Drush 7 on OSX I had a working drush 5.6 (manually installed) on OSX (Yosemite) and decided I wanted to upgrade to the latest drush 7 version. I ended up with version 6.0-dev.

I followed the installation isntructions and decided to use homebrew to install composer and drush. So far so good, but the thing is, I can't seem to get to the latest "master" dev version: I'm stuck on 6.0-dev.

I tried different ways like:

brew install --HEAD drush
brew switch drush HEAD

and:

composer global require drush/drush:dev-master
composer global update

My composer.json looks like this:

{
    "require": {
        "drush/drush": "dev-master"
    }
}

which drush:

/usr/local/bin/drush

drush status:

 PHP executable        :  /usr/bin/php
 PHP configuration     :
 PHP OS                :  Darwin
 Drush version         :  6.0-dev
 Drush configuration   :
 Drush alias files     :  /Users/albert/.drush/aliases.drushrc.php

Any ideas?

You should add to your ~/.bashrc file the additional PATH, e.g.:

# Add a Composer's global bin directory if exists.
which composer >/dev/null && export PATH="$HOME/.composer/vendor/bin:$PATH"

It should come first before your other drush. See my full .bashrc for details (bash4 syntax).

Alternatively install drush by specifying COMPOSER_BIN_DIR, like:

COMPOSER_BIN_DIR=/usr/local/bin composer global require drush/drush:dev-master

Assuming that /usr/local/bin is already in your PATH.


How to run drush with cron (elysia cron)? Problem

I can't get cron (specifically elysia cron) to run with Drush. I've been using this as a guide. What have I missed/done wrong?

My Crontab

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
COLUMNS=80

*/5 * * * * /usr/bin/drush @main elysia-cron
* * * * * env > /tmp/cronenv.log

Checklist:

I've used www-data for my crontab. This is the default nginx server user.
The path to drush (/usr/bin/drush), comes from which drush.
I've used an alias for the site, @main. I've tested this outside of cron and the command drush @main elysia-cron runs cron, although only once an hour (see this problem). This cron runs every five minutes so it should work once an hour.

I also tried the format in the docs above:

*/5 * * * * /usr/bin/env PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin COLUMNS=80 /usr/bin/drush @main elysia-cron

It would probably be easier to use --root and --uri instead of @main.  Drush loads aliases on a per-user basis; the user you are testing drush @main elysia-cron probably has the @main alias defined in an alias file in ~/.drush.  You'd need to either move your aliases to a global location, or perhaps copy your alias file to the www-data user's .drush folder.


slideshow module where editor can upload images I am looking for a JQuery slideshow module, where an editor can upload images from Drupal, without having to go into the code or through ftp.  I imagine this module already exists.

There are many options, but I am rather fond of Views Slideshow

It allows you to create a slideshow from a view. What is nice is this basically means the possibilities are endless. Plus, it allows your user to easily upload images, assuming of course you have created a content type they can use.


Get text field value before saving node I have a a custom module in which I am implementing hook_node_presave() for a content type "ABC".

I want to get the value of a text field say 'field_test' before saving the node.

How to do this.

Use the following code,

$value = $node->field_test[$node->language][0]['value']

This to get the value for the text field alone for other fields format will chage.


How do I create a Forum topic post? I'd like to be able to create a topic on an existing forum, using the REST API exposed by the Services module. This is drupal7 and services 3.x .

via the REST interface, I can successfully:

query the index of forums  GET /rest/node?parameters\[type\]=forum
retrieve a single forum post.  GET /rest/node/8
update forum posts (via PUT)  PUT /rest/node/8   ...

I have not been able to create a forum post.
I tried many different variations of the JSON payload, and have not yet found the secret to success.

Example:

curl -i -X POST \
  -H Cookie:SESSe6a353351df0bfa8deadcafe=B0ZkiW3-U2x93yJU-deadbeef \
  -H X-CSRF-Token:PSCd5qIdddax0Mh5gfnOM872hdj893-eeeeffff \
  -H Accept:application/json \
  -H content-type:application/json \
  http://myserver/rest/node \
  -d '{
    "title": "This is a test post",
    "body": {
      "und": [{
        "value" : "This is a test post. Please ignore.",
        "summary": "test1",
        "format": "filtered_html"
      }]
    },
    "type": "forum",
    "language": "und",
    "status": "1",
    "forum_tid": "8"
  }'

The error looks like this

{
  "form_errors": {
    "taxonomy_forums][und":"An illegal choice has been detected. Please contact the site administrator."
  }
}

I have tried many variations of the payload, and always get the same error. I think the error means I need to pass different data. But I don't know which different data. Help?

Er, yes, I just succeeded in creating a Forum topic, after many trials. This was successful :

curl -i -X POST \
  -H Cookie:SESSe6a353351df0bfa8deadcafe=B0ZkiW3-U2x93yJU-deadbeef \
  -H X-CSRF-Token:PSCd5qIdddax0Mh5gfnOM872hdj893-eeeeffff \
  -H Accept:application/json \
  -H content-type:application/json \
  http://myserver/rest/node \
  -d '{
    "type": "forum",
    "title": "test post?",
    "language": "und",
    "taxonomy_forums": {
      "und": "1"
    },
    "body": {
      "und": [{
        "value" : "test post",
        "summary": "this is a test1",
        "format": "full_html"
      }]
    }
  }'

The key difference was, I think, adding this to the JSON:

    "taxonomy_forums": {
      "und": "1"
    },

I guessed this, based on a view of the Firefox firebug Net panel, when using the UI to post a new forum topic. This number specifies the forum to which the new topic should be associated. It is a different matter to get the list of forum topics!

Maybe this will help others.


Render with custom style all contents of a content-type from custom module I am trying to create a custom module to manage a slider.

After install my current-development module, I have:

a slider content-type
a slider view defined to show Content (Full Content) of the content-type slider with Unformatted list format
a node--slider template that renders the slider node as a li element

EDIT: Code updated
You can check the module code here: https://github.com/jmvelasco/drupal

I wonder how could I add a wrapper that contains all nodes of this content-type and call to render each node using the template defined.

The idea I have in mind is define a block like:

        render_node_slider($slider_content)

So the end rendering will be somethink like:

 slider content 1

 slider content 2

         ...

 slider content N

But I don't know how to manage this even if I am pretty sure this is completely possible to achieve.

The accepted answer points to the right direction, from the current state of development, now I'd like to know if I can improve the slider_block_view

https://github.com/jmvelasco/drupal/blob/master/slider.module (line 101-124)

using a templete file defined in the module instead code the html inside a function module. I want also to attach a css and js files when rendering this view.

I'll appreciate any kind of help here.

Thanks for the reading.

If you want to just use the views module.  Set your view to use fields.  Filter by content type and set your display to using HTML List style.  Pickout the fields you want to display (Image, Title).  You can then add your custom javascript through a module or your theme so that it actually runs as a slideshow.

There are other modules that can handle this as well like views_slideshow and owlcarousel.

If you want to keep the code all in your own module, you may want to take a look at this article:

http://www.sitepoint.com/building-drupal-7-module-show-latest-nodes/

It shows you how to create your block, how to query the database, how to use the theme('item_list', $theme_args).  It should be straightforward.


Views multiple entities output I am new to Drupal 7, so I hope I am using the word entity in the right context.

I am using the profile2 module to collect additional information when yours signup. Of course, the users are required to provide an email address and they can also upload a photo of themselves.

My issue is how to use the same view to return a users user information (email, username, photo) and all the profile2 collected information.

When you create a view for users or the profile nodes, you should be able to add a relation to the other one. Not shure thou whether this works in both directions.


how to customize Registration form How to add a fields into custom registration form in drupal7 and how to give the link so that annonmous user can register.

As an adminstrator, you can set additional user fields at:

/admin/config/people/accounts

Note the tabs Manage fields and Manage displays. You can control if and how these fields appear on the registration form, and also how they appear to the user via these tabs. You can even create non-visible fields for storing other kinds of hidden data against a user should you need to.

By default, the link to register is:

user/register

You would normally create a menu item if one doesn't exist already to appear somewhere on your site, or you can just output the link in a suitable location depending on your needs.


Using Workbench Moderation state changes as events I would like to use the Rules module to send out emails to specific roles whenever a moderation state change event occurs on a node. So if a node is saved, and it goes from Draft to Needs Review, this rule would be triggered to send out emails to the Content Approver role.
This was possible in the Drupal 7 version of Workbench Moderation and Rules, but not out-of-the-box with the Drupal 8 version of these modules.
Any ideas what to do here to accomplish this?

We are using Workbench Email to accomplish this on our D8 site, would this work for you?


How can I flush a json response in a controller? Didn't find this when I googled before, posting to maybe save the next person some time.

Maybe obvious for people familiar with Symfony, but was new for me; spent way too long trying to find something so simple:

$json_response = new JsonResponse($my_key_value_array);
$json_response->send();
$this->function_that_takes_a_long_time();


Custom page template for specific node - template inheritance I'm trying to customize the page template for a specific node of a specific content type. This is what I have: Content type: Custom Page Node ID: 2

First, I need to customize all 'Custom Page' content nodes so I created a custom page template for them: page--custom-page.tpl.php

Then, I also need to customize a specific 'Custom Page' node so I created a custom page template for it too: page--node--2.tpl.php

But when I visit the node 2 page it is using the Custom Page (page--custom-page.tpl.php) template and not the page template I created specifically for that node.

How can I make the custom page template for that node work?

Templates are chosen based on the other that they are in the $variables['theme_hook_suggestions'] array.

So if you have a list:

page.tpl.php
page--node.tpl.php
page--node--1.tpl.php
page--node--edit.tpl.php

Then it will look from the bottom up and use the first template it finds.

From Drupal 7 Template (Theme Hook) Suggestions:

  When the page is actually rendered, the last suggestion is checked. If it exists, that suggestion is used. Otherwise the next suggestion up is checked, and so on. Of course, if none of the overriding suggestions exist, page.tpl.php is the final suggestion. This also explains why page--front.tpl.php, if it exists, overrides any other suggestion for the front page: it is always the last suggestion for the page designated as the front page.

Because you have custom code (I'm assuming your code here) that adds a tempalte suggestion to the end of that like this:

$variables['theme_hook_suggestions'][] = 'page__custom_page';

Then that suggestion is added to the end of the list, so will override all previous ones if it is present.

If you want to have different template precedence then you have to make the hook suggestions array use that order.

There are a number of ways you can do this and it depends what you want to achieve as to how you want to do it.

If you want your template to be last in the template precedence (first in the array) then you can do this:

array_unshift($variables['theme_hook_suggestions'], 'page__custom_page');

Other than that you can also use other PHP array manipulation functions to insert your suggestion in the middle of the array, or you could add your suggestion to the end, then add other suggestions after it again (it doesn't matter if a suggestion is in the array multiple times, the first time it is checked it will be used).


From where drupal get the template? if i don't have one I've created a template with the following.

myTheme.info

name = myTheme
description = Just my theme
core = 7.x
stylesheets[all][] = css/myCss.css

regions[test] = Test
regions[content] = Content

template.php

// Empty file

css/myCss.css

// Some styles

Drupal has position content and other blocks, but from where did he gets the template if mine is empty?

Also I get these errors:

  Notice: Undefined index: highlighted in include() (line 126 of Z:\home\test1.ru\www\modules\system\page.tpl.php).
  Notice: Undefined index: sidebar_first in include() (line 138 of Z:\home\test1.ru\www\modules\system\page.tpl.php).
  Notice: Undefined index: sidebar_second in include() (line 144 of Z:\home\test1.ru\www\modules\system\page.tpl.php).

It looks like it was used in the core template, but in my newly created template, I get this errors. Maybe I need to override some hooks? Which hooks should I override?

The variables for which you get those errors are the variables that Drupal uses to output the default regions a Drupal 7 theme should have, which are the following one.

regions[header] = Header
regions[highlighted] = Highlighted
regions[help] = Help
regions[content] = Content
regions[sidebar_first] = Left sidebar
regions[sidebar_second] = Right sidebar
regions[footer] = Footer

The template.php file is not a template file; it's the file containing functions template files use.

When your theme doesn't define a template file, Drupal uses the one defined from the module implementing the theme function. For example, the Node module defines theme_node(); if your theme doesn't have the template file used by that theme function (node.tpl.php), Drupal will use the template file that is in modules/node/node.tpl.php.


How do I use "DOES NOT CONTAIN" with \Drupal\Core\Entity\Query\QueryInterface? I have a node with a list field of text values. I want to write a query that gets all nodes that don't have one of the selected values.

How do I write this query?

$query->condition('field_states_excluded', $state, 'DOES NOT CONTAIN');

You can make use of NOT REGEXP if we assume that $state is an array of multiple states.

I will explain with example:
for example if want to get all nodes with the field title DOES NOT  CONTAIN page, hello, and test.

Sql statement should be something like:

SELECT * FROM `node_field_data` WHERE `type` = 'page' AND `title`  NOT REGEXP '^.*page.*$|^.*hello.*$|^.*test.*$';

Drupal Code:

  $excluded_strings = array('page', 'hello', 'test');
  //- Add regex prefix and suffix
  $excluded_strings_with_regex = array_map(function ($val) {
    return '^.*' . $val . '.*$';
  }, $excluded_strings);
  //- Join array elements with a string | glue
  //- result $regex_p_string = "^.*page.*$|^.*hello.*$|^.*test.*$"
  $regex_p_string = implode("|", $excluded_strings_with_regex);
  //-Build Query
  $query = \Drupal::entityQuery('node');
  $query->condition('status', 1);
  $query->condition('type', 'page');
  //- Add regex Condition.
  $query->condition('title', $regex_p_string, 'NOT REGEXP');
  $nids = $query->execute();


Site Offline After Saving a Setting I'm trying to fix a menu problem for a client - I tried saving new settings in the Appearance tab and I got this error

PDOException: SQLSTATE[28000] [1045] Access denied for user 'tester'@'88.208.252.203' (using password: YES) in lock_may_be_available() (line 167 of /home/linweb12/7/7a7.co.uk-1059923790/user/htdocs/includes/lock.inc).

What would cause this error?

This is a MySql error. MySQL is not getting fed the correct logon information. Can you logon to mysql using your drupal credentials - either by command line or PHPMyAdmin or some other method. If you can't logon it's a credentials problem. Otherwise it's likely a path problem.

In your settings.php file, make sure everything is correct. Double check it

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'MYDATABASENAME',
      'username' => 'MYUSERNAME',
      'password' => 'MYPASSWORD',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),

);


Loading css style present in DOM of another node I am using the module Simple Background Image Formatter to convert an image into a div background image. It has two options - one to put as an inline style of a div or to choose a CSS selector which it styles with a background image in the DOM.
I cannot use the inline style method in views so that is ruled out. Now as per the CSS selector method, it adds a style directly on the page with the 'selectedclass_id'. I can choose the selectedclass but not the id (appears to be randomly added).

However, since my requirement is through views, it somehow (although with wierd settings) automatically prints the class and adds the id, however, the image for other nodes is not loaded in this node as its html style in not loaded in the current page. That is, the image of every page is converted into a
selectedclass_id (background-image:...) and placed in the html of that page but the selectedclass_id of the other nodes which are part of the view in this page are not loaded here with their respective values. Therefore, these images are not being displayed in the view.

Is there a solution here? I want the page to load the css selectors for the nodes which are shown in the view (of the same content type) so that the code for each of the view fields is  where the id will be different for each of the nodes. The current page should have the values of all such nodes in the view as it does with regard the value of the current page. Presently, only the selectedclass_id of the current page is being loaded in the head html style.

An alternative for the module is Background Images Formatter but this is dependent on bg_image which does not have a Drupal 8 version and doesn't work without it.

I have a related content section on my page through views in which i
want one field to be a div with a background-image.

Ok, then you can use Image URL Formatter. Which will output your image as a url instead of the actual image.
Then add the image field, which contains the image you want to use as background

Hide it from display.
Select image url as your formatter

Add a custom field OR Rewrite the result of an existing field and use the image replacement pattern.
ex
OR if you create a .html.twig template file for your view, then you can use

Another option
In Style settings you can add a class to your fields.
[
Then with css give it a z-index: 0; and give everything else z-index: 1; and move img around by giving it position: absolute; top: -100px; etc..


Get all nodes where date field matches month and year I have a content type with a date field (myFieldDate) whose values are timestamps. (I'm collecting only day, month, and year.)

I have a custom form where I have a select list to select month and year.
I need to use the EntityFieldQuery class to get all the nodes where the date field contains the month and the year I specified.

$query = new EntityFieldQuery();
$query
  ->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'horas')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->fieldCondition('field_day', 'value', $myFieldDate, '=');

If the select list contains '2015-05', for example, the query should return all nodes where myFieldDate contains a date for that month and year.

You can use a range like condition:

$query = new EntityFieldQuery();
$query
  ->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'horas')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->fieldCondition('field_day', 'value', $myFieldDate . '-01', '>=')
  ->fieldCondition('field_day', 'value', $myFieldDate . '-31', '<=');


Simple REST request to create nodes I'm having the following issue trying to create nodes from Drupal 7 to a Drupal 6 install. The target Drupal site is running Services 3.x.

Here's my code:

$base_url = $params['path'];
$data = array(
  'username' => $params['username'],
  'password' => $params['password'],
);
$data = http_build_query($data, '', '&');
$headers = array();
$options = array(
  'headers' => array('Accept' => 'application/json'),
  'method' => 'POST',
  'data' => $data
);

$response = drupal_http_request($params['path'] . '/user/login', $options);
$data = json_decode($response->data);

// Check if login was successful
if ($response->code == 200) {
  // Now recycle the login cookie we recieved in the first request
  $options['headers']['Cookie'] = $data->session_name . '=' . $data->sessid;

  // Create a new node
  $data = array(
    'node' => array (
      'type' => 'cloudnode',
      'title' => 'node1',
      'field_ip_address' => array ('value' => '1.2.3.4'),
    )
  );
  $options['data'] = http_build_query( $data, '', '&');
  $options['method'] = 'POST';
  $response = drupal_http_request($base_url . '/node', $options);
}
else {
  die ('Failed to login');
}

I get a 200 response; the node is being created, but somehow it doesn't take care of my 'field_ip_address' CCK field at all.

I've tried any kind of variations but they don't work. There is not much documentation around as well.

If anyone has succeeded in creating nodes using REST, I would be very interested for any help.

CCK fields are always stored as an array of fields, even if the actual field is limited to only a single value.

So you it should be something like:

'field_ip_address' => array(array('value' => '1.2.3.4'))

Note that in Drupal 7, field values are additionally grouped by the language, which is 'und' (LANGUAGE_NONE) if the field is language-agnostic. So it would be something like this:

'field_ip_address' => array('und' => array(array('value' => '1.2.3.4')))

Copied from my comment, so that the question can be marked as fixed :)


Add 'Last modified by ...' footer to each page How do I add a footer to each page generated by Drupal (7) so to show the identity of the last user that modified that page? (together with the modification date)

I think you should be able to do this with something like this, note that this is only pseduo code and is not tested:

 // get the user that made the latest modification
 // for a node of type 'page'
 function getLatestPageUpdater() {
     $query = "SELECT n.changed, u.* FROM node n
               INNER JOIN users u ON u.uid = n.uid
               WHERE n.type = 'page'
               ORDER BY changed DESC
               LIMIT 1";
     return db_query($query)->fetch();
 }

Then in your page.tpl.php you could do like this:

 <?php $user = getLatestPageUpdater();
       if($user):
 ?>

Last edited <?php print $user->changed; ?> by <?php print $user->name; ?>

 <?php endif; ?>

Like @tostinni pointed out Drupal doesn't track the last editor of a node, so the above code would always display the original author of the node. If you're using node revisions I think you should be able to do something like this (again this is only pseudo code and is not tested):

function getLatestPageUpdater($node) {
  $query = "SELECT u.name
            FROM node_revisions nr, users u
            WHERE nr.uid = u.uid
            AND nr.nid = ".$node->nid."
            ORDER BY timestamp DESC
            LIMIT 1";
  return db_query($query)->fetch();
}

<?php if($node->type == "page"): ?>
<?php $user = getLatestPageUpdater($node);
      if($user):
?>

Last edited <?php print $node->changed; ?> by <?php print $user->name; ?>

<?php endif; ?>
<?php endif; ?>


Missing FieldItem properties while in entity::preSave() I have a custom FieldItem that has a single 'value' property that is also a custom TypedData.

This TypedData property holds an object. The \Drupal\Core\TypedData\TypedDataInterface::getValue() on the property(TypedData) returns a string fetched from the represented object and \Drupal\Core\TypedData\PrimitiveInterface::getCastedValue() returns the represented object.

All is working fine but one thing. In my entity which has this FieldItem attached, I update its value in the entity::preSave() operation.

And Drupal started to complain Notice: Object of class ... could not be converted to int in drupal_schema_get_field_value().

And I couldn't figure out why was the represented object used instead of the "plain" value.

After a bit of debugging I have found that when I set the FieldItem's value(I pass an object) in the entity::preSave() the FieldItem's properties are not loaded which will cause the \Drupal\Core\Field\FieldItemBase::__get() fetching the value from FieldItem values array instead of getting it from properties.

Any idea why the properties are not loaded? I was thinking that it has something to do with performance maybe but since the field item is just a wrapper around data types it makes no sense that field item would handle the data itself.

Edit:
Looking more closely at entity values and properties it seems that only computed properties are initialized by default. But real properties are initialized only when \Drupal\Core\TypedData\Plugin\DataType\Map::get() is called. The values are meant for plain values when creating a new entity for example, if I understand it correctly, but I don't get why the properties are not utilized yet.

I will answer my own question...

I am not sure when the property initialization comes to play but adding this code into my field item solved it. The get method will look for the property and initialize it if it does not exists with existing value which will result in the field returning correct data.

  /**
   * {@inheritdoc}
   */
  public function preSave() {
    $this->get('value');
  }


Instalment payments with ubercart I'm building a student application on which we have the requirement that student can pay its fees via instalment.I have googled around the same but I does not found how to achieve it.Does there any existing module for to achieve the similar functionality.If you have any ideas then do let me know how to achieve this.
The instalment payment will be charged only in two instalments(first instalment and second instalment).The amount of the first instalment can be vary from second instalment.

You can use the UC Down Payment module for this task.

This module allows Ubercart store administrators to add partial payment functionality as a product feature. They can assign down payment amount and the due date to any product, and manage down payments and partially paid orders in the admin section.


Redirect to 404 page, if URL alias does not exist I am developing multilingual site in Drupal 8. I added content in Turkish language and did not create any translation for that node.

Suppose node ID is 123, so system URL is http://example.com/tr/node/123. I have managed to redirect the system URL to its alias. So when I go to https://example.com/tr/node/123 I am successfully redirected to https://example.com/tr/custom-node-in-turkish which is perfect.

The problem now is, when I go to https://example.com/node/123 (without tr) or add another language http://example.com/ar/node/123 (ar = Arabic) then I want to redirect the user to the 404 page as these are not the original content.

How can I achieve that in Drupal 8?

You could redirect 301 the specific node id's to 404 using .htaccess file

Redirect 301 /ar/node/123 /page-not-found


hide cck field not working I want to expose the node add form for a particular content type to anonymous users but not with all the fields visible. I want limited fields to be visible to anonymous user.
I have tried to hide the unwanted fields through display fields functionality of cck module, but it does not seem to work.

I also want to theme the node add form in a way that the various text fields with different text sizes should all appear of the same size to anonymous user. Just as a proper form.

Please tell me a way to do this.

You should also have a look at the Field Permissions module, which allows you to control granular permissions per field by role.

By default, if a user can edit a node they can edit all fields, but Field Permissions allows you to create specific privileges for the field if you need more granular control.

So for this instance, you'd want to enable edit privileges for the fields you want to hide from the anonymous users, then go to user permissions and grant edit permissions for those fields only to authenticated users.  The result would be that the fields would be hidden from anonymous users, but still editable by authenticated users.

You could then use the Forms API as Dan described to make the fields all of a length for anonymous users, or use something as simple as CSS if your theme attaches a body attribute for logged-out users (many do).


How do I get the vote result in Vote API? I have installed the rate module, and found out that the votes associated to a node are stored in the votingapi_vote table.
Is there a function to use to get the sum of all the votes for a node?

As you have installed the Rate module, then you can use the function rate_get_results(), which can be called as rate_get_results('node', $nid, $widget_id); $nid is the node ID of the node for which you want to get the result, and $widget_id is the identifier of the widget used to cast the vote.
The result is an array that contains many values (some of them are present only for a particular widget); in particular $output['rating'] is the rating, and $output['count'] is the number of the votes.
If the widget saves the sum of the votes, then $output['rating'] (where $output contains the result returned from rate_get_results('node', $nid, $widget_id)) contains the sum of the votes, which is what you are looking for.


Trying to send a  with webform I have a Webform that does some calculations (javascript) based on user selections, which i would like to send along with the user-selectable fields to a user's email.

Is it possible to append these div's to the HTML email along with the fields?

You could add a regular webform field to capture the calculation result, filling it via Javascript.
Then you hide the field via CSS.

Storing a bunch of html has a security risk though.


How can I show parent and child terms in facet search filter block for a taxonomy field having simple hierarchial select as widget type I am using facet filter to filter views values . I have a taxonomy term using widget type [Simple Hierarchial Select][1]  . I want to be able to filter parent and child terms both in facet filter block

Tax A
-- Tax A child
---- Tax A child of child

I want to use each one of the above as a filter in the facet filter block

How Can I achieve it?

I have ticked 'index hierarchy ' but it just shows the deepest term e.g. "Tax A child of child"

http://example.com/admin/config/search/search_api/index/*server name*/workflow

I'm presuming you are using FacetAPI and Search API Solr.

You need to add some settings to the facet itself at Search API > Index > Facets > [Taxonomy name]:
http://example.com/admin/config/search/facetapi/[indexname]/block/field_[taxonomyname]/edit

You'll need to

Expand the hierarchy
Treat parent items as individual facet items
Don't flatten hierarchy
and minimum count zero (ie: show even when empty)


Why does form ID get displayed to drupal_set_message? I'm upgrading from 6 to 7 (thankless task!) and Ive noticed that in the admin section the name of any form that is on the page seems to get output to drupal_set_message (it appears in the green box) I thought this to be unusual but possibly deliberate on the part of the module author. However, in my custom module I have a form and when ever I go to the page the name of the form appears in the green status box.

Can anyone shed any light onto why this may be happening?

You may be having hook_form_alter(&$form,&$form_state,$form_id) in your code
possible code in your custom code will be

function hook_form_alter(&$form,&$form_state,$form_id) {
//just remove the below line to disable the message
drupal_set_message($form_id);

}