How to create (& pre-populate) multiple “field collection” fields on an ajax call This is an extension of this question - "How to pre-populate multiple "field collection" fields in node form"

I'm trying to do the same thing, but I'm trying to get it to work on an ajax call rather than on the form load.

The form loads, the user selects an option on a dropdown and then the form automatically populates several field collections with ajax.

The Problem

The existing solution on the question above involves altering the form when it's first built, by changing:

 $form_state['field']['--machine-name-of-field--'][LANGUAGE_NONE]['items_count']

And then rebuilding the form using the new form state values.

The problem with an ajax call is that, it seems to ignore any changes made to $form_state in the callback. i.e.

function ajax_get_parent_field_collection ($form, &$form_state) {
  $form_state['field']['field_collection_entity']['und']['items_count'] = '3';
  return $form['field_collection_entity'];
}

The changes made in $form_state above are ignored, so when the form is rebuilt nothing happens and if you then dump $form_state none of the changes made are saved.

I could manually create the field collection entities and insert them, but I was hoping there's a cleverer answer. Has anyone tackled this before?

EDIT:

The ajax is currently called on a select field, so the ajax triggers when the select dropdown is used.

$form['field_company_for_center']['und']['#ajax'] = array (
  'callback' => 'ajax_get_parent_field_collection',
  'wrapper' => 'ajax-wrapper',
  'effect' => 'fade',
);

The form needs to be build again after items_count is changed.

function MYMODULE_form_alter (&$form, &$form_state, $form_id) {
  if($form_id == 'MYFORM'){
    $form['#attributes']['id'] = 'MYMODULE-form-ajax-wrapper';

    // Handle triggered ajax element.
    if(!empty($form_state['triggering_element']['#array_parents'][0])) {
      if ($form_state['triggering_element']['#array_parents'][0] == 'field_node_reference') {
        $form_state['field']['field_collection_entity'][LANGUAGE_NONE]['items_count'] = '3';
      }
    }

    // Add ajax callback.
    $form['field_node_reference'][LANGUAGE_NONE]['#ajax'] = array (
      'callback' => 'MYMODULE_ajax_rebuild_form',
      'wrapper' => 'MYMODULE-form-ajax-wrapper',
    );
  }
}

/**
 * Ajax callback, rebuilds and returns the entire form.
 */
function MYMODULE_ajax_rebuild_form ($form, &$form_state) {
  return drupal_rebuild_form($form_state['build_info']['form_id'], $form_state, $form);
}


Dynamic Content Fields I am new to Drupal. using drupal 7

I would like to have dynamic fields in content type.
basically i would like to allow users to add a content and in that content, fields should generate dynamically.

for example if user has select  CAR the next field (MODEL) should be generated dynamically according to first one having all the model for that particular car and so on.

i know about "hierarchical select" but its not good for me. conditional fields are still under development.

search a lot but did not come out with any solution. please help.

thanks

Despite your statement in your question, Hierarchical Select is the standard way to approach this sort of need.

There's likely no other stock solution for this, since no one bothered to duplicate HS.


Image block module translate I have created block using image block module. I want to translate block content in other languages. I have used i18n module for translation. currently I only translate the title of the block. But I also want translate body content. So,please anyone help me. Thanks in advance

I believe the image block module is not yet fully compatible with i18n module and you will need to apply the patch in this issue which according to the posters is reviewed and ready to be committed.

Alternatively you can install nodeblock and create a content type (i.e. block) and use it as a nodeblock and you will get all the benefits of nodes and blocks.  Therefore you can add image fields or any other fields that you need and after creating a node of that content type you will be able to add it in a region of your theme like a normal block. Nodeblock supports translatable content (Contrent translation with i18n and Entity Translation).


Prevent dual submit on form submission I've got a form that submits via AJAX and in the callback I need to rebuild certain parts of the page to reflect the newly submitted data. One of these parts is the form, which I need to clear all user input values from so it's ready to use again.

$response = new AjaxResponse();

// Remove all user submitted values
$form_state->setValues( array() );
$form_state->setRebuild( TRUE );

// Build a new instance of the form
$form_object = \Drupal::service('class_resolver')->getInstanceFromDefinition('Drupal\tpl_project\Form\MultiContactForm');
$form_object->setCompany( $company );
$replacement_form = \Drupal::formBuilder()->buildForm( $form_object, $form_state );

// Replace the old form with the new one
$response->addCommand(new HTMLCommand('.form-container', $replacement_form));

return $response;

When the form is submitted it runs the validation callback, the submit handler, then calls the above ajax handler. When it rebuilds the form in the above process, it fires the validation and submit handles again, thus storing two records.

How can I prevent this from happening and still rebuild the form to display no user input all within the same request?

Any help greatly appreciated.

See if this will help: How can I implement AJAX form submission?

It's a pretty decent checklist for ajax form operations.


How to change default registration form? By default, user registration form in Drupal 7 takes 2 fields: "Username" and "Email."

I want users to set their password directly upon Registration.

Take 4 fields:
- Username
- Password
- Confirm Password
- Email

How can I do so?

In  Administration » Configuration » People » Account settings, uncheck the Require e-mail verification when a visitor creates an account. option. This will allow user to directly enter their password on the registration form.


Counting each filter near its label I've created a view in order to override the default search page form and results, then I've exposed the content type in order to have the possibility to filter by that, all now is working

How can I have the count of the relative content near each content type label on the filters?

Sounds like you want to use search facets.  Facets are ways of showing various search 'tag' information for the current results with/without counts.  Note that this is slightly different from a filter which will show all values even if there is no result with the specified search criteria.

That said, there is a defunct facets core search module. As the module page says, the best way to approach this with Drupal 8 is to use the Facets module which requires the Search API module with the included Search API DB engine (no Solr required).

This will add a bunch of extra functionality that the core search will not handle.  Stuff like full text search across multiple text fields, stemmed searches (e.g. search for work also finds working, works, and the like), ability to show extracts (were the word was found), and much more.


Total number of published comments from the logged in user On our Drupal 6 site we are looking at setting up this rule for comments:

1) If you don't have an approved (i.e. published) comment then your comment goes into the moderation queue

2) If you have an approved comment, then your comment is published straightaway

Is it best to use Rules in Drupal? How can we check how many published comments a user has? Custom PHP code perhaps?

Any help appreciated!

You do not have to execute a rule every time a user submits a comment. If you have approved a comment for the user, then the permissions systems can handle it.

First create a new role 'Comments approved' and give the role a single permission to 'Publish comments without approval'.

Then create a rule triggered on the event 'After publishing a comment'. Have the rule perform the 'Add user role' action giving the comment author the Comments approved role.

This will mean that the user will be able to publish comments after you have approved their first one, and you will be able to remove the role from the user if they abuse the privilege.

If you want to get really fancy, create another role called 'Moderation only' with no additional permissions. If you have to control comments from a particular user, assign them this role, and in the conditions for the rule, check to see if they are a 'Moderation only' user, and do not assign the 'Comments approved' role if the 'Moderation only role' is present.


How to limit webform submissions access to only users who have Webform submissions? I am using Webform for surveys. But I want to permit users who have submitted to see all results. In other words: to see all Webform submissions.

Any user can submit but no user can't see all results without submission.

Any ideas or suggestions?

Maybe not a complete solution but here is how you can start of

create a view that displays submissions
make it available to everyone (view has permissions)
put it in a URL that is not linked from your main site (its like being hidden but not exactly)
put the URL link at the submission completion page (thank you page)

beware this will not prevent a person that knows this URL to visit it and see the results.  I am not aware at this point of a module that will give the required permission see results after submission or something similar so if the above is not to your satisfaction then you might want to create a module to do that or modify webform to include such a feature


How to dynamically assign submit hooks to webforms when generating blocks in mymodule_block_view I am generating some blocks for my site, depending on configuration data stored in the database. Some of these blocks may have Webform front ends:

$block = module_invoke('webform','block_view','client-block-' . $r['webform_nid']);

At the point above when I fetch the webform, I would then like to attach a custom submit hook to the webform. The submit hook will need access to the values entered into the webform by the user, and also some variables which are available to the block (so would need to be passed through to the webform somehow).

The submit hook needs to be selected dynamically by the block code, it won't be the same every time.

Any help much appreciated.

UPDATE - HOW I EVENTUALLY SOLVED THE ISSUE

As Shawn says in his reply, webform_block_view returns a rendered webform, with no access to $form_state, so there is no way to pass information into the form. Instead, I figured out how to use drupal_build_form from within my module_block_view to generate the webform:

$node = node_load($webform_nid);
$form_state = array();
$form_state['build_info']['args'] = $node;
$form_state['rebuild'] = FALSE;
$form_state['foo']['bar'] = $bas; // block specific info passed into form
$block['content'] = drupal_build_form($webform_name,$form_state);

I then added code into my module_form_alter as per his suggestion, to add the custom submit hook to the form. The submit hook then checks the foo and bar variables passed through from module_block_view and behaves accordingly.

WATCH OUT FOR ...

One thing worth mentioning for anyone reading this page in future, is NOT to use $form['storage'] for storing custom form data when using webforms, as the webform module rather rudely destroys $form['storage']. This took me a long time to discover!

From _webform_client_form_pages_ in webform.module

// Determine what we need to do on the next page.
  if (!empty($form_state['save_draft']) || !$form_state['webform_completed']) {
    // Rebuild the form and display the current (on drafts) or next page.
    $form_state['rebuild'] = TRUE;
  }
  else {
    // Remove the form state storage now that we're done with the pages.
    $form_state['rebuild'] = FALSE;
    unset($form_state['storage']);
  }

webform_block_view() returns a block object that already has the rendered webform. At that point, you're not going to be able to make any form altercations need for your custom submission handlers.

However, you can add a hook_form_alter() invocation to your custom module. Webform generates a standard form id for each form webform_client_form_NID.

MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'webform_client_form_NID') { //@TODO: substitute NID for your webform NID
    $form['#submit'][] = 'MYMODULE_webform_client_form_NID_submit';
  }
}

If you need to pass data from your hook_block_view invocation to your hook_form_alter invocation, a global variable should help there.


How do I include the full body field in the RSS feed for a taxonomy term? How do I include the full body field in the RSS feed for a taxonomy term?

I tried enabling the default taxonomy view in Drupal, but it doesn't let me select any fields in the field list area.

Drupal 6:

The easiest way is to:

Change the setting in
/admin/content/rss-publishing

Or:

Install views
Enable taxonomy_term view
Edit the 2 Feeds

Click on the gear right of Row Style
Change to full text


Reset View result counter after changing page (manually or with Twig) Drupal 8

I have a View that uses the View result counter starting at '0'. It works great, except for the fact that when you change to Next page the counter doesn't start off at '0' again, but rather continues on.

I tried using Twig modulus to get a circular-list (always reset back to 0), the reason I use 10 is because my pager displays 10 items.

{{ counter % 10 }}

It doesn't work, it always prints 0 for some reason. But if I do {{ 11 % 7 }} it prints the correct result which is '4'.

Does anyone know either of these:

Can I force view to restart counter at '0' when it goes to other pages int he pager?
Why is Twig not printing the proper math result of {{ counter % 10}} ? (Keep in mind that doing things like {{ counter + 1 }} don't work either. For some reason it only works when you use only numbers like {{ 1 + 3 }}  )

Thanks.

It doesn't work because counter is actually an object with the value as a property, that's done to properly handle markup or special characters and preventing them from being escaped multiple times.

Depending on what template you're overriding and where, you could possibly do this in twig, especially if you are where you are loop over the rows already, although that might be a bit complicated.

My/the backend developer approach would be to make your own counter views field/plugin that doesn't consider the pager. This logic happens in \Drupal\views\Plugin\views\field\Counter::getValue(). So you can copy this  class into a custom module, rename to NoPagerCounter or so, and change the annotation to @ViewsField("no_pager_counter"). Then you remove the pager related part in the getValue(). Now you just need to implement hook_views_data() and define this as a field, just like views_views_data does with the counter:

  $data['views']['no_pager_counter'] = array(
    'title' => t('View result counter (no pager)'),
    'help' => t('Displays the actual position of the view result'),
    'field' => array(
      'id' => 'no_pager_counter',
    ),
  );

(Possibly with a better title/help, I just switched the ids)

Another variant of that would be to add an option for this to the existing class and provide a core patch/feature request for this. If others agree that it is useful then it might eventually get committed and you don't need to maintain custom code, but you will have to maintain the patch until then.


Custom ckeditor.styles.js possible to specify for any/all elements? In the ckeditor.styles.js can you leave the element blank or specify multiple elements in a single line? Ex. if the class .red could apply to any element, do I actually have to write out a line for every possible element?

{ name : 'Red' , element : 'p', attributes  : { 'class' : 'red' } },
{ name : 'Red' , element : 'h1', attributes  : { 'class' : 'red' } },
{ name : 'Red' , element : 'h2', attributes  : { 'class' : 'red' } },

etc...

Or is there an easier way?

I also searched for a way to specify multiple elements for one style - and it doesn't seem to be documented anywhere. I was successful with specifying multiple elements as an array:

{ name: 'Red', element : ['h1', 'h2', 'p'], attributes: { 'class': 'red' } }

This works for me in CKEditor 4.2.1.


How to Remove '-None-' option from Select List Field? How can I remove the default option -None- in the Select list?
It should not be an option in my select list.

Edit the filed and make one of the option as default value in the select list and Make it required field.


db_query('SELECT nid FROM uc_products'); doesn't give any results! Why? There's a really simple query related to the enabled and working Ubercart, where the task is to get all the nids from uc_products table, which simply doesn't give any results:

$query = 'SELECT nid FROM uc_products';
$result = db_query($query);
dsm('===================================================');
dsm($query);
while ($nid = db_result($result)) {
    dsm('$nid: '.$nid);
}

BUT when I run the very same query in the same database in phpMyAdmin, it works, and it gives me ALL the correct results (I have 8 products now).

BUT the following queries work correctly, and give me all the expected results (the first is the strangest, because vid field is of the same type, but only has another name):

$query = 'SELECT vid FROM uc_products';
$result = db_query($query);
dsm('===================================================');
dsm($query);
while ($vid = db_result($result)) {
    dsm('$vid: '.$vid);
}

$query = 'SELECT * FROM uc_products';
$result = db_query($query);
dsm('===================================================');
dsm($query);
while ($row = db_fetch_object($result)) {
    dsm('$row->nid: '.$row->nid);
}

$query = 'SELECT nid FROM node';
$result = db_query($query);
dsm('===================================================');
dsm($query);
while ($nid = db_result($result)) {
    dsm('$nid: '.$nid);
}

Here's a screenshot of the test results:

As you can see, the first two queries don't return any results, while the others work correctly.
This is a really strange problem. I didn't modify the core modules, so I don't understand the situation. It doesn't matter whether I run it on localhost or my ongoing public server, the result is the same. This means that uc_order_condition_has_products_form() in Conditional Actions menu doesn't work correctly either. I've never ever met such problems in Drupal.

Does anyone have a clue where I should start debugging?

I think it is likely because your first result is a "0" and php will evaluate that as a False, which stops your while loop from running.


How to determine if the current Drupal page is a contact page? With Drupal 8, in THEMENAME.theme I can generate a class based on the current node ID which will be inserted in the body tag :

In the THEMENAME_preprocess_html() function, i use :

$node = \Drupal::routeMatch()->getParameter('node');
  if($node) {
    $variables['attributes']['class'][] = 'node-' . $node->id();
  }

But how can i determine if we are on the contact page since it is not a node ?

Have you tried

\Drupal::routeMatch()->getParameter('contact_form');

This returns an object of type ContactForm when the user is on a contact page. A simple detection you can do with getRouteName():

if ('entity.contact_form.canonical' === \Drupal::routeMatch()->getRouteName()) {
  // huhu, a contact form
}

You can have a look at ./core/modules/contact/contact.routing.yml. There are all routes available.


Get Username from UID with Preprocess for Template I'm a bit lost at finding the username based on the uid. I get the uid from the address using:

  $current_path = \Drupal::service('path.current')->getPath();
  $urluid = (explode("/",$current_path));

  $us = \Drupal::entityTypeManager()->getStorage('user')
  ->loadByProperties(['uid' => $urluid[2]]);

  kint($us);

returns an array of data where i do see the uid, but not the username for that uid. Name:

'name' => array(1)
*DEPTH TOO GREAT*

returns NULL:

kint($us->name);

I'd like to return the UID->Name as the title on the ROLES and EDIT screens for the user. Exactly how it is returned for VIEW (example dvweb is: /user/10):

EDIT:::

Was able to get it with:

  $u = Drupal\user\Entity\User::load($urluid[2]);
    kint($u->getUsername());

It's better to use the route instead of the path, where you'll find the already loaded user entity:

if (\Drupal::routeMatch()->getRouteName() == 'entity.user.canonical') {
  $user = \Drupal::routeMatch()->getParameter('user');
  $username = $user->getUsername();
}


Multiple Content Types sharing a lot of common fields I wanna have three types of Events on my website. All three types of events have common fields such as: name, date, location, time, host, price.. and many more.

Now each event type has few extra fields that do not apply to other events types.

It is very important requirement in UI administration form not to show fields that do not apply to a specific event type.

I was considering the idea of creating 3 separate Content types (one for each Event type), but somehow I feel this is not the best way to go since there is a lot of common elements.

Any suggestions?

If the content types share the majority of fields, it makes sense to keep them as a single content type.

I'd suggest adding a field for "Event type" or similar to record what sub-type of Event the content is and perhaps group the additional fields in fieldsets.

You can then show/hide the additional relevant fields with hook_field_attach_form (or equivalent) by setting '#access' => FALSE on the relevant field.

If you don't mind showing the fields to the user, you could also use a module like conditional_fields (D7 dev works ok)


Not able to print variables of content type I want to print variables of a particular content type, but I have not found any way. Here is my code.

function mytheme_preprocess_node_mytype(&$vars) {
  echo '<pre>';print_r($vars); echo '</pre>';
}

This function is in template.php. Is there a problem with my code?

Try this: (D7)

function YOURTHEME_preprocess_node(&$vars) {
  drupal_set_message('<pre>' . print_r($vars, true) . '</pre>');
}


Convenience of inserting external data (products) as Drupal nodes I am building a multisite/multidomain site in Drupal 7. We have a section which will show details of thousand of products of the company and clients. We manage these products with an independent management tool. Is it recommended to insert these products in the database as nodes in order to get full capability of Views listings, search functions, etc.? I was going to use just PHP to manage listing, details page, etc., but I am no sure if keeping them outside of Drupal is a good idea. If it is better to include them as nodes, or any other entity... what contributed modules would be recommended and what would be the best approach? (Import them as csv files in a commerce module, insert them directly in nodes and related tables...).

IMHO, you have this choices :

Use the Feeds module to import data to nodes via CSV file, and you can use the powerful Views module to list all your product, or develop a simple module that can do that.
Use can develop a module that build entities based on your tables, with this approach, you can use your database without creating nodes/terms or other stuffs, but you need to create an admin interface to manage all your tables
If you plan to sell your products online, try to use Drupal Commerce, and import with Feeds module


Multiple URL for one Drupal 8 website configuration I want create one Drupal 8 website (one database) with changing contents depending of the URL the user used, I mean:

If the user goes to the main URL http://foo.com, the main page of the website is loaded and contains some content generated for the http://foo.com URL
If the user goes to the main URL http://faa.com, the main page of the website is loaded and contains some content generated for the http://faa.com URL

I can manage that with Apache settings. But how can I configure Drupal? If a user uses the URL http://foo.com and then, he goes to the subpage /test, the URL must become http://foo.com/test.
But, if a user goes to the site with the URL http://faa.com and then, he goes to the subpage /test, I want the base URL still http://faa.com (http://faa.com/test).

I've handled this situation very easily by setting two different Apache VirtualHost with the same DocumentRoot.

The thing you have to be very careful is the page caching of Drupal. I recommend you to read the Cache Context document on Drupal 8 who is very helpful for your situation. By passing the "url" cache context on your different render arrays, you will prevent the content of a URL to be displayed on the other.

Drupal routing system doesn't take the domain name. So there'll be no problem and a user who go on a subpage from a domain name will stay on this domain name.


Allow some products to be sold only in bundles (groups) with some other products I'm making a commerce site with Drupal 8 and Drupal commerce and I have a not so common request. Some of the products should be available to buy only in groups (bundles) with some other products. E.g. if you want to buy product A in quantity 100 you must also buy product B, product C and/or product D and sum of them (B+C+D) must also be 100. Other way it shouldn't be possible to buy any of them separately.

I saw that there are some Bundle modules (not even sure if they could fulfill this request), but they exist only for Drupal 7.

So is there some module for D8 which will allow grouping products like this. If not what would be the best way to achieve this feature?

As far as I know, there are no supported modules to acheive what you want.

So if you want a sustainable and future proof solution, you should probably code it yourself.

I would go for solution, where I create a custom entity type, Product Validation.

Here are some fields, that I think it should contain:

Product ID (The product it's active on).
Applies above (quantity) (A minimum quantity that must be purchased, before the validation is applyed).
Depending products (Products that be must purchased too).
Min SUM (The minimum sum of all the depending products).

Those are just fields that should probably be there, you can always add more fields like, if only one of depending products must be purchased, or all of them, maybe also support for multiple product ID's to avoid creating duplicates, etc.

Then add a custom validate handler, when the user clicks the place order button on the cart page.

EDIT: To alter the cart form you could use hook_form_alter, and check if (strpos($form_id, 'views_form_commerce_cart_form_default') === 0.
The cart form has a unique ID per order so that's why you want to do like that. Then you can add $form['#validate'][] = 'MY_MODULE_product_validation', where the logic will then be.

Your logic will look similar to this:

$product_validation = $entityTypeManager->getStorage('product_validation')->loadByProperties([
  'product_id' => $product->id(),
]);

if (isset($product_validation)) {
  if ($product_validation->getAppliesAbove() > $product->quantity) {
    $total_quantity = 0;
    foreach ($product_validation->getDependingProducts() as $dep_product) {
      // Check if $dep_product has been added to cart.
      // If yes $total_quantity += $cart->getItem('something')->quantity.
    }
    if ($product_validation->getMinSum() >= $total_quantity) {
      return TRUE;
    }
    return $form_state->setError($form, 'something');
  }
}

OBS: This code is using dummy variables and is intended to help you understand the logic, not as a "ready to implement" solution.

I hope it all makes sense.


How to get node url from Entity Reference field? We have an ECK Bundle that has an Entity Reference to Article and Basic Page content type. In the twig template we are using the following line below to get the node's nid value and then using that in the twig template to create a link to that node. However, we are getting the following error message while logged out (for logged in users it works fine).

How can we get the node's url for both anonymous and logged in users?

Twig template (eck-entity--component--eck-ref-node--default.html.twig where eck-ref-node is the eck bundle name):

{% set field = entity.field_eck_ref %}
{% set ref_node = field.0['#node'] %}
{% set nodeId = ref_node.nid.value %}
{% set nodeURL = path('entity.node.canonical', {'node': nodeId}) %}

<a href={{ nodeUrl }}>
...
</a>

Error:

  Uncaught PHP Exception
  Symfony\Component\Routing\Exception\InvalidParameterException:
  "Parameter "node" for route "entity.node.canonical" must match "\d+"
  ("" given) to generate a corresponding URL."

#node is usually part of a render array. Don't know why you named this entity. If it were a real entity object, then you could get the node id directly with .target_id instead of ['#node'].

The problem with keys in render arrays like #node is, they are only included if needed for rendering, so it's not a good idea to write code which fails if it does not exist.

You have to look for the entity object. According to the template doc the entity is named eck_entity:

{#
/**
 * @file
 * Default theme implementation to display an ECK entity.
 *
 * Available variables:
 * - eck_entity: The full ECK entity with limited access to object properties
 *   and methods. Only "getter" methods (method names starting with "get",
 *   "has", or "is") and a few common methods such as "id" and "label" are
 *   available. Calling other methods (such as node.delete) will result in an
 *   exception.
 * - content: All ECK entity items. Use {{ content }} to print them all,
 *   or print a subset such as {{ content.field_example }}. Use
 *   {{ content|without('field_example') }} to temporarily suppress the printing
 *   of a given child element.
 * - attributes: HTML attributes for the containing element.
 *
 * @see template_preprocess_eck_entity()
 *
 * @ingroup themeable
 */
#}

If this is the template you use, then try something like this to access the field object and the target id of the node:

{% set field = eck_entity.field_eck_ref %}
{% set nodeId = field.0.target_id %}

This works independently of user permissions.

And only build the url when you are sure you have a node id, because otherwise your code still fails if the field is empty.


Programmatically validate required fields of node object I want to know if a node object could pass the form submit.
With the UI, if required fields are missing, you can't save the node.

I would like to load the node object programmaticly, and check if all required fields are set. Is there a easy way to check that ?

Passing form submit means passing the form's validate handlers. Once validation is passed, the node is written into database and no more validation will be done(not sure about this). That's why node_save api function does not return anything.

It means that "Required" fields are to be validated only in the Form validator. You can however choose to even write a Node without "Required" fields filled in. For example to can choose to empty "Required" fields in hook_presave(D7).

node_load does not check if all fields are set or not. It simply creates a node object which is consistent and also calls various hooks. It saves us from portability issues if we were to write our own functions to read the database and build node object.


How do I generate URL by term_id I have a taxonomy term ID that I would like to generate the the URL alias for. In other words, instead of /taxonomy/term/{id} I would like to get the alias I have defined for this, eg: /some/path/myawesometerm.

How can I accomplish this?

What you are calling "URL aliases" are referred to by Drupal 8 as "path aliases."

The path.alias_manager service (\Drupal\Core\Path\AliasManager) allows to lookup path aliases.

$aliasManager = \Drupal::service('path.alias_manager');
// The second argument to getAliasByPath is a language code such as "en" or LanguageInterface::DEFAULT_LANGUAGE.
$alias = $aliasManager->getAliasByPath('/taxonomy/term/' . $term_id);

But what use is a path alias? The end result is probably to put it into a link render element. \Drupal\Core\Url::fromRoute should also be a valid option as that will translate into any path alias anyway. It is not exactly clear from the API documentation that it does this, but it does.

$link = [
  '#type' => 'link',
  '#title' => 'Taxonomy term ' . $term_id,
  // Passing in 'language' key as the third option is preferable here so that a language-dependent alias can be found.
  '#url' => Url::fromRoute('entity.taxonomy_term.canonical', ['taxonomy_term' => $term_id])
];


Can I downgrade to drush 5.x using homebrew? I used brew install drush which installed the latest stable version (6.1), when I need the 5.x branch.

This GitHub issue indicates a drush 5.x package was made available for homebrew, but I'm unsure how to install it.

Homebrew install specific version of formula? - this answer on drupal.stackexchange might help you to get the overview of how specific formulas can be installed via homebrew.

Short version related to your specific question:

Update homebrew with brew update.
Get all the versions available for drush formula with brew versions drush
You will see a list of commits that point to specific drush versions, e.g.,

6.1.0    git checkout a188056 Library/Formula/drush.rb
6.0.0    git checkout 1264aaf Library/Formula/drush.rb
6.0-rc4  git checkout 39b2450 Library/Formula/drush.rb
6.0-rc2  git checkout 2a61472 Library/Formula/drush.rb
6.0-beta1 git checkout 54ba68d Library/Formula/drush.rb
5.9      git checkout 81108ad Library/Formula/drush.rb
5.8      git checkout 91cb127 Library/Formula/drush.rb

Go to the base brew directory by typing cd $( brew --prefix )
Uninstall your current drush installation with brew uninstall drush (this won't affect your settings in ~/.drush directory).
Checkout the drush formula for specific commit that you are interested in. If you want to have drush version 5.9, type git checkout 81108ad Library/Formula/drush.rb and you will have a brew formula available for this particular version.
Install drush (version 5.9) with brew install drush
Type drush --version to make sure you have the correct version installed.


How to add filters to a custom entity type listing page I have a custom entity type and a list of entities of that types shown on a standard listing page.

But I need to have some filters similar to what we have on a node list page

How could I do that ?

The simplest way is create a view like "Content View"
More information can be found in /admin/structure/views/view/content
Another way, you can create a form expose for that EntityListBuilder


Install module that requires composer on server with only FTP I am working on website that only has restricted ftp access. Ya, no way around it.

I want to install the module PHPmailer, which uses composer to install libraries.

I have a local composer run dev site, from which I installed properly, then moved the module dir, and composer.json, composer.lock to the server, but when installing the module on the server I get the error

Please install the PHPMailer library by executing 'composer update' in your site's root directory. (Currently using PHPMailer library version Missing).

Does composer update the database or what is going on here?

How can I easily install a module that made it self dependant on composer?

That error message is called from the modules install file.  It's checking to see if the PHPMailer class exists, and if not, let's you know the library needs to be installed before you can install the module.

If you successfully installed the module on your local dev site, then Composer downloaded the PHPMailer library to the root 'vendor' folder.  In the 'vendor' folder there should be a 'phpmailer' folder.  You just need to copy this folder over to your website's server (to it's root 'vender' folder) and then you should be able to install the module.


Can someone explain how Text Formats work with CKEditor profiles? Very confused sorry if this is a silly question, but I'm stuck.  I'm trying to figure out the relationship between profiles configured in CKEditor and those configured in Config>Text Formats.

Some context:  In CK editor (Config > CKEditor), I set up three text editor formats:
- "Admin": Full editor for admin
- "Editor": Filtered-but-robust text editor for editors and bloggers
- "User": Filtered-but-VERY-simple text editor for everyone else.

In CKEditor, I don't see a way to assign these profile to different roles.

When I head over to Config > Text Formats, I DO see the ability to assign them to roles, and some configuration options.

Can someone explain the relationship (if any) or what I am missing?

Thanks in advance!

The text formats have to do with how the text is being processed as you can have functions that process icon labels, tokens, video snippets, etc. Sometimes you don't want certain roles to have access to these properties.

For example, I wouldn't want to give a normal user access to add certain HTML tags or YouTube video tags, but I would want to give that access to a content editor.

With CKEditor, you can then assign a CKEditor profile with a certain set of buttons to each text format. For example, I would give a CKEditor profile with a lot of buttons and functionality to an admin or content editor, so I would pair that with the Full HTML text format, but I want to slim down the CKEditor profile for a regular user, so I would pair that with the Basic HTML text format (if I created one).


How to show/render 'Add to Cart' button? I have a Commerce Kickstart 2 site.  I know how to create products and variations.  I used the Omega Kick Start theme and have implemented my own template files for the entire site.  Now I need to theme the shopping basket, starting with the "Add To Cart" button.  For the life of me - cannot get it right.

I've already tried the advice from this question -  but no luck.  For the record, my reference field is setup to render / display as Add to Cart form:

The Shopping cart block from Kickstart is enabled and set to my Content region:

The template file to render my product starts off like this:

<?php
$nodew = entity_metadata_wrapper('node', $node);

/* Manually extract the product ID to get a new wrapper */
$product_id = field_get_items('node', $node, 'field_product')[0]['product_id'];
$productw = entity_metadata_wrapper('commerce_product', $product_id);
?>

<?php echo $nodew->title_field->value(); ?>

<?php echo $nodew->body->value(); ?>

    <?php } $duration=$ nodew->field_duration->value(); if (!empty($duration)) { ?>

 Duration -
      <?php echo $duration; ?>

    <?php } $assignments=$ nodew->field_assessments->value(); if (!empty($assignments)) { ?>

 No of assignments -
      <?php echo $assignments; ?>

    <?php } ?>

What I would like to do is add/show the default, standard Commerce Kickstart "Add To Cart" button below all these attribute fields, and then hopefully I can use the standard commerce kick start shopping basket system (allowing me to just theme the relevant pages).

Just a side note - if I change the theme back to the Omega Kickstart 7.x-3.4 theme - my products show, and obviously the Add To Cart button as well, so I am fairly sure I did not break anything (uninstalled a module that was needed, or something like that).

There are a couple of things I would try to see what is going on.In the post that you referenced, they said the following code. render($content['field_product']).

Have you tried just rendering the whole content using the following render($content), which for you I think would be render($productw). This should render the whole product including the add to cart button.  I am guessing that if it doesn't show up then, then there is something wrong with how you are getting the content and field_product isn't even available to render.

Also, which display are you affecting when you change your product reference to Add to Cart form?  Your default or your teaser? Are you modifying the right template?


In Commerce 2, how can I load an order item's 'purchased entity' object given its ID? I have need to load an order item's 'purchased entity' object so that I can object the base product's title for an order item.

In my scope, I have the order_item object and, from there I have access to the 'purchased entity' ID number. But I can figure out how to load the 'purchased entity'object from this ID number.

EDIT:

Thanks to Chance G I was able to achieve what I needed by:

  $product_variation = $order_item->getPurchasedEntity();
  $product_id = $product_variation->product_id->getString();
  $product = \Drupal\commerce_product\Entity\Product::load($product_id);
  $product_title = $product->getTitle();

If your $order_item is an instance of the OrderItem class you should be able to do:

$product_variation = $order_item->getPurchasedEntity();
$title = $product_variation->getTitle();

If you have an $order you should be able to do:

foreach ($order->getItems() as $order_item) {
  $product_variation = $order_item->getPurchasedEntity();
  $title = $product_variation->getTitle();
}


How can you display the current user's name in the header region? I created a new user. When they logs in, they should to see their user name in the header region.

I can create a block for header but I am not sure how to create a block that displays the username of the logged in user.

Using php filters is not recommended.

Instead create a User view for it.

Steps to creating a user view:

Go to Admin -> Structure -> Views
Click on "Add new View"
Now simply create a User view.

Click on Continue and edit button.
Add a contextual filter for uid.

Click on apply button. And the filter value as "User Id from logged in user".

Click on Apply button.
In the field, add the name of the user as the field to display. If you want to show more things just add more fields to it.

Save the view and place the block in the header region.


Getting "On Behalf Of" in ubercart email confirmation I am using ubercart in my site.  After making the payment we are getting two emails.  One is for the user and another for admin.  In the amin email I am getting "On Behalf of" and id of the developer who developed this app.  How to change it.

Any help is greatly appreciated.

Try to look in modules folder, in

site root folder /sites/all/modules/ubercart/uc_order/templates/uc-order--admin.tpl.php


How to shorten file urls So for a file the standard url is example.com/sites/default/files/the_file.pdf how can I get rid of the leading /sites/default ?

If you want to get rid of the /sites/default/files/ part and change it to something shorter then just go to the admin menu and follow Configuration > Media > File System

( Or just follow the url : /admin/config/media/file-system )

There set your Public file system path and Private file system path to what ever you want.

---- EDIT ----
Actually the above is valid for Drupal 7.
For Drupal 8 you will have to change the value of $settings['file_public_path'] in the settings.php file, as mentioned by 4k4.
In D8 the Configuration > Media > File System page displays these two parameters but no longer allows editing them.
----END EDIT----

So you could change your sites/default/files to something like resources for example.

And then your files will have   urls like this : example.com/resources/the_file.pdf
instead of what you had : example.com/sites/default/files/the_file.pdf

Also make sure that :
  - your resources directory exists, and
  - is located at your web document root directory, and
  - is writable by your apache user (or whatever webserver you use).

Of course, this will be fine for a fresh setup, but if you already have a lot of contributed stuff then changing these settings may impact on your existing node contents.


Debugging Ajax Callback Goal: Print/dump $formState values to debug
I am altering a form and the functionality works:
$form['elements']['location']['deparment']['#ajax'] = [
  'callback' => 'myAjaxCallback',
  'event' => 'change',
  'progress' => [
    'type' => 'throbber',
    'message' => t('Verifying entry...'),
  ]
];

but what I want is to be able to print out $formState in myAjaxCallback
function myAjaxCallback(array &$form, FormStateInterface $formState){
 $response = new AjaxResponse();
 print_r($formState); //I've tried, with memory_limit=-1 . it just hangs
 dump($formState); //gives me File upload exceeds. This comes from issue with using dump in ajax
                     https://drupal.stackexchange.com/questions/250078/ajax-submission-leads-to-an-unrecoverable-error-occurred-the-uploaded-file-l

 return $response
}

I have also read https://www.drupal.org/docs/drupal-apis/javascript-api/ajax-forms and tried their Debugging AJAX Callback Functions, which has:
$response = new AjaxResponse();
$debugOut = @Kint::dump($formState); //but this uses dump too, which gives me ajax errors

so dd($formState->getValues()); kind of works. This is what it shows me. So, as you can see, I can now see the variables. It's not the best, but readable.

whereas if I go to [website]/webform?ajax_form=1 , it's not even readable.

I am running out of ideas to be able to debug the variable $formState .

@sonfd Xdebug helps print out the values beautifully. No more print_r() or kint() errors.


Change the way results are shown when using the Quiz module I have installed the Quiz module. Using the quiz module you can see the results of all the persons who have taken the quiz under node/*/results. Right now it shows shows the username of person in the table.

In the database I have a table that is called "profile_value" and there are some columns in it, "fid", "uid", "value".

Now I want to show the "value" of this where "fid" is equal to "1" and the user id is equal to "uid" instead of user-name in the result of the quizes.

I think I should be able to do this by changing  the file theme/quiz-results-browser-body.tpl.php.

Am I right?  How should I change it?

Generally speaking when you need to alter the output of a module, you need to override the theme function which is responsible for formatting the data you'd like to alter.

You can do this either by overriding the theme function within template.php within your theme (can get messy quite quickly with a lot of overrides), or by overriding the theme function within a custom module (I would rather recommend doing it this way).

There's plenty of reading material on the subject out there to get you started. Just remember never to hack away at the core or contrib module's theme functions!! :)

Good luck!


Taxonomy term individual occupant can anyone tell me if there is a way to set the terms under a taxonomy to have only one node?

I am building a system which is based on taxonomies but each term should contain only one one. If any user tries to save a node under an occupied term, I need it to be disallowed.

Can anyone help with some insight?

you could use a hook_form_alter when a node is saved and check if the selected term has already been used. Then just show an error message.


How to make a lock forget? I understand how locks work, thanks to this post.  Very straightforward:

function mymodule_long_operation() {
  if (lock_acquire('mymodule_long_operation')) {
    // Do the long operation here.
    // ...
    lock_release('mymodule_long_operation');
  }
}

My problem is that my function can get "stuck" if lock_release is never hit. So how can I get my function to work again if something goes wrong here:

function mymodule_long_operation() {
  if (lock_acquire('mymodule_long_operation')) {
    // SOMETHING GOES WRONG HERE!
    lock_release('mymodule_long_operation');
  }
}

Yes, I can put the whole function around a try/catch and release the lock in the catch. But as a developer, I often add "die()" in my code when working. So I can easily trigger this function into an unexecutable state.

Is there some way to make the lock expire after a while? Or to make the lock expire as part of some gauranteed garbage collection function?

Any ideas would be highly appreciated! Thanks!

** UPDATE **

Nevermind me adding die() in my code. What if the function times out? Then it wont reach the release. I'm sure there are more cases to validate this as a problem.

Is there some way to make the lock expire after a while?

lock_acquire takes a second parameter, defining the lifetime of the lock:

https://api.drupal.org/api/drupal/includes%21lock.inc/function/lock_acquire/7.x

The Drupal 8 version would be:

lock->acquire($name, $timeout);

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Lock%21DatabaseLockBackend.php/function/DatabaseLockBackend%3A%3Aacquire/8.2.x


Views: Use default value from URL for contextual filter, THEN show all if default value empty? Short version, general question: You want to pipe in a 'Default value', specifying a URL argument, to a contextual filter in Views 3. You also want all results (the full unfiltered view) to be displayed if this argument in the URL is empty. However, "Default value" and "Display all rows if empty" settings in Views contextual filters are mutually exclusive, and the default if nothing is passed to the filter is to show nothing.

How can you achieve this?

Full version with case specifics: I'm using a Context View with a contextual filter on a Search API index to search based on search terms in a URL: path like "/search/my%20search%20terms, loaded into a Page Manager panels page as a page context so that bits of the view can be dispersed across the page regions. Pretty standard use of Search API Views.

Since you can't specify what arguments or contexts to pass to a context view in Page Manager / Panels when loaded as contexts in the Contexts form (unlike block views etc, loaded as content, where you can explicitly pass in arguments or contexts), I need to tell it which URL argument it will find the search terms in using the 'Provide default' options under Contextual Filters in the Views settings for the view.

This works, but has an unintended side effect - if someone goes to the search page without any terms (navigates to /search or submits an empty search box), they get nothing. I'd like this path to show the full unfiltered view (it's full of search facets and such so just navigating to it without search terms works like a drill-down browse/advanced search page).

If this was a block or loaded as content in panels/page manager, I could set "If no filter value is provided" to show all rows and use panels/page manager to pass in the current URL argument. But, in Views UI, default values and 'Show all' are mutually exclusive.

So, how to use a default value for a contextual filter, then show all if that default value isn't present or is empty?

Even faster:
PHP is not even needed to just display all values...

Under "When the filter value IS available or a default is provided
Tick "Specify validation criteria" Choose 'Basic validation'
Under "Action to take if filter value does not validate", choose "Display all values"


Domain Access - restrict content for only authenticated users (and keep domain specific settings) I have a site using domain with multiple subdomains.

I want to display some of the particular domains. I can do this with the "Publish to *" field in the domain access options. How do I also restrict access to some content types so that only authenticated users can access these content types and also work with domain access?

I had the module content_access installed to prevent ANONYMOUS USERS from viewing specific content types but this was causing problems with domain as it would write to the node_access table realm=all & view=1 for all content types. This meant that all domains could get access to the content even though the check boxes were set to one specific domain. I think the node_access permission logic is connected with OR.

Any guidance would be appreciated!

Actually I found the issue was with the content_access module. It was overriding the settings for the domain access.

Once this was turned of domain was able to operate as designed with just the 'publish to ...' settings.


Delay in logging Drupal user through Services I have two Drupal7 sites. I am using a service that allows a registered user to login using session authentication.

On the site that performs the call to my remote service I measured the time when I enter the login function and after I got my session id response. It is 6 seconds apart.

When I use the browser to login it works as normal, no delays.
Both Drupal7 instances are running on localhost.

I need some pointers as to where to look in order to reduce this latency.

watchdog("LOG", "Login function hit at " . date(DATE_RFC2822));
$resource = 'access/';

$this->options = array(
  'headers' => array(
    'Accept' => 'application/json',
    'Content-Type' => 'application/json',
  ),
  'method' => 'POST',
  'data' => json_encode(array(
    'username' => $this->username,
    'password' => $this->password,
  )),
);

$response = drupal_http_request($this->base_url . $resource . 'user/login', $this->options);
$data = json_decode($response->data);

// Check response code
if ($response->code == 200 && $data != null) {
  $this->options['headers']['Cookie'] = $data->session_name . '=' . $data->sessid;
  watchdog("LOG", "Connected to remote at " . date(DATE_RFC2822));
}

I wrote a basic php login function to run it from outside a Drupal install and the time to login is 5 seconds. Measured the web login and it's instant. I also switched from Services Resource API 1.0 to 1.1 with no improvements.

This looks unrelated to drupal itself but it's more likely to be a glitch / misconfiguration in the web server/LAMPP settings or a DNS lookup issue.

Can you please let us know more about your LAMPP stack and OS?

Also consider trying the following:

Setting the ServerName property in httpd.conf ( ServerName
  127.0.0.1:80 )
If the above doesn't work, in your httpd.conf be sure to set the setting HostnameLookups Off
Enable slow query log in MySQL.
Have a look at this post https://serverfault.com/questions/66347/why-is-the-response-on-localhost-so-slow


Update the author_uid for an entity registration I'm looking to update the author_uid for an Entity Registration in Drupal 7 programatically. I want to replace all anonymous users with the UID of 0 with another UID lets say 2 upon saving the registration. I have tried three different solutions thus far to no avail.

Solution 1) Update the author_uid in the $form_state prior to saving the registration form.

<?php
function registration_form_alterations_form_alter(&$form, &$form_state, $form_id) {

    if ($form_id == "registration_form") {
        dpm($form);
        dpm($form_state);
        $form['#submit'][] = 'registration_form_alterations_custom_submit';

    }
}

function registration_form_alterations_custom_submit($form, &$form_state) {
    //  submit handler code
    dpm($form_state);
}

This didn't work because author_uid isn't available to be altered in form_state to the best of my knowledge.

Solution 2) Update via hook_entity_presave. I'm not sure this will work because I can't seem to isolate the actual registration entity to update the author_id in hook_entity_presave.

Solution 3) Use rules... Which doens't allow you to update the author_uid. A rules message screen comes back with a message about the value not being writable/editable.

Does anyone have any additional thoughts on this. Sorry I know its a bit of a weird request, but we have a user that wants anonymous registrations reassigned to them so that they can manage additional details associated with the registrations.

(a) hook_entity_presave() should work, giving you access to the entity, before it is persisted, e.g.:

/**
 * Implements hook_entity_presave().
 */
function registration_alterations_entity_presave($entity, $type) {
  if ($type === 'registration' && $entity->author_uid === 0)) {
    $entity->author_uid = variable_get('registration_alterations_anonymous_registrations_reassign_uid');
  }
}

(b) Alternatively, you could use hook_field_attach_submit(), which is also triggered inside registration_form_submit() and would give you access to the submitted form in case you needed it. This would look similar to (a):

/**
 * Implements hook_field_attach_submit().
 */
function registration_alterations_field_attach_submit($entity_type, $entity, $form, &$form_state) {
  if ($entity_type === 'registration' && $entity->author_uid === 0)) {
    $entity->author_uid = variable_get('registration_alterations_anonymous_registrations_reassign_uid');
  }
}

Good luck!


Should I edit a closed issue with the issue summary template? Once you go to create a new issue in drupal.org you can see a message that says:

  Learn how to report an issue. Use the issue summary template to
  summarize the issue in the Description field below. Others can also
  change the summary. Editing the summary does not subscribe you to the
  issue or notify subscribers, so add a comment describing your changes
  after any significant edit.

But there are some closed issues like Incorrect call to urldecode() in the www.drupal.org site that don't follow the template format.

Should I edit a closed issue with the issue summary template?

Yes. It's completely appropriate to edit an issue to clarify the findings, solutions, workarounds etc. and make it easier for people who may look to that issue for reference.


Can I pass file name as a parameter to menus page arguments? I have a hyperlink, in that I am passing the dynamic foldernames and filenames as url like below.

 $data .= '
' ."--". $filenames .'
';

When I click on this, it will go to the particular menu, in the menu I am calling a function to do delete functionality. Below is the menu implemetation

 $items = array();
    $items['/delete/%/%'] = array(
    'title' => "Delete Files",
    'page callback' => 'delete_public_files',
    'page arguments' => array($arg1, $arg2),
    'access arguments' => array('administer custom settings'),
   'type' => MENU_CALLBACK,
  );

I am getting confused while using the arguments here. Can anybody help me that how I have to hit this sitename/custom/delete/foldnames/filenames url. On the samy way how can  call delete_public_files function with $foldnames and  $filenames as arguments.

Example

function mymodule_menu() {
  $items = array();
  $items['custom/delete/%/%'] = array(
    'title' => "Delete Files"
    'page callback' => 'delete_public_files',
    'page arguments' => array(2, 3),
    'access arguments' => array('administer custom settings'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

Please use integer in the array of page arguments to specify the value in url. The url is split in this format: 0/1/2/3


How to use views filter on an entity property I used hook_entity_property_info_alter to add two properties to an existing entity [crm_core_contact].  I find that I can see these two new properties in the "Fields" section of views, and that my views will display the values of those properties, but I cannot see these new properties in either the Sort or the Filter section of Views?  Any ideas on documentation that might tell me what is going on?

Here is the code for one of the properties:

$properties = &$info['crm_core_contact']['properties'];
$properties['notes'] = array(
                'setter callback' => 'entity_property_verbatim_set',
                'setter_permission' => 'Administer wcgopindividualinfo content',
                'label' => 'NotesText',
                'type' => 'text',
                'schema field' => 'notes',
                'getter callback' => 'entity_property_verbatim_get',
                'entity views field' => TRUE,
                'getter_permission' => 'Administer wcgopindividualinfo content',
                );

Although the Trellon documentation does not say this, I'm wondering if I need to add a hook_views_data_alter function to specify the filter and sort handlers for the properties that I added.

I have now done some experimentation and find that yes, what I needed to do was use hook_views_data_alter to tell views how to handle the properties I had added above.  Here is the code inside my hook_views_data_alter function:

$data['crm_core_contact']['notes'] = array(
            'title' => t('Notes'),
            'help' => t('The notes for the contact'),
         // Information for displaying the notes field
                'field' => array(
            'handler' => 'views_handler_field',
            'click sortable' => TRUE,
  ),

    // Information for accepting a note as a filter
        'filter' => array(
        'handler' => 'views_handler_filter_string',
  ),
    // Information for sorting on a note.
        'sort' => array(
        'handler' => 'views_handler_sort',
  ),
);


How to connect 2 forms in drupal 7? I have 2 forms in drupal 7 and I want to connect these 2 form.. Means when I will fill first form with some values then this form should be submit with ajax.After submit new form should be show.

You might need MultiStep form using ajax enabled. Just implement #ajax on the buttons of form as in the given link.

    $form['buttons'] = array(
      '#type' => 'container',
    );
    if($form_state['step'] !== 1) {
      $form['buttons']['back'] = array(
        '#type' => 'submit',
        '#value' => t('Back'),
        '#limit_validation_errors' => array(),
        '#submit' => array('ajax_form_multistep_form_back_submit'),
        '#ajax' => array(
          // We pass in the wrapper we created at the start of the form
          'wrapper' => 'ajax_form_multistep_form',
          // We pass a callback function we will use later to render the form for the user
          'callback' => 'ajax_form_multistep_form_ajax_callback',
        ),
      );
    }
    if($form_state['step'] !== 3) {
      $form['buttons']['forward'] = array(
        '#type' => 'submit',
        '#value' => t('Next'),
        '#ajax' => array(
          'wrapper' => 'ajax_form_multistep_form',
          'callback' => 'ajax_form_multistep_form_ajax_callback',
        ),
      );
    }
    else {
      $form['buttons']['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
        '#ajax' => array(
          'wrapper' => 'ajax_form_multistep_form',
          'callback' => 'ajax_form_multistep_form_ajax_callback',
        ),
      );
    }


how to show breadcrumbs only on subpage? How can I show breadcrumbs only when the depth level is more than 2.

i.e.:

home > page > subpage => show breadcrumb
home > page => hide breadcrumb

Additionally I would like to hide 'home' also (and always), but this has less priority in my question.

Thanks for your explanation!

Regards,
Hans

If you are using Drupal 7, then you can use:

Path Breadcrumbs
Context path breadcrumb

  Path breadcrumbs module helps you to create breadcrumbs for any page with any selection rules and load any entity from the URL!

  This is a plugin module for the context module. It takes the request URI part of the URL of the current page (for example /our-company/our-team/steve) and uses this path to build the breadcrumbs.


Profile 2 display field on my account page Use this module - Profile2 Registration Path and Profile2 -  when registering, so that would be made at check-in person was filling certain fields, in this regard, I have a question - how do I display the fields that person fills during registration, on the profile page?

you can enable profile2 pages, that comes with the core of profile 2

That module will add different pages per profile types in the user account. so your users can select their profile and check for the fields they filled during registration


Displaying the submitted values in a table I created a custom form and after the form is submitted I need to display the submitted data in a table? This seems like a very simple problem. I am able to use dpm() and drupal_set_message() to display data submitted from the form in mymodule_form_submit($form, &$form_state); however, I can't output it to a table.

I have 3 field values

$form_state['redirect'] = 'some/path/' . $form_state['values']['my_value'];

Using this I can send just 1 value. But how can I send an array with this? Query string may appear to be very long.

You don't need to redirect the form like that: a form submission handler can pass data to the form builder using $form_state; in this way, you don't have any limit for what you can pass back to the form builder.

It's enough the form submission handler uses the following line.

$form_state['rebuild'] = TRUE;

Then it saves in $form_state the values to pass back to the form build, being careful not to use the same index used for other purposes, from Drupal, or your module. Usually, $form_state['storage'] is used for that purpose, as explained in $form_state keys.

  $form_state['storage']
      When building complex forms that require multiple steps for completion (for example, a three-page survey), it's necessary to preserve the data from all steps so that they can be processed together at the end. (And, on occasion, to vary the contents of one step based on the input from the previous one). Any data placed in the 'storage' bin of the $form_state collection will automatically be cached and re-loaded when the form is next submitted, allowing your code to accumulate data from step to step and process it in the final stage without any additional code. Developers who want more control can use their own caching mechanisms to store temporary form data (the user session and hidden form fields are two popular alternatives), but the 'storage' bin is automatically handled for you by the form API.

That is for Drupal 6; for Drupal 7, see drupal_build_form().

  storage: $form_state['storage'] is not a special key, and no specific support is provided for it in the Form API. By tradition it was the location where application-specific data was stored for communication between the submit, validation, and form builder functions, especially in a multi-step-style form. Form implementations may use any key(s) within $form_state (other than the keys listed here and other reserved ones used by Form API internals) for this kind of storage. The recommended way to ensure that the chosen key doesn't conflict with ones used by the Form API or other modules is to use the module name as the key name or a prefix for the key name. For example, the Node module uses $form_state['node'] in node editing forms to store information about the node being edited, and this information stays available across successive clicks of the "Preview" button as well as when the "Save" button is finally clicked.

If you really need to print the data in another page, then save the data in $_SESSION, instead of passing that as GET data.


how to modify print--mail--node--node-type.tpl.php drupal 7x I installed the module https://drupal.org/project/print , drupal 7x , but now we need to get control over each variable on the display node. I mean print out some variables content and other NO, also print it in two columns.
well make a table is not a problem. the PROBLEM is how to get the variable content in order to print out?

I have this code, works, but print all the content by default, in an UGLY way.

I will appreciate ...Any ideas or suggestions.... please sent to me a basic example...

I think that you can do this by changing display of content type. Just go to the Manage display page of the content type you print; at the bottom, expand Custom display settings and select Print. After saving, you'll see the Print tab (next to tabs like Default and Teaser).

Now you can change the page display settings. You can also change the page style using CSS.


How can I set a variable in the body of a node? In Drupal 7 I've created a node of type basic page.
Then in Body field I've inserted some markup mixed with php code.
Then this was saved in PHP text format.
In the above mentioned markup I have variable I'd like to output to html.
I tried some preprocess functions but that didn't give me any result.
How can I set the variable?

take a look at What is best method for token replacement within node content?

If you are feeling lack of available tokens, you can extend it with tokens hooks.


PHP rule for views exposed filter I'm writing a visibility rule for an element on a Panel page that also has a view with exposed filter. The goal is to show this element only when the filter isn't set. Is there a way to check weather the view on the current page was filtered with exposed filter or not?

There might be other more convenient solutions but this is a quick one, in some cases it wont work or suit at all (it will work on pages with clean urls), but you can perform current path validation by this code:

$destination = drupal_get_destination();
$destination = $destination['destination'];

// validate if path contains "?" from exposed filter

if (preg_match("/\?/", $destination)) {
return FALSE;
}
else {
return TRUE;
}


Render Array Customise Theming I have what is probably a common question ... How do render arrays get parsed into the the twig template - If we have a controller class which outputs a render array, such as:

$output['element1']=array ("#type"=>"markup","#markup"=>"Hello World!");
$output['element2']=array ("#type"=>"markup","#markup"=>"Today is a nice day!");

Now, lets say that we're using the bootstrap framework, hence using row and columns for layout, if we want the array elements to be output in the following manner:

    Hello World!

    Today is a nice day!

How can this be done?  It is clear that Drupal will initially use the page.html.twig template, which will call the region.html.twig template, which in turn will call the block.html.twig template in order to display the render array.  But, the block.html.twig will output the render array as:

 Hello World! Today is a nice day!

Namely,it will not output the div tags - mostly because the block.html.twig doesn't know about them.  And looking at the block.html.twig it appears that the output is only available as 'content':

 {{ content}}

And there is no way of templating the content in the following way:

        {{ content['element1'] }}

        {{ content['element2'] }}

Secondary related query:

What would also be useful, is being able to ascertain which class called the page.html.twig so that one could use the {% if calling_page="page name" %} in the block.html.twig template

Hopefully, you get what I am outining here.  Thanks in advance and please operate upon the premise I'm totally new to Drupal when outlining solutions.

I can answer the first part of your question...

Drupal uses render arrays for the different outputs. Since you only specify two single dimension arrays with #markup they are rendered as 2 strings.

There are multiple ways to achieve what you want, I will highlight 2;

Use #prefix and #suffix:

$output['element1']=array (
  "#type"=>"markup",
  "#markup"=>"Hello World!"
  "#prefix"=>'

',
  "#suffix"=>'

',
);

Use nested elements:

$output['element1']=array (
  'row' => array(
    '#prefix' => '
',
    '#suffix' => '
',
    'cols' => array( // This has no #, so is the next level of elements
      '#markup' => t('Hello World!'),
      '#prefix' => '
',
      '#suffix' => '
',
    ),
  ),
);

See this related issue: How to nest elements in a render array.

However, there might be cases where it is not possible to alter the output of modules. Instead you want to do this in the theme. Your suggestion was not that bad. It is just that in twig arrays are noted with a dot symbol. {{ content['element1'] }} should be {{ content.element1 }}

        {{ content.element1 }}

        {{ content.element2 }}


Scheduler Module unpublish content Trying to schedule a content type to be unpublished on a specific date. Using the scheduler module everything is set up seemingly correct. When I run Cron the update fails,

Updater Content - Publishing status complete. Results: No updates were performed. 1 updates were invalid
When i go to Scheduled Updates Overview and run scheduled updates manually it works just fine.

Why is Cron Failing?

I have created a drush command to run only the scheduled_updates_cron() function from the command line and also from crontab. I didn't know why all of my updates were invalid till I saw your post, so I made some research and I managed to make my drush command work like the "Run Updates" button from Scheduled Updates Overview page, by specifying the user who should run the update.

Example (Wrong results): drush command-name

Example (Good results): drush --user=1 command-name

If you are using the drush croncommand, you should modified it to drush --user=1 cron

I hope this helps !


I lost my gmap macro builder I'm embarrassed but I can't find the gmap macro builder anymore. I looked under

config->content-authoring->location and all its tabs
as well as configuration->web services-> GMap and all its tabs
and configuration->web services->GMap location and everything under that.

I also made sure that GMAp macro builder module is enabled

The following modules are also enabled:

Gmap 7.x-1.x dev
Gmap location 7.x-1.x dev
Gmap macro builder 7.x-1.x dev
Gmap taxonomy markers 7.x-1.x dev
Location 7.x - 4x dev
Location add another  7.x - 4x dev
Location Search 7.x -4.x ev
Node locations

A peek in the code reveals that the macro builder registers the path map/macro.

function gmap_macro_builder_menu() {
  $items['map/macro'] = array(
    'type' => MENU_NORMAL_ITEM,
    'title' => 'Build a GMap macro',
    'access arguments' => array('create gmap macro'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('gmap_macro_builder_form'),
  );
  return $items;
}

It is understandably hard to find when it's not under admin; though, perhaps, gmap registers map for its own set of admin pages.


Perform bulk operations on a custom database table I have a custom database table. I implemented hook_views_data() to make it available with views.
/**
 * Implements hook_views_data().
 */
function uploader_views_data() {
  $data = array(
  'texts' => array(
        'table' => array(),
      ),
  );

  $data['texts']['table'] = array(
    'group' => t('Uploaded Texts'),
    'handler' => 'views_join',
  );

  $data['texts']['table']['base'] = array(
    'field' => 'txt_id',
    'title' => t('Texts'),
    'help' => t("Text ცხრილში ინახება ინფორმაცია ტექსტების შესახებ. მაგ: ავტორი, სათაური და ა.შ"),
    'weight' => -10,
  );

  $data['texts']['txt_id'] = array(
    'title' => t('txt id'),
    'help' => t('ცხრილის უნიკალური ID-ი.'), // The help that appears on the UI,
    // Information for displaying the nid
    'field' => array(
      'handler' => 'views_handler_field_node',
      'click sortable' => TRUE,
    ),
    // Information for accepting a nid as an argument
    'argument' => array(
      'handler' => 'views_handler_argument_node_nid',
      'name field' => 'title', // the field to display in the summary.
      'numeric' => TRUE,
      'validate type' => 'nid',
    ),
    // Information for accepting a nid as a filter
    'filter' => array(
      'handler' => 'views_handler_filter_numeric',
    ),
    // Information for sorting on a nid.
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
  );

  $data['texts']['teqstis_saxelcodeba'] = array(
    'title' => t('ტექსტის სახელწოდება'),
    'help' => t('ნაბეჭდი ტექსტის სახელწოდება.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE, // This is use by the table display plugin.
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );

  $data['texts']['xelnaceris_saxelcodeba'] = array(
    'title' => t('ხელნაწერის სახელწოდება'),
    'help' => t('ხელნაწერის სახელწოდება.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE, // This is use by the table display plugin.
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );

  $data['texts']['type'] = array(
    'title' => t('Type'),
    'help' => t('ტექსტის ტიპი.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE, // This is use by the table display plugin.
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );

  return $data;
}

I want to create a custom bulk operation on this table.
function uploader_action_info() {
  return array(
    'uploader_myaction' => array(
      'type' => 'entity',
      'label' => t('Do my action'),
      'configurable' => FALSE,
      'pass rows' => TRUE, //this will ensure that the entire views row is passed as part of the context in your action callback.
    ),
  );
}

The action callback is the following one.
function uploader_myaction($cmt, $context = array()) {
   drupal_set_message(t('uploader_myaction was called'));
}

When I try to add a field in the view fields, there is no Bulk operations: Content option.

I've had a similar problem.  It's not ideal behaviour, but when I created the field, save it (selecting no action, or an action at random), then edit it (unselecting the random action, if I did that), then my custom action shows up.


How to theme the views exposed form? I've created a view with a number of exposed filters, but it is pretty ugly looking.

I'd like to improve the theming, including wrapping the whole thing in a fieldset as well as grouping some of the other elements (like pairing the published and updated inputs), but not sure how to go about this.

I tried to var_dump the form, but it seems to go on forever and my browser locks up, so I can't easily learn anything about the form that way.

I also tried putting the form as a fieldset child in another form, but getting all the form ID information and so on proved problematic (although, I did get the fieldset styling).

Anyone got any pointers?

Update:

I copied over the template from the module to my site's theme directory, and made a start.

<fieldset>
    <legend>Filters</legend>

            <?php foreach($widgets as $id => $widget): ?>

                    <?php if (!empty($widget->label)): ?>
                        <label for="<?php print $widget->id; ?>">
                            <?php print $widget->label; ?>

                    <?php endif; ?>
                    <?php if (!empty($widget->operator)): ?>

                            <?php print $widget->operator; ?>

                    <?php endif; ?>

                        <?php print $widget->widget; ?>

            <?php endforeach; ?>

                <?php print $button ?>

</fieldset>

I can't seem to figure out how to pair up the date fields - I need to somehow modify the widget properties so I can wrap them in HTML (using hook_form_alter doesn't work because the #prefix and #suffix are added to $widget->widget so they break the output)

Theming Views' exposed form is hard because it doesn't behave like most forms and use its own label mechanism. So, you can't simply use a form_alter hook to add #prefix and #suffix to elements. But using THEME_preprocess_views_exposed_form, you can craft your own suffix/prefix mechanism:

function THEME_preprocess_views_exposed_form(&$variables) {
  if ($variables['form']['#id'] == 'views-exposed-form-VIEWNAME-DISPLAYID') {
    foreach ($variables['widgets'] as $id => &$widget) {
      switch ($id) {
        case 'first_date_id':
          $widget->prefix = '
';
          break;
        case 'last_date_id':
          $widget->suffix = '
';
          break;
      }
    }
  }
}

and in the template file

<fieldset>
    <legend>Filters</legend>

            <?php foreach($widgets as $id => $widget): ?>
                <?php if (!empty($widget->prefix)) print $widget->prefix; ?>

                    <?php if (!empty($widget->label)): ?>
                        <label for="<?php print $widget->id; ?>">
                            <?php print $widget->label; ?>

                    <?php endif; ?>
                    <?php if (!empty($widget->operator)): ?>

                            <?php print $widget->operator; ?>

                    <?php endif; ?>

                        <?php print $widget->widget; ?>

                <?php if (!empty($widget->suffix)) print $widget->suffix; ?>
            <?php endforeach; ?>

                <?php print $button ?>

</fieldset>


How to call default node validation functions I have a custom node-creation form for which I have my own validation function. How can I make sure that after my validation function the form goes through the same validation that it would have done on the original node-creation form?
Some thing like node_validate looks like the kind of thing I need, but it works on $node objects rather than forms.
The order of operations I perceive to be the best is

On submit run custom validation
If custom validation passes run the normal node validation
If node validation succeeds insert values in the database

Is that a good and Drupal way?

If your form has a structure similar to the one used for the node edit form, then you can use node_validate(), which is called from the form validation handler for the node edit form.

function node_form_validate($form, &$form_state) {
  node_validate($form_state['values'], $form);
}

node_validate() converts the first argument in an object using the following code.

  // Convert the node to an object, if necessary.
  $node = (object) $node;
  $type = node_get_types('type', $node);

Your form validation handler's code should be similar to the following one.

function mymodule_form_validate($form, &$form_state) {
  // Run your validation code.
  node_validate($form_state['values'], $form);
}

As general rule, the validation code should go in the form validation handler. If the form validation handler set any error, the form submission handler is not called, and the user is returned to the form to correct what is wrong in the data that has been submitted.


The Batch API won't continue running if the browser is closed correct? Can a batch be run with Drush? Can the batch API continue to run once the browser closes? If not then can I run a batch with Drush? I have an insane amount of data to migrate and I don't really have time to wait for it to import every item one at a time on my local machine.

Currently I have my batch process setup to import each item (groups, users, blogs, files, etc) one per op call. But I am going to change that to do 50 to 100 per call to improve the speed. But I just ran it last night on just my groups and it took almost an hour to run on almost 800 groups.

This is part of a data migration from multiple websites to one unified site. Thoughts? Suggestions? Can Drush help me out?

EDIT: I have rolled my own export/import scripts for this because of the nature of the migration (multiple Drupal 4.7 sites that are highly customized and with potentially hacked cores to Drupal 6). I already have the exported data file created and ready to go. I am just testing the import portion of this madness.

It seems possible, have you tried: Processing batch jobs with drush.


How to delete first user (admin) For security reason, I want to delete the first user (which has all rights, event without the admin role) and login only with the drush uli command. How can I do that? From the backoffice it say I can't remove that user

I doubt that's possible, or at least not without messing with a lot of core code.

User 1 is synonymous with the root user in linux. It can be disabled, hardened, made virtually impossible to access, but not removed.

See Securing user #1 for more information.


How to prohibit some words and letters to use as a Drupal password? I need to prohibit a user from using a few words as a password. E.g I don't want to use these words as a password. Drupal, 123456, Microsoft. When a user submits the registration form with the above terms in the password field then they get a message about the prohibited password.

This module should work. I have never used it before, but it should definitely have the feature to prohibit certain password strings.
Password Policy Module


ALL input doesn't work I installed Drupal on my VPS, but it seems that all input on website doesn't work from web interface. What I mean by that:

I cannot login by using web interface
I CAN login by using one-time login link generated by Drush, but then strange things happen, I guess consequences of not working input - like Admin Menu disappears after refresh, and editing any content is impossible, after sending change - the edit page simply refresh with old values,
I have Redmine installed on this server and it works ok, so it seems to be Drupal specific.
The problem doesn't exist with "?q=/user/login" - it exists only with rewritten links. I'm pretty sure I have unmodified .htaccess.
The problem exists when I remove from .htaccess everything, with the exception of: ErrorDocument 404 /index.php and RewriteEngine on (which is bare minimum for rewriting to work it seems).
There are absolutely no errors in logs of Drupal, Apache and MySQL.

My Virtual Host: http://pastebin.com/R5hRQMWc

My .htaccess: http://pastebin.com/xM5Kj1yd

System: Ubuntu 14.04, Apache 2.4.7, PHP 5.5.9-1ubuntu4.2 , mysql Ver 14.14 Distrib 5.5.37

Any ideas what is going on and why only Drupal is affected?

Maybe Apache server doesn't include "mod_rewrite".

Try do below code in the console:

sudo a2enmod rewrite
sudo service apache2 reload

I think this help to you!


What does this Apache SOLR error mean? From the log (set as "error"):

SearchApiException while optimizing Solr server local solr server: "0" Status: Request failed: request timed out in SearchApiSolrConnection->checkResponse() (line 541 of /var/www/domainname/sites/all/modules/contrib/search_api_solr/includes/solr_connection.inc).

What does this error message mean?

The error means exactly what it says:

  Request failed: request timed out

The connection between your Drupal server and Solr server timed out.

If the servers are geographically far from one another, you might consider moving them closer together to reduce latency. Your Solr or Drupal server may also need more resources.

Both are things you'll need to incrementally test (preferably in an identical staging environment) until you've worked out where the bottleneck is and how you can overcome it


FileDepot upload file sizes restriction I am using the filedepot module. With this module I am able to upload files. I want to allocate space for "uploading files" to individual registered users basing on user roles.

Is it possible? How do I do it?

I don't believe that is possible with filedepot without patching the module. However it is readily available within the IMCE module if you are able to change modules.  From the project page:

  Basic file operations: upload, delete
  Image(jpg, png, gif) operations: resize, create thumbnails, preview
  Support for private file system
  Configurable limits for user roles: file size per upload, directory
  quota, file extensions, and image dimensions
  Personal or shared folders for users
  Permissions per directory
  Ftp-like directory navigation
  File sorting by name, size, dimensions, date
  Tabbed interface for file operations
  Keyboard shortcuts(up, down, insert(or enter), delete, home, end,
  ctrl+A, R(esize), T(humbnails), U(pload)).
  Built-in support for inline image/file insertion into textareas
  Multiple file selection(using ctrl or shift)
  Ajax file operations
  Themable layout using tpl files

For a better idea of what you are looking at, take a look at a screenshot of filedepot.

Everything you need is already built in to IMCE.


Why are my search results not showing when I input any body text? Why my search result not showing when I input any body text ?

Are search results based on node title only?

I am creating a multilingual site with French and English languages.

Users should be able to search results by entering any text of a node whether its body text, taxonomy, subtitle and so on.

Core search indexes titles and body content but in order to actually be able to search the nodes have to be indexed.

Search indexes nodes on batches and each batch starts on a cron run.  You can run cron manually by going to your /admin/reports/status but ideally you want to setup a cronjob to do this for you automatically.

Search admin page (admin/config/search/pages) reports on what percentage of the nodes have been indexed.

Only after the search admin page says you have 100% of the nodes indexed you can be sure that what you search can be found.


Assigning template file to a view How to display the custom content type fiels in the custom template file. I have integrated custom content types in views.

How to assign custom template files to a view which is filtered to display certain content type only.

Take a look at Drupal 7 Template (Theme Hook) Suggestions

For content types you can try

node--[type|nodeid].tpl.php

base template: node.tpl.php

Theme hook suggestions are made based on these factors, listed from the most specific template to the least. Drupal will use the most specific template it finds:

node--nodeid.tpl.php
node--type.tpl.php
node.tpl.php

To theme a view..

Set up your view; by going to Views -> Add View
Once, your view is completely set up, at the bottom of the view (left column), you will see a link called "Theme Information", click on it.
What you will be presented with is a list of templates (.tpl.php) files that the views uses to theme your data. Basically the file names that are bolded are the files views is using to theme the data.

Check How to create a Custom Template for a View


Removing title from content pane I have used a content pane in a panel to add a description on top of it. It was a success but I can't find a way to remove the pane title in the view. The screenshots are below:

I have also set the content pane title to none

There is no option in the panel for title.

So how can I remove it?

In the view, there is an 'allow settings' link (bottom right of your screen shot). This allows you to select which settings can be changed within panels, including the title.

You can then, in panels, override the title with an empty string.


Add Fields to View page I have a view that is a page and I'd like to be able to add a a field to this page.

My other pages are content type pages and they have the option to assign a top hero banner content type to them. How can I assign a hero banner content type to a view page?

In your view's edit screen do the following:

1.) Under Format, Change Show: Content to Show: Fields

By clicking on Content and then selecting Fields

2.) Under Filter Criteria add Type and then check mark your content type name.


Taxonomy saving order on node Coming from a different CMS, I am diving little by little into the Drupal philosophy and I have already bumped into a problem. (being a beginner sucks :/ )

I have installed the hierarchical select module to facilitate my user to add the taxonomies they want. But the user is not happy with the way that the list is displayed.

What I wanted to do is to find a way for the user to define the display (and thus the saving) order of the taxonomies on each node independently.

I thought of weights but that would have an impact on the taxonomy order and not the node.

I did a few searches on the fora and also googled a bit but I always go around the views related topics and I am not able to find a module that does this.

It might be impossible (I have no clue yet on how the taxonomies are saved and treated in the database) so I explain a bit more the situation as there might be a better solution or an alternative to what I am thinking.

In practice, my user wants to be able to choose out of a list of taxonomies one to be displayed before the others, and ideally to be able to arrange the rest of the terms at will.

eg.

node 1 -> Term3, term 2, term 5

node 2 -> Term1, term 5, term 6

The user suggested that could also "work" with 3 fields that define the order of the chosen terms but I find this solution very short term solution and will cause problems the day that I need to add a 4th or a nth field on the same node.

Any suggestion apart from creating my own module?

Thanks a lot for you input,

Thanks for your input @JPMC. In the end I just used Simple Hierarchical Select and did what I wanted to do.


Ubercart add custom price product? I want to add a Gift Card product to my Cart but assign a value the user typed in (so for example Product ID 3 would be gift card for $1, and I would then make it $25,$50, and so on).

How can I do this? I looked at uc_cart_add_item but it is just NID, and I don't want to make 500 different products for each amount possible.

Any help!?

Have you looked at the Variable Price module?
http://drupal.org/project/uc_varprice

It's ostensibly for donations, but I think it might be customizable for your purpose.


Set Default Value for Image Field contain Multiple Images I've added a multiple image field to the user account that uses the multiupload_imagefield_widget and it works when I edit the account.
On the other hand, I have a custom module with a form that I would like to edit just this field (I have a submit handler to update the user data). I call user_load to display the data and I can see the data is there in the debugger, but no images are displayed on the form.
What do I have to do to make them show up?
Here's my code:
$user_data = user_load($user->uid);
$form['my_imageGallery'] = array(
  '#type'             => 'image',
  '#title'            => t('Image Gallery'),
  '#default_value'    => isset($user_data->field_galeria) ? $user_data->field_galeria : null,
  '#upload_location'  => 'public://user_galleries/',
  '#upload_validators' => array('file_validate_extensions' => array('png jpg gif')),
);

I think you need to use a managed_file form element.
$user_data = user_load($user->uid);
$form['my_imageGallery'] = array(
  '#type'             => 'managed_file',
  '#title'            => t('Image Gallery'),
  '#default_value'    => isset($user_data->field_galeria) ? $user_data->field_galeria : null,
  '#upload_location'  => 'public://user_galleries/',
  '#upload_validators' => array('file_validate_extensions' => array('png jpg gif')),
);


Getting all the Submitted field values after the Webform is just submitted in Drupal 7? I created a webform for which I need all the submitted fields with values on the confirmation page after the user submitted the form. I am using WebForm 7.3.

The user when confirms the information, can make any final change before submitting it (updating the existing one, I guess).

This is what I used and placed it in the template.php but sadly it doesn't work:-

function user_register_webform_submission_insert($node, $submission){
// Load information about form components
$comps = $node->webform['components'];
$fields = array();

//Extract the component info to get form_key=>cid to resolve relation
foreach($comps as $cid => $comp_info){
    $fields[$comp_info['form_key']] = $cid;
}

// Load the submitted data (field values)
$data = $submission->data;

//Prepare a user info
$user = array(
    'mail' => $data[$fields['mail']]['value'][0],
    'name' => $data[$fields['name']]['value'][0],
    'pass' => user_password(8),
    'status' => 1,
    'init' => $data[$fields['mail']]['value'][0],
    'roles' => array(2, 3),
);

$account = user_save(null, $user);
}

If you are able to upgrade Webforms, preview functionality is now part of the 7.x-4.x branch of the Webform Module. There is an involved discussion about it here: Summary/review/preview page before final submission in multistep forms.


Show a required textfield when user select only ups shipping service on checkout form I am using drupal commerce for my client ecommerce site. For shipping methods I am using commerce_shipping, commerce_ups, commerce_usps.

Everything is working but my client wants when a user select any ups shipping service a textbox should be shown and should be required.

What I have done till now :

I have created a pane which contains a textbox using order setting. And that taexbox is showing on checkout form . But when I make this textbox as a required field than it is not possible to submit the form when user select usps or flat rate shipping services.

So how I can show a textfield on checkout form which should be required only when user select any ups shippping service.

Thanks!

You could try to do this via #states property in form API.

More information about that can be found here:
How to make a form required with states?

Personally i only used it to hide/display form elements, but required/non-required should be possible as well.


term reference field with empty select list We need to make the term reference field select list to have no options because the vocabulary have big number of terms which makes the form loads very slow due to getting the term list from DB and render them.

That field is being updated by ajax so we need it start clean with no DB operation to increase performance and page loads fast.

  Implementing: hook_field_attach_form or hook_form_alter

has no effect as we see the form is built.

what we need i to prevent DB reading list.

if($form_id == 'field_ui_field_edit_form'){
      $form['instance']['default_value_widget']['field_brand']['und']['#options'] = array(0 => t('No'));
}

Above code didn't change any thing in node/add form which still list all brands

Is it posible in drupal?

Try with the following code

function yourmodule_form_alter(&$form, &$form_state, $form_id){
 if($form_id == 'your-edit-form-id'){
   $form['your-select-feild']['#options'] = array();
 }
}

Hope this will help you..