How do you clear a field value with entity_metadata_wrapper()? Suppose I have an entity with a field field_foo on it and I want to clear that field's value.

What should I pass to $wrapper->set()?

I have tried NULL and array() and both produce an error message.

The problem is that you must set an empty value that is compatible with the data type of your field. If you do not, you will get an exception raised. Passing NULL or array() when a string is expected will therefore raise an error.

Another thing to keep in mind is that the data you pass will also depend on whether your field is a single value, a multi-value field, or a field with multiple properties.

If your field is a single value (and thus the wrapper for the field is an instance of EntityValueWrapper) then you should assign it an empty value compatible with the data type in question. For instance the two following methods are equivalent:

$wrapper->title = '';
$wrapper->title->set('');

However the following three examples will raise an exception, because the data types are not compatible with the title field:

$wrapper->title->set();
$wrapper->title->set(NULL);
$wrapper->title->set(array());

If your field is a field with multiple properties (for instance a formatted text field, which defined both a value and format property) and thus an instance of EntityStructureWrapper, then array() or NULL will be the correct empty value. So you can do the following:

$wrapper->field_formatted_text = array();
$wrapper->field_formatted_text = NULL;

But in that case, passing an empty string would have raised an error. Note that you could have chosen to make the value property empty instead, in which case a string is the correct data type:

$wrapper->field_formatted_text->value = '';

Finally, if your field is a multi-value field (and thus your wrapper is an instance of EntityListWrapper) then array or NULL are the correct empty values, and the following three lines are equivalent:

$wrapper->field_example_multiple->set();
$wrapper->field_example_multiple = array();
$wrapper->field_example_multiple = NULL;

Note:
Calling the clear method on the wrappers is not equivalent to setting the field to an empty value. When the field is set to an empty value, it then calls EntityMetadataWrapper::updateParent on the field's parent wrapper. This ensures amongst other things that the setter callback defined by hook_entity_property_info is called. Calling clear does not do that.


How to restrict access to content based on roles (multiple levels) and show a public preview? I'm looking for a reliable solution for the following situation:

a membership site with multiple levels of access for users (based on roles, say anonymous, and levels 1 through level 4)
need to restrict node view access by role on a per node basis, but allow anonymous access to the teaser (should be possible to show/restrict other fields as well)
take performance and flexibility into account

There are several modules that solve most of the problem, but not entirely. I'm looking for recommendations on the combination of modules to use, and whether I'd need to extend any of these with custom code or if just combining contrib modules is feasible.

Premium content offers the basic functionality, but it seems to only work for the regular body field. Is it still a good option if you want to publically show or restrict other fields? (e.g. restrict the body as well as another text or file field).
Taxonomy Access Control: I like how you can easily change the access level per node by just changing the assigned taxonomy term. But how would I allow anonymous access to the teaser or other fields?
Field permissions offers all the granularity on the field level I would need, but I need the option to restrict one field (e.g. node body) to different roles on a per-node basis.
Or maybe do something with Panels (cf. this answer)?

A solution that plays nice with other modules (e.g. Views) is preferred (I think TAC would qualify here - e.g. filter by taxonomy, maybe use VBO for changing terms...).

How would you do this?

Update: I've looked into using Panels; whle I like the flexibility that a Panels-based approach offers, I doubt it's feasible for my use case.

Using Panels, the selection rule would have to be based on a combination of current user's role and node being viewed's term id, so for each selection rule you'd need 2 criteria and the 'All criteria must pass' setting. So each access level (except 'Anonymous') needs two variants: one for the combination of tid + roles that get to view the teaser, and one for tid + roles that get the full node.

Since there are 5 roles to take into account (anonymous + roles A, B, C, D) I'd need 9 page variants. This doesn't feel quite elegant, or would 9 variants be acceptable? (thinking about performance, maintainability etc.).

Another problem is that the Term ID criterium in the selection rule is per Content type, so if I wanted to use this for multiple content types I'd need even more variants. Since I need the 'All criteria must pass' setting for the combination of role and term id, I cannot add term id of two content types in one selection rule.

Another option would be to use PHP for evaluating the selection rule, but that feels like it may be defeating the purpose of using Panels. And code in DB is not a good idea, etc.

So unless I am overlooking a simpler way with Panels, it doesn't seem such a good idea (except maybe with custom PHP for selection rules...)?

I would use Panels.

Basically, for all of your Panel Pages, you would have two variants.

Each variant would have a Selection Rule based on the user role, one for the role and one for not the role.

Then on each, build up the content the way you need.  Personally, I would make a custom node view for the restricted view, so you can use the Node Being Viewed content piece and just configure it to use the view mode you made.

The reason I recommend Panels is that it makes it easier to change things in the future without needing to get special-function modules to cooperate with each other.


Entity reference link module I am using entity reference field in a content type with select list widget allows you to add the title of a node in the content type, however the title dose not work as a link to the node.
I would like to now how can i make the title work as a link to the node?

dose Entity Reference link module fits this purpose??
if yes how it works?
if no is there any way to do this??

Go to  Content types » [your_content_type] » Manage display
and select FORMAT as Link label to the referenced entity for your referenced field.


Show all nodes with the same term, the current user is assigned to That sounds quite simple but I can't find a hint how to do this:

I have invoices with a term reference to a "Department" vocabulary [field_invoice_department]. The user has a term reference to the same vocabulary [field_user_department].

So how should I configure my contextual filters to show all invoices assigned to the same department, the current user is assigned to?

There are a lot of answers you can search for "sibling taxonomy" or some other wording.

Here's one answer you can follow: Filter taxonomy term attached to user field

The only difference is you always want your views to show the current user's matches, and not create, for example, profile pages for everyone separately as it is in that answer.

To make your Views show only the current user's matches in the User ID Contextual filter you have to choose User ID from logged in user instead of User ID from route context.


Can Apache Solr Search allow a user to search 'within' current results? I'm looking for a way to allow a user to search 'within' current Solr search results (not search api solr results).

Is there existing functionality that provides this?

If I need to implement a module to do so, so be it; recommendations for what hooks to implement in that case would also be helpful.

Edit:

Re. amateurbarista's comment.  I'm wondering if there is a way to make a second query against the results of a first. I don't think Facets allow me to do this, is that so?

For example suppose my first search query returns 10 nodes.  I'm asking what it would take to allow a second query to search only within those 10 nodes.

This is from my experience using Database Search not Solr but it might work.

I'm also not sure it's exactly what you're looking for but it might be a starting point.

Clone your view, but keep the URL the same.

This allows you to run two exposed forms both of which re-direct to the same view. So I have one on my homepage and then one on my search results page. When you search from the home page the values are automatically populated into the second exposed form when you land on the results page.

Because the exposed forms are different this means you can show more fields on the exposed form on the search results page and because it remembers the first search, technically, you're searching within the original search.


State field in Civicrm profile display as digit I'm using D7, with CiviCRM 4.4.6. I had use civicrm to create a profile, for user to enter and edit their billing address in their account.

The country, displaying well as "Malaysia", but the state field is displaying as digit, "07".

Is there any way that I can display the state name, just like the selected name in drop down when editing state field?

Check the table:

civicrm_state_province

specifically the column abbreviation for malaysia. If i had to guess, all the abbreviations are numeric and hence u r seeing numbers.

You can use PHPMyAdmin to find the relevant rows for malaysia. Your short term fix will be to populate the right values. Would be even better for you to submit a PR against civi-core so that changes get incorporated into future versions


Multiple webforms: Show list of those user has submitted? Is there a way to list all webform submissions user has submitted using views?

I have a site where there is hundreds of webforms. I need to create a block that contains all webforms by title current user has submitted.

If you are using Drupal 6.Try this view export code

$view = new view;
$view->name = 'test_webform';
$view->description = '';
$view->tag = '';
$view->view_php = '';
$view->base_table = 'webform_submissions';
$view->is_cacheable = FALSE;
$view->api_version = 2;
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */
$handler = $view->new_display('default', 'Defaults', 'default');
$handler->override_option('relationships', array(
  'nid' => array(
    'id' => 'nid',
    'table' => 'webform_submissions',
    'field' => 'nid',
  ),
  'uid' => array(
    'id' => 'uid',
    'table' => 'webform_submissions',
    'field' => 'uid',
  ),
));
$handler->override_option('fields', array(
  'title' => array(
    'id' => 'title',
    'table' => 'node',
    'field' => 'title',
    'relationship' => 'nid',
  ),
));
$handler->override_option('filters', array(
  'uid_current' => array(
    'id' => 'uid_current',
    'table' => 'users',
    'field' => 'uid_current',
    'relationship' => 'nid',
  ),
));
$handler->override_option('access', array(
  'type' => 'none',
));
$handler->override_option('cache', array(
  'type' => 'none',
));
$handler = $view->new_display('block', 'Block', 'block_1');
$handler->override_option('relationships', array(
  'nid' => array(
    'label' => 'Node',
    'required' => 0,
    'id' => 'nid',
    'table' => 'webform_submissions',
    'field' => 'nid',
    'override' => array(
      'button' => 'Use default',
    ),
    'relationship' => 'none',
  ),
  'uid' => array(
    'label' => 'User',
    'required' => 1,
    'id' => 'uid',
    'table' => 'webform_submissions',
    'field' => 'uid',
    'override' => array(
      'button' => 'Use default',
    ),
    'relationship' => 'none',
  ),
));
$handler->override_option('fields', array(
  'title' => array(
    'label' => 'Title',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'link_class' => '',
      'alt' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'link_to_node' => 0,
    'exclude' => 0,
    'id' => 'title',
    'table' => 'node',
    'field' => 'title',
    'relationship' => 'nid',
    'override' => array(
      'button' => 'Use default',
    ),
  ),
  'submitted' => array(
    'label' => 'Submitted',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'link_class' => '',
      'alt' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'date_format' => 'small',
    'custom_date_format' => '',
    'exclude' => 0,
    'id' => 'submitted',
    'table' => 'webform_submissions',
    'field' => 'submitted',
    'override' => array(
      'button' => 'Use default',
    ),
    'relationship' => 'none',
  ),
  'sid' => array(
    'label' => 'Sid',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'link_class' => '',
      'alt' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'set_precision' => FALSE,
    'precision' => 0,
    'decimal' => '.',
    'separator' => ',',
    'prefix' => '',
    'suffix' => '',
    'exclude' => 0,
    'id' => 'sid',
    'table' => 'webform_submissions',
    'field' => 'sid',
    'override' => array(
      'button' => 'Use default',
    ),
    'relationship' => 'none',
  ),
));
$handler->override_option('filters', array(
  'uid_current' => array(
    'operator' => '=',
    'value' => '1',
    'group' => '0',
    'exposed' => FALSE,
    'expose' => array(
      'operator' => FALSE,
      'label' => '',
    ),
    'id' => 'uid_current',
    'table' => 'users',
    'field' => 'uid_current',
    'relationship' => 'uid',
    'override' => array(
      'button' => 'Use default',
    ),
  ),
));
$handler->override_option('block_description', '');
$handler->override_option('block_caching', -1);


How do I pass dynamic parameters to a service? Is it possible to pass dynamic parameters when calling a service?
mymodule.services.yml
services:
  my_module.default:
    class: Drupal\services\DefaultService
    arguments: ['@entity_type.manager']

DefaultService.php
namespace Drupal\my_module;
use Drupal\Core\Entity\EntityTypeManagerInterface;

/**
 * Class DefaultService.
 */
class DefaultService implements DefaultServiceInterface {

  /**
   * Drupal\Core\Entity\EntityTypeManagerInterface definition.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  private $myValue;

  /**
   * Constructs a new DefaultService object.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;

    //how set $myValue?
    // $this->myValue = ???
  }

}

Is there a way to dynamically set myValue when calling this service,  for example while calling the service from hook_ENTITY_TYPE_update(), passing the $entity->id() value?
I've found similar questions, such as How do I pass parameters to a service? or  Create service with argument, but they don't answer my problem.

Giuseppe, I recommend defining your service using the Factory design pattern. You can then instance the factory and call a copy of your business logic class, initialized with the nid. I believe that this pattern is what @kiamlaluno was hinting at in his comment about using DatabaseBackendFactory.
Factory injection example
A simple and common example of this pattern would be getting an instance of a storage controller from the EntityTypeManager.
In your .services.yml file:
example_service:
  class: Drupal\my_module\MyExampleClass
  arguments: ['@entity_type.manager']

In your service class:
<?php

use Drupal\Core\Entity\EntityTypeManagerInterface;

class MyExampleClass {

  /**
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $termStorage;

  /**
   * @inheritDoc
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->termStorage = $entity_type_manager->getStorage('taxonomy_term');
  }
}

In the example above, the EntityTypeManager, which acts as a factory, has been injected, and then we call the getStorage() method to get an instance of \Drupal\Core\Entity\EntityStorageInterface that has been initialized for the taxonomy_term entity type.
Similarly, you could define a service that is, itself, a factory, and the factory would then be responsible for creating instances of your business logic class.
You could inject your factory service, as in the example above, by replacing the EntityTypeManager service with your own. You can also create an instance in a hook, like this:
my_module_node_view($node, $view_mode, $langcode) {
  // Get instance of your factory service.
  $my_service = \Drupal::service('my_service');
  // Get an instance of your business logic class from the factory,
  // initialized to use the nid that we provided from $node->id().
  $node_processor = $my_service->get($node->id());
  // Make the call to process the nid.
  $node_process->doBusinessLogic();
}

Plugins
It might also be helpful to know about Drupal 8's plugin system. Drupal 8's plugin system is essentially a specialized version of the factory pattern. If you have Drupal Console, then generating new Annotation plugins is easy. Depending on all of the requirements of your project, a custom plugin type might be exactly what you need.
Here are some tutorials and references on plugins that I have found to be useful:

https://robvarkonyi.com/blog/ultimate-guide-drupal-8/plugin-system-drupal-8
https://www.drupal.org/docs/drupal-apis/plugin-api
https://www.sitepoint.com/tutorial-on-using-drupal-8-plugin-derivatives-effectively/
https://drupalize.me/tutorial/what-are-plugins (requires subscription)


Control content access whilst creating content Is there  a way to control access during the content creation process?

With the Content Access module I can setup access controls for individual nodes of the same type, but only after I have created that content.

Could this process be integrated into the content creation process for the sake of intuitiveness.

Workbench, Workbench Access and Workbench Moderation modules could help you with access control and content management.

Workbench improves content management for Drupal 7.
It has more then 1200 reported installs.

Workbench allows to :

simplify the user interface for content creators and editors
limiting training and support time.
control who has access to edit any content based on an organization's
structure not the website structure
customize editorial workflow that integrates with the access control
feature described above or works independently on its own

Workbench Access
Workbench Access provides hierarchical permissions across "Sections" of your website. You can use menus, taxonomy or create your own hierarchical structure for controlling access to the content.

Workbench Moderation
provides editorial workflow. It is a flexible system. It provides default workflow states like Drafts, Needs Review, and Published. You can also change these states to suit your needs.


Problem with commerce_checkout_page_info() function I've been poking around in various forums trying to change the hard-coded values for the Checkout Page buttons and titles. For semantic reasons, I want to change the last submit button from 'Continue to next step' to 'Complete Submission'.

I have had success in changing the other buttons with combinations of hook_form_alter() and how hook_menu_alter()

function bartik_form_alter(&$form, &$form_state, $form_id){
dpm($form_id);
dpm($form);
if (commerce_form_callback($form_id, $form_state) == "commerce_cart_add_to_cart_form"){
    $form['submit']['#attributes']['title'] = $form['submit']['#attributes']['value']=t("Add to Inquiry List");
    }
if(strpos($form_id, 'views_form_commerce_cart_form_default')===0){
    $form['actions']['submit']['#value'] = t("Update List");
    $form['actions']['checkout']['#value'] = t("Submit List");

    }

However, I am having problems changing the final submit button in the commerce_checkout_form_review form. I've tried the method suggested here http://mtt.desk.com/customer/portal/articles/1430204-how-to-customize-the-label-of-the-drupal-commerce-button-on-the-order-review-page, both as a module and as a function in the theme template, but neither method produces an error or gives me the desired text change.

function co_button_commerce_checkout_page_info_alter(&$checkout_pages) {
$checkout_pages['review']['submit_value'] = 'Submit Order';
}

So, I've been trying a couple of different variations, but I'm still not sure how to target the buttons on that form. I have also tried this little if statement, but it's still not effecting the change.

if(strpos($form_id, 'views_form_commerce_cart_form_default')===0){
$form['buttons']['continue']['#value'] = t('Complete submission');
}}

TIA, any advice would be greatly appreciated.

I think this is the relevant portion of the array

buttons (Array, 4 elements)
#type (String, 8 characters ) fieldset
#attributes (Array, 1 element)
continue (Array, 6 elements)
#type (String, 6 characters ) submit
#value (String, 21 characters ) Continue to next step
#attributes (Array, 1 element)
#suffix (String, 59 characters ) <span class="checkout-processing element-
#validate (Array, 1 element)
#submit (Array, 1 element)

I think you can handle it with hook_form_later, try something like below,
change your condition according to your checkout base name ,
I hope this help you :

/**
 * Implements hook_form_alter().
 */
function yourmodule_form_alter(&$form, &$form_values, $form_id) {
  if($form['checkout_pane']['#value']['base'] == 'checkout_pane_review') {
    $form['submit']['#value']='yourvalue';
  }
}


Content type with a field of multiple values of other content type (1-n relation) What should be the approach for the common cases where we need a content type with a field of multiple values of other content type? The typical "1 invoice as n invoice lines" where invoice is a content_type and *invoice_line* other content type.
I did some research and I'm confused because there are: Relation, References, Entity References...
(For Drupal 7)

Thank you.

The Entity reference would be the best choice for your requirement. It is also a successor of the References module.

  References will most probably be deprecated in the near future in
  favor of Entity Reference, which should probably be considered first
  on fresh D7 projects.

The Relation module is more suitable for complex relationship. You can see this clearly in its module page:

  Relation is an API module and storage model for both simple and the
  most complex relations between entities. The module can handle both
  directional and symmetrical relations very well.

  Relations are entities and can therefore have fields. This makes
  Relation the most flexible and powerful relation model out there.


In Views, how can I use the rewrite text to include an image in HTML with some text and then translate the text? I've installed Views along with the Internationalization views module.  I have a view of users.  The users have some single-value boolean fields in their profiles.  I would like to rewrite the results of these fields so that if they are true an image and some text is shown.

Example: If "likes_soccer field is true, then show an image of a soccer ball with the words "Loves soccer"

This is quite simple to do in Views.

However, I also need to translate the text, and this is where I'm running into problems.  Internationalization Views allows the text to be translated, but because it is HTML it ends up being sanitized so that the IMG tag is displayed as code rather than interpreted as HTML (as this answer explains).  I can simply ignore the IMG tag in my translation, which will allow me to translate the text, but then I will lose the image in the translation.

Is there an alternative way to do this?

I hit upon a very straightforward solution for doing this-- simply add each field that needs to be rewritten twice.  Place the IMG tag in one field and the string to translate in the other.  This way, no custom code need be written and everything can stay in Views.


Migrate files attached to comments from D6 to D7 While migrating from Drupal 6 to Drupal 7 (into a new blank site), I noticed that files attached to comments are not handled by the Migrate module. The D6 site uses a contributed module „Comment Uploads“ that associates files with comments in a table comment_upload:

+------+------+-------+----------------------+------+--------+------------+
| fid  | nid  | cid   | description          | list | weight | legacy_fid |
+------+------+-------+----------------------+------+--------+------------+
| 1002 | 1001 |  1000 | under_149.jpg        |    0 |      0 |          0 |
| 1774 | 1969 |  6855 | ruler.png            |    0 |      0 |          0 |
| 1706 | 1712 |  6009 | 1.png                |    1 |    127 |          0 |
| 1703 | 1712 |  6006 | 2.png                |    1 |    127 |          0 |
| 1704 | 1712 |  6006 | 3.png                |    1 |    127 |          0 |

Nodes, comments and files already migrated successfully to D7 using the migrate_d2d module and its user interface. Node attachments went through fine. Except comments no longer have files attached now. Since files and comments exist, it should be possible to attach the files to their original comments, using the above table.

Q: How would I go about and migrate comment attachments properly?

a) Would it make sense to hack the migration class for D6 comments? The issue is: The comment attachments do not appear as a source field in the Migrate user interface, as they do for nodes. Maybe if this could be achieved, this would be the best solution.

b) Why not grab that above table’s data (some 1000 rows only), iterate over it and call the appropriate D7 API to attach each file (fid) to its original comment (cid)? If so, which API calls should be used and where do I place this code?

Despite doing software development for decades, Drupal’s inner underpinnings are new to me. Any help is highly appreciated.

Edit: I don't want to use the Comment Upload module under D7 anymore.

Consider looking at this Github link mentioned in Comment #35 of Issue # 554986 ...

If it works for you, then please add an appropriate comment about that in that issue (which currently has status "needs review" ...). And of course let us know about it around here also ...


Drupal 7 How to make the value of a user field (site_path/admin/people) dependent on user role I am using the module Administration Views (https://www.drupal.org/project/admin_views) to change the layout and content of the Drupal users view at "site_path/admin/people". The site I am working on requires that users pay yearly for membership using Ubercart. Using Ubercart's add user role on purchase functionality, I have added the "Paid User" role to the site. When any registered user makes an Ubercart purchase of a "Membership", he/she is given this Paid User role.

The site admins want to be able to track users by whether or not they have made their yearly payments to ensure that their privileges within the organization for which I am producing this site reflect their membership payments. Therefore, I have added a "Dues Status" field to the "user" node type and displayed it in the Drupal users view at "site_path/admin/people" using the Administration Views module.

However, as the tracker for "Paid Dues" is whether or not the user has the role "Paid User" rather than a user edit, I have been unable to make the value of the "Dues Status" field update in the view. Since Administration Views has access to each user node in their respective views rows, I considered using Views PHP (https://www.drupal.org/project/views_php) to try to access the data in  the "User Roles" field and check for the presence of the role "Paid User", but I did not know how to do this and change the value of the "Paid Dues" field.

I am familiar with re-writing fields using HTML, just not with PHP. Could someone explain how to use Views PHP to rewrite the value of a user field by checking for a user role on that user? Or, if there is a module I have been unable to find that can do this, please let me know.

Please never ever use something that uses eval(). Even if you don't migh related security problems because nobody else has access to your site eval() is very very slow.

What you are looking for is hook_views_pre_render()

or a preprocess hok for the specific field. There are plenty examples if you use google.


Is it possible to combine RSS feeds and other stories in the same view? I subscribe to an RSS feed I would like to post in the same view as some user-generated stories and I would like both types of content to display as a uniform list. Can that be easily done?

Can you give more details? Do you mean importing a feed into your website and then displaying its contents alongside your own? You'd need the Feeds module to do that.

UPDATE: Yes, this is possible. You need the Feeds module, and to create a content-type to hold the feeds. When displaying your view, use Filters to narrow it down to just your user-entry content-type and the Feeds-info content-type, and they will both display (in whatever order you set, the default is posted date).


Create User Dashboard as startpage hope that you can help me.

Version: Drupal 6/7

i need information about a user dashboard.

we want to create a intranet solution with bug/ticket reporting/scrum functionality and need for a overview a User/Team overview (newest issues/newest tasks etc.). but i don't found any help/information about a user/team dashboard.

1.) can i set a dashboard as startpage?

Greets Frank

You could use Homebox and redirect the user to their individual dashboard on login (possibly using LoginToboggan or Rules).  I've used it before and it's pretty neat.

Following that, you just create views to display your tickets/issues/tasks etc and display them in the homebox.


403 forbidden for all css files located in /modules My multi site Drupal 7 installation is suddenly unable to load any CSS file located in the /modules folder and subfolders (for example http://example.com/modules/system/system.base.css). I get "Failed to load resource: the server responded with a status of 403 (Forbidden)" in the browser console.

All CSS files for installed custom modules and all custom theme CSS files (inside /sites/all/modules and /sites/all/themes) are loading just fine.

Even more strange: the /modules/ CSS files load fine if I enable "Aggregate and compress CSS files." in Configuration > Development > Performance. When I disable "Aggregate..." I get the 403.

I realize that aggregating CSS is recommended in production sites, but I need to figure out what is going on and why the CSS files are not loading (they were loading fine earlier today). I did some changes in permissions earlier today, but I reverted those, with no success.

Any ideas?

PS: I noticed that Drupal adds "?obkukf" after .css - what is this, and does this have anything to do with the problem?

That extra query string are used to control caching. That will change everytime the cached files expired.

As per Dave Reid:

  It's to prevent browsers from caching those files when they change.

See these threads:

https://www.drupal.org/node/346711
https://stackoverflow.com/questions/11362261/appending-query-string-to-all-js-and-css-files-to-prevent-caching


Data not received on server in ajax I'm trying to post data from ajax to php page which I made in the hook_menu, called "handler".
So I have "domain.com/handler" which I try to do this in it:

function handler(){
  print_r($_POST);
}

and the hook looks like this:

$items['handler'] = array(
  'title' => 'Handler',
  'description' => 'handler for File Upload',
  'page callback' => 'handler',
  //'access arguments' => array('access my_module_name via ajax'),
  'access arguments' => array('access example ajax'),
  'type' => MENU_CALLBACK
);

and on my js file i do this:

$.ajax({
  url: "/handler",
  type: "POST",
  dataType: "json",
  data: {"name":"John","location":"Boston"}
})

and its wrapped inside Drupal.behaviors.mymodule = {...}
when I run the ajax, the response I get is an empty array.
why don't I receive the data?

$_POST is:

  An associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.

That's not what you're doing. To receive JSON data in PHP you need to use:

$data = json_decode(file_get_contents('php://input'), true);
print_r($data);

Or change the data type of your AJAX request to one of the values that will result in $_POST being populated.


Select list field type as sorting order criteria I have a view which uses a custom field called article type as it's sorting criteria to sort articles. This article type field, has the following options:

0Editorials|Editorial
2Feature|Feature
5Spotlight|Spotlight
6Special|Portraits
3Perspective|Perspective
8Research in Translation|Research in Translation
7Columns|Column
4Interviews|Interview
1PhotoEssay|Photo Essay
0Introduction|Special

The reason I have a number preceding the text in every option is so that, when I use this field as a sort criteria and choose the order as ascending, Views actually looks for the key text and arranges the results in that order (0 to 8 in this case).

Now, I want to achieve this same order without having to tamper with the key|value pairs like I have done. I have heard of Draggable Views, but I'm not sure that solves the issue here, since this view takes a contextual filter value and the results are always dynamic based on the filter value that is passed to it from the URL.

So is there another way to use a select list's options as a sorting criteria, but in an order that we want it to be in?

Looking for approximately the same, but I believe this isn't easily solvable. What you could do is use taxonomy instead and then sort the view by the term weight (create a relation to the taxonomy in the view and you get term weight as sort criteria).


How can I filter multiple nid at the same time using Views exposed filter? I have an node view with an exposed filer for nid.
It seems that I can put only one value (one nid) in there.
But is there anyway I can filter down nodes by multiple nid?
I tried these in the form
"1 and 2"  "1,2" "1 2" but didn't work.

I don't think this can be done by Views only.

You must create a custom module that use the hook_views_query_alter() (The code is for Drupal 7)

function my_module_views_query_alter(&$view, &$query) {
  // we only want to alter this view, so we check against the machine name
  // and we make sure our exposed filter is set
  if ($view->current_display == 'my_current_display' && $view->exposed_raw_input['nid']) {
    // first we grab the value from our filter and convert it into an array
    // make sure you use the same character you used to delimit the string
    $nids = explode(',',$view->exposed_raw_input['nid']);

    // now we loop over the array of values we created from our exposed filter field
    foreach ($nids as $nid){
      // Be conscience of the ‘where[1]’
      // In the $query object you noticed the conditions array had multiple arrays.
      // Each filter in your view will be placed in a conditions array.
      // It is important to include the empty brackets [] after ['conditions']. This will append the new conditions instead of overwriting them.
      $query->where[1]['conditions'][] = array(
        'field' => 'node.nid', // this is ‘table.field’ from your database. If you used another filter than ‘Content: nid’ this will change. i.e ‘users.uid’
        'value' => $nid,  // looped value from our values array
        'operator' => '!=',  // condition operator. I want to filter out nids, so I am using ‘not equal’
      );
    }
  }
}

Disclaimer: I run a similar issue and the solution gave to be by the below article. The code and the credits go to Peter Schuelke.

More information can be found here:

  http://www.metaltoad.com/blog/passing-multiple-values-through-exposed-filter


Get route name from path with wildcard we've wanted to implement a policy to consider some URLs as whitelist, I've provided a config form to admin to enter whitelist Urls, separated by newline, it must support * ( wildcard).

sample urls are

/user/*/edit
/coming-soon

and my implementation

$config = $config_factory->get('mint_coming_soon.softlaunchconfigadmin');

$white_route_list = $config->get('white_path_list');
$white_route_list = $white_route_list ? preg_split("/\\r\\n|\\r|\\n/", $white_route_list) : NULL;
$is_white_route = FALSE;
foreach ($white_route_list as $route) {
  $route_name = $this->pathValidator->getUrlIfValid($route);
  $route_name = $route_name ? $route_name->getRouteName() : NULL;
  drupal_set_message($route_name);
  $current_route_name = \Drupal::routeMatch()->getRouteName();
  if ($current_route_name == $route_name) {
    $is_white_route = TRUE;
    break;
  }
}

$this->pathValidator->getUrlIfValid doesn't work on URLs with the wildcard, my question is how can I get the route name of Url which contains a wildcard?

Notice: wildcard in this question is particularly *.

$pattern = '/user/*/edit';
$route_provider = \Drupal::service('router.route_provider');
$found_routes = $route_provider->getRoutesByPattern($pattern);
$route_names = [];
foreach ($found_routes as $route_name => $route_object) {
  $route_names[] = $route_name;
}


Event calendar help - creating view of event with all registered users in a block I am new to Drupal so I encounter this problem. I've installed Event Callendar. Using tutorials found all over the web I made a signup content type and displaying list of registered users for each event using Eva reference.

I would like to make a block of latest event and registered users in the front page. The problem is that my list of registered users take context filter from node URL (where event content is displayed).

How can I put all of this in a single block and set context filter of users list to URL of the event?

This is very confusing. I am trying to do it for the last two days with no luck ...

You can create a block and output your view with PHP, that way you can control which argument to pass:

<?php
  print views_embed_view('your_view_name', 'display_id', $your_argument);
?>

You can get 'your_view_name' and 'display_id'from the view's edit page:

'your_view_name' from the URL, something like admin/structure/views/view/your_view_name
'display_id' on the right side under "Other" > "Machine Name". It's usually something simple like 'block_1', or if you have a single display, try 'default'.

Also remember to set the text format to PHP code.


Question about part of Comment.module The following is part of the comment.module file (line 950):

// Add indentation div or close open divs as needed.
if ($is_threaded) {
  $prefix .= $comment->divs <= 0 ? str_repeat('
', abs($comment->divs)) : "\n"     . '
';
}

Can someone explain that what is it doing?

For reference, this is in the comment_view() function.

It is equivalent to this, which makes it a little easier to understand:

if ($is_threaded) {
  if ($comment->divs <= 0) {
    $prefix .= str_repeat('
', abs($comment->divs));
  }
  else {
    $prefix .= "\n" . '
';
  }
}

$is_threaded is a boolean value for whether or not threading has been enabledfor comments in the settings for this content type.

$comment->divs is set in comment_prepare_thread() and is a count of the indentation divs required to have this comment in the right place in terms of the comment's depth. So this value will either be 1 if a new indentation div needs to be added to make sure the comment is at the correct depth, or a negative number, which is how many indentation divs need to be closed to have the comment at the correct depth.

So if comment threading is enabled, then if $comment->divs is less than or equal to zero then close zero or more indentation divs by appending str_repeat('
', abs($comment->divs)) to the markup otherwise, if $comment->divs is 1 then open a new indentation div by adding '
' to the markup.

For example if you had these comments:

Comment 1
-Comment 2
--Comment 3
---Comment 4
--Comment 5
---Comment 6
----Comment 7
-----Comment 8
-----Comment 9
Comment 10
Comment 11
-Comment 12
Comment 13
Comment 14

Then for each comment, $comment->divs would be:

Comment 1: 0
Comment 2: 1
Comment 3: 1
Comment 4: 1
Comment 5: -1
Comment 6: 1
Comment 7: 1
Comment 8: 1
Comment 9: 0
Comment 10: -5
Comment 11: 0
Comment 12: 1
Comment 13: -1
Comment 14: 0


Form Select not rendering as a dropdown I'm building a form that contains a select but it's not rendering as a dropdown. It's rendering with a scrollbar and a dropdown down arrow

$form['my_select'] = [
  '#type' => 'select',
  '#empty_option' => '- None -',
  '#title' => $this->t('My Select'),
  '#options' => ['Option1', 'Option2'],
  '#size' => 6,
  '#weight' => '0',
];

What am I doing wrong?

It's rendering as a list because you have set #size to 6, which means 6 rows will be visible. Either remove the #size property completely, or set it to 1 to display a normal dropdown.

From the documentation:

  #size: The number of rows in the list that should be visible at one time.


search with transliteration How I can implement transliterated searches?
for example if someone write in latin characters these to be converted to another coding characters?

How I can instruct drupal that latin character a corresponds to another language character?

Or how i can integrate google transliteraion api in drupal search?

Thanks

This is possible by implementing hook_search_preprocess() and integrating with the Transliteration module.  Example code is below:

<?php
/**
 * Implementation of hook_search_preprocess().
 *
 * Transliterates text added to the search index and user submitted search
 * keywords.
 */
function mymodule_search_preprocess($text) {
  return transliteration_get($text, '', language_default('language'));
}
?>

There is a more complete example and discussion at http://drupal.org/node/1058064.


Redirect to last page after saving new content with rules Drupal goes normally to the new node after creating or editing it. How to redirect to the last page where the user clicked on the node/add link using rules?
I tried different tokens with no success. Here is the rule:
Let's say we are on url: sitname/node/133
a user clicks on node/add/announcement
Rules: after saving, I need to go back to sitename/node/133
Rules:
After saving new content type:announcement

Action: Redirect to page sitename/node/ (token) not sure what to do here

I solved it by taking another route. The original page I wanted to be redirected to is a node type page; on that page, there is a link to create a new node type (announcement).

I didn't mention that the announcement node is referencing the page node through the Entity reference module. To be redirected to the old node type page, I need to use the token [node:field-new-habit-ref:url] in the action section of the rule.


Installing Drupal patches in Ubuntu terminal I'm new to Ubuntu and I never ran Drupal patches before and now is my first to do so: I've searched here in the Drupal answers with the phrase: "Patches, Ubuntu" But I didn't find instruction on how to run patches for a module in a local site via the Ubuntu terminal. I've also searched some in Google in Youtube but I found ways for many other CLIs, but not for the Ubuntu terminal.

Is it possible to run the patches there as I would run Drush commands?

As far as I know there is nothing in specific about applying patches for drupal in ubuntu.

If you are already using git for managing your project code then you can apply a patch to a project's repository by using following code:

git apply -v path/file.patch

If you are not using git, or if the repo isn't a local checkout of the project you wish to patch:

patch -p1 < path/file.patch

For more information, check https://www.drupal.org/patch/apply

Live example for patching in Drupal 8:

Download the .patch file (in this case: Add_rtl_support.patch)
Copy it into the particular module's directory (since the patch is relative to the module directory).
Change the destination directory in the Ubuntu terminal to the module's folder - In this case it should be cd modules/admin_toolbar.
Apply the patch using 2nd method patch -p1 < Add_rtl_support.patch


A block created with Views is not rendered if the page URL contains "page=" I have an odd problem. I'm using Drupal 7 and an Omega subtheme. Within Views, I have a block defined and it works great - appears where it's supposed to all over the site - except when the URL has a "?page=" in it. Some possibly relevant info: clean_urls and pathauto enabled, Delta and Layout installed but no Deltas defined.

I discovered this when I created a page View (of a different content-type) that features the pager to scroll through the results. When using the pager it appends "?page=1", "?page=2", etc to the URL. I think it does it by default and from what I've read it seems to be difficult to change this. I could probably put up with the non-clean URLs but the bigger issue now is trying to work out why this results in my first view block not being rendered. I've tested it out by navigating to random pages on the site and appending the "?page=" to the URl and it's always the same result - the block view's not displayed.

Do you have any idea, or any pointer to where I should start looking?

I think I worked out what the problem was. The way the View selected the content, there could only be one result (the View is to show the current exhibition for an art gallery website, and they only ever have one exhibition at once). Because by design it could only produce one result I didn't even think about the pager, which was to Full by default.

This caused problems when that block was rendered on the same page as another View - one which deliberately has a pager. Maybe there's an issue with multiple pagers on the same webpage?

Anyway, I changed the block View's pager settings to "Display a specified number of items | 1 item" and that fixed everything - now there's only ever one pager on the webpage and now my block view is displayed on every page as it's supposed to.

Edit: Will click this as accepted answer in 2 days when I'm allowed to


Context shows empty views block I've got a views block that shows data from node field.

I've set up a contextual filter

NID:

WHEN THE FILTER VALUE IS NOT AVAILABLE

Provide default value: content ID from url.

I've also set up a context show this block

Condition: Node Type

Reaction Block

It works fine, but if the field is empty it will show Block title and empty content.

Is there a way I can hide the block if the view is empty?

Thanks in advance

I've added FILTER CRITERIA: my_field (NOT NULL)... it was so simple...


Webform Module and Elements Module I have a hook that i wrote to include the elements fields (i.e, telfield) in a webform. The field doesnt take on the same css as the rest of the fields which means I probably need to add a style to the CSS for it. However, I'm trying to figure out a way to implement this globally so that I will be accepted as a regular form component since I have over 40 different themes that this will be applying to.

This is an attempt to avoid having to go into each them and adding the style.

Thanks,

there is no way to add a stylesheet and be global for all the themes you have inside sites/all/themes

The unic way is that all your different 40 themes were subthemes of one parent theme then you can have your styles in the parent theme and all your subthemes will inherit the styles of the parent, there is no other way...


How to render Entityform submission (entity) without DOCTYPE and HEAD tags? I need to render entity as a part of page instead of individual page. By this I mean I want to able to render it without DOCTYPE declaration and HEAD tags.

Typically this could be done within html.tpl.php but I haven't found the correct naming  convention or other solutions.

How to render entity programmatically in a bare div container using Entity view modes? This shouldn't be a huge problem since e.g. Views can list entities using a certain display/view mode. I'm trying to render it in a Rules config to send it out as email.

So in the end it was the Emogrifier class that kept adding the DOCTYPE and everything else.

It would have been good to know that it adds CSS inline but it also fixes/creates a whole new document. So it can't be used for e.g. fragments or in this case entities.


saving any view clears all cache I am working in drupal 6. I know that saving any node clears cache but is the same with views? I am experiencing this issue. I would like to know how to prevent it. Thank you.

If we inspect views_ui_edit_view_form() we can see the following #submit handler being assigned:

  $form['buttons']['save'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
    '#validate' => array('views_ui_edit_view_form_validate'),
    '#submit' => array('views_ui_edit_view_form_submit'),
  );

Drilling further down into views_ui_edit_view_form_submit() it becomes clear which caches are affected by saving a view:

  // Make sure menu items get rebuilt as neces
  menu_rebuild();

  // Clear the views cache.
  cache_clear_all('*', 'cache_views');

  // Clear the page cache.
  cache_clear_all();

  // Remove this view from cache so we can edit it properly.
  views_object_cache_clear('view', $form_state['view']->name);

In summary, these are the caches that get cleared when a view gets saved:

menu
views
block
page

In addition, the menu rebuild triggers the following hooks:

hook_menu()
hook_menu_alter()


Adding metadata to content types I'm trying to add more fields to my content types.
I have a content type called Cars, and another called Airplanes; I want they belong to a category called "Transportation".

If I want to get a list of all transportation content types, it will return Cars and Airplanes.

Use taxonomy but automatically assign the taxonomy. So anytime you create a car, it's automatically assigned to term "transportation." You can do this with the Taxonomy Defaults module.

  Taxonomy Defaults allows you to assign default terms from any vocabulary to any node-type. The default terms will be pre-selected on the /node/add form, but can be edited.

  If a vocabulary is marked as "Hidden" for a particular content type, then that vocabulary will not be shown on the /node/add form and the default terms will be assigned automatically and cannot be edited.

The module is a bit tricky to get at first, make sure you select "hidden" so that the user can't change the default taxonomy.


How to make a relation between nodes in drupal 7? I need to create a relation between to nodes in drupal 7 without taxonomy.. because I don't have taxonomy option for drealty_listing.. And after I need to create a view regarding these relation.

Entity Reference module works well. But If you need to create a view, you may use Entity View Attachment module. This module attaches a view to a node.


Webform Serial - Serial Numbers updating after editing submission I am using webform serial to generate tracking numbers for webform submission.

If I edit a submission the serial number auto increments to the next available number. How can I stop this from happening and have the number locked - even when I edit a submission?

I was going to suggest placing an issue on the project page-it seems like it would be a common issue-but you've already done so. If the maintainer doesn't respond, you could look at the code yourself to figure out why and create a patch for it.


Theme div.item-list of views pager? How can I theme the div with a class of item-list that appears around a views pager? All I need to do is add an additional class to this div when it surrounds a pager.

I can find lots of documentation on theming the content of the pager, but none on how to theme them this div.

Typically, unless you are using a specific contributed module, the pager is a template file that comes with views. You can override theme_pager for the specific view (or all your paged views) and add the additional div.

https://api.drupal.org/api/drupal/includes!pager.inc/function/theme_pager/7

Examples on how to do this:
https://www.drupal.org/node/387786


Unpublished Nodes and Content Access I have a view that relies on a specific content type to display images. The Content Type has a Title,  a File Field, and a checkbox for show or don't show.  The default setting for all nodes created using this Content Type is unpublished, so that users can't randomly access the node ( basically it's a slideshow that displays banner ads, accessing the actual node isn't a bad problem per se ).

This works great.  As it turns out I also need a members only section for the site, so I installed Content Access.  That works great for restricting access to the nodes I need restricted.  However, I discovered that now the unpublished Slideshow nodes don't show.

My question is how to work around this.  Will another access module work differently or is this a core feature?  Could I write a small module to grant view access to the Slideshow nodes?  Or barring all that, is there a module or ( I know it's probably off-topic) an htaccess recipe that would not allow direct viewing of the nodes of a certain type?

I solved this by making the Content Type nodes published again.  So in my View I check to see if the checkbox is check AND if the node is Published.  The slider works as it should.  I was then left with the task of deciding if allowing access to the actual node was desirable.  Viewing the direct node in my case was not all that bad, it's not restricted content or anything but I felt it would just be sloppy.  So since I had Panels already installed, this solution https://drupal.stackexchange.com/a/19072/12881 worked out great.  If someone stumbled upon one of the nodes of that specific Content Type they're just sent to the front page.


Custom theme function with drupal render I'm trying to make a custom module based on menu module to render a sitemap.

I want to use a custom theme function for rendering it but for unknown reasons my variables are not passed to the theme function. Here is my code (simplified so we get what matter) :

function custom_module_theme() {
  return array(
    'custom_module_link' => array(
      'variables' => array(
       'attributes' => NULL,
       'title' => NULL,
       'href' => NULL,
       'below' => NULL,
       'original_link' => NULL,
      ),
    ),
  );
}

function theme_custom_module_link(array $variables) {
 $element = $variables;
 $output = ...;
 ...
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . "</li>\n";
}

function _custom_module_tree_output($tree) {
    ...
    ...
    // Allow menu-specific theme overrides.
    $element['#theme'] = 'custom_module_link';
    $element['#attributes']['class'] = $class;
    $element['#title'] = $data['link']['link_title'];
    $element['#href'] = $data['link']['link_path'];
    $element['#original_link'] = $data['link'];
  }
 return $element;
}

function custom_module_page() {
  $tree = ...
  $output = _custom_module_tree_output($tree);

  return drupal_render($output);
}

This code return a error page with the following : TypeError: Argument 1 passed to drupal_attributes() must be of the type array, null given ...

I don't understand why drupal_render doesn't iterate over the $element['#theme'] call to fetch variables as described in the documentation. What I'm missing ?

  From the doc : Basically, the '#theme' = 'function_name' calls
  theme_function_name(), and other array values of the form '#var_name'
  = $value in the same array are passed as arguments to the theme function

If I dpm $variables in my theme_custom_module_link function, variables are set as NULL as in my hook_theme ...

What I wanted to do is to get the html through a function and not a template. So actually there is no need to set the variables, just the 'render element' did the trick.

function custom_module_theme() {
  return array(
    'custom_module_link' => array(
      'render element' => 'element',
    ),
  );
}


Webforms preview Tpl page I want to alter some data on preview page of Webform and I want to add Tpl for it .
How can I theme for Webforms preview page , and what's the Tpl for it ?

I find two solution links, please check them:

Sol-1: https://www.drupal.org/node/1430034 (Most relevant solution)

Sol-2: How to theme a webform - D7 (It another solution to theme webform with another tpl name: webform-form.tpl.php. Here is the link which provide tpl code.)

I guess you need to use node--webform.tpl.php and also add preprocessor in template.php.

function themeName_preprocess_page(&$vars, $hook) {
  if (isset($vars['node'])) {
    $vars['theme_hook_suggestions'][] = 'page__'. $vars['node']->type;
  }
}

And when you create tpl file you can check preview variable to check and theme accordingly.

If this doesn't help try second solution.


getFormId() must be compatible with Drupal\Core\Form\FormBuilderInterface::getFormId (Drupal 8) I newish to Drupal and very new to Drupal 8, as this comes out in a couple of weeks it seems to make sense to grab the bull by the horns and start any new project with this now! Anyway I was following pretty good tutorial: http://www.drupalwoo.com/content/blog/my-first-drupal-8-module on creating a Drupal 8 module but it looks to be a year or two old and things have changed. I am getting the following error:

Fatal error: Declaration of Drupal\bd_contact\AddForm::getFormId() must be compatible with Drupal\Core\Form\FormBuilderInterface::getFormId($form_arg, Drupal\Core\Form\FormStateInterface &$form_state) in modules\custom\bd_contact\src\AddForm.php on line 7

This is the file in question: https://github.com/nlisgo/bd_contact/blob/master/src/AddForm.php could anyone tell me what would be the correct way? I have googled it quite a bit and found similar issues but I can't see how I'd integrate those changes into mine.

In my project it works as public function without arguments since drupal beta 1 until today (i've updated today to rc3):

 public function getFormId() {

You only have to add public to your function.

Otherwise your error suggest, that there are the two arguments form and form_state missing, what is also described in the api.drupal.org:

public function FormBuilder::getFormId

But I don't think, that you need these arguments in the definition of the getFormId(). This is probably a false alarm. You only need these arguments, when using the function in the context of formBuilder, when you don't provide the form through your class, for example like this:

this->formBuilder->getFormId($form_arg, $form_state)

Edit:
Berdir has the right clue, you have to change this:

wrong: class AddForm implements FormInterface {
right: class AddForm extends FormBase {

and the use statements for this are:

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

This is a complete example:

<?php
/**
 * @file
 * Contains \Drupal\mymodule\Form\OrderForm
 */

namespace Drupal\mymodule\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements an form.
 */
class OrderForm extends FormBase {

  /**
   * {@inheritdoc}.
   */
  public function getFormId() {
    return 'mymodule_order_form';
  }

  /**
   * {@inheritdoc}.
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

  }

   /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {

  }

   /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

  }


How do you add rules to specify zero rate VAT when a VAT number is supplied? I'm using the Commerce VAT, Commerce EU VAT and VAT Number modules and would like to add a rule so that if someone is within the EU (but not in the UK) and enters a valid VAT number, the VAT rate is set to zero rate.

Our current setup is working so that purchases from within the United Kingdom are being charged VAT, purchases from outside the EU are not, but I've also added the VAT Number module so that people who are in the EU but not in the UK are charged zero rate tax.

I've overwritten the validation function within the VAT Number to bypass the SOAP server for the purposes of testing, but when I get through with a, say, FRXX ** VAT Number, the full 20% is still being added. I'm guess I need to create a rule to work with the VAT Number, but I can't see how or where, as I'm still relatively new to Rules.

How do I create a rule so that the VAT rate on an order changes to zero rated when the customer supplies a valid VAT number, is within the EU and not in the UK?

Any help here would be appreciated.

The rules for adding zero-rated VAT to other EU countries when a valid VAT Number is supplied are added when you enable the 'Commerce EU VAT Intra-community Supply' module in the 'COMMERCE EU VAT' module group.


Setting a default checkbox value in FAPI Trying to set a default value on an entity reference field.

$unitid = node_load($unit);
$form['field_choose_a_service']['und']['#default_value'] = $unitid;

  Warning: Illegal offset type in form_type_checkboxes_value() (line
  2390 of
  /homepages/43/d503288075/htdocs/example.co.uk/includes/form.inc).

  Notice: Object of class stdClass could not be converted to int in
  form_process_checkboxes() (line 3316 of
  /homepages/43/d503288075/htdocs/example.co.uk/includes/form.inc).

And targeting the nid from that loaded node...

$unitid = node_load($unit);
$form['field_choose_a_service']['und']['#default_value'] = $unitid->nid;

  Warning: Invalid argument supplied for foreach() in
  form_type_checkboxes_value() (line 2389 of
  /homepages/43/d503288075/htdocs/example.co.uk/includes/form.inc).

The first one actually works, but kicks up the errors. What am I doing wrong?

Essentially I want to check if the nid im passing in the URL as a _GET query matches an option in the entity reference checkbox options, and make that option selected if it does.

Try this one:

$unitid = node_load($unit);
$form['field_choose_a_service']['und']['#default_value'] = array($unitid->nid);

And please note that node_load returns an object but not a ID. I see you use $unitid as the variable name. It can make people confused.


Combine 2 content types into view I am facing trouble with view having 2 content type without relationship.

content type 1: (toys) title, body, series_taxomony, price

content type 2: (areas) title, area_name, percentage

I'd like to have a view to display a form like
series_taxonomy and area_name are exposed to user select from list and show detail

serias_taxonomy
price
area_name
percentage

In order to complete view, what should i do and is there any way to restructure content type to do easier

Thanks in advance

Well if I am getting you right, for this issue you should do this;
Create a new view, and in filters option select type "toys" and again select type "areas", this will give you 2 content types into one view.

For exposed filters, in the filter criteria, select both the fields, "series_taxonomy" and "area_name" and select them as exposed filter.

Hope this helps.


Changing Site Background on button (and carrying it over to all pages on site) i'm trying to create a drupal site where under the logo, there would be three options visisble (light, dark, color), and once the user clicks on one of them, the site background will change.

now i know that this is easy to do with javascript (button, changing css background-image element)

but, how can i carry it over so that if the user clicks on a link on the site, the background-image stays the same without revolting to default?

i couldn't find any resources on how to do it, but i would gladly appreciate all of your help and anyone else on the interwebs with the same idea :)

You could change the background with JavaScript and also save that preference in the user's Local Storage - which is basically a cookie that doesn't get sent to the server. It gets erased when cookies get erased.

First you need a JavaScript function to check that LocalStorage is available. Here is the function I use, cribbed from Stack Overflow:

function localStorageTest(){
  var test = 'test';
  try {
    localStorage.setItem(test, test);
    localStorage.removeItem(test);
    return true;
  } catch(e) {
    return false;
  }
}

You'll throw an exception if the localStorage object is not available (e.g. if cookies are completely disabled), so that's why the try/catch.

Then you need to check for a preference when the page loads. I'm using jQuery here:

if (localStorageTest()) {
  var bgcolor = localStorage.getItem('bgcolor');
  $('#page').css('background-color', bgcolor);
}

Finally, some code to set the preference - assuming here we are setting the same color as the button. You could use another attribute on the element to store the value. jQuery again:

$('#button').click(function() {
  var bgcolor = $(this).css('background-color');
  $('#page').css('background-color', bgcolor);
  if (localStorageTest()) {
    localStorage.setItem('bgcolor', bgcolor);
  }
};

Just to add some Drupal to this answer, there is a Local Storage module that doesn't quite do this yet, but could potentially work if you set up a custom form and send the color choice as an AJAX form submit.

Also consider the Session Cache API module if you are going to elaborate on this example - it won't do what this example does, but it can help perform similar tasks.

I haven't tested this code, so there may be errors - consider it at least a roadmap to accomplishing the task.


How do I migrate the content of a SQL table? I have a sql table which contains Visitor name, Afiliation, Start date and End date.

I have created a content type named "Visitors" which contains title (i.e Visitor name), Affiliation (Text field), Start and end date (Date field)

How can I migrate my sql records from tables to populate this content. Please share the online resource link and other material which can help me to achieve this objective.

I am using Drupal 7.

Thank you for your help

You can achieve it using the Feeds module.

  Import or aggregate data as nodes, users, taxonomy terms or simple database records.
  Import or aggregate CSV files
  Create nodes, users, taxonomy terms or simple database records from import
  Extensible to import any other kind of content
  Granular mapping of input elements to Drupal content elements
  Exportable configurations
  Batched import for large files

Reference

Importing data from a comma separated value (CSV) file into one multi-value field.
Importing content with the feeds module


Sorting comments from newest to oldest How should I configure Drupal 8 to sort comments from newest to oldest, similarly to what the Comment Goodness module does in Drupal 7?

As CommentStorage::loadThread adds comment_filter tag to its query, you may use hook_query_TAG_alter hook to change comments order:

/**
 * Implements hook_query_TAG_alter() for comment_filter tag.
 *
 * @see CommentStorage::loadThread().
 */
function mymodule_query_comment_filter_alter(Drupal\Core\Database\Query\AlterableInterface $query) {
  // Change comment order to DESC for 'comment' field.
  if ($query->getMetaData('field_name') == 'comment') {
    /** @var \Drupal\Core\Database\Query\SelectInterface $query */
    $order_by = &$query->getOrderBy();
    // 'c.cid' is for flat comment lists.
    if (isset($order_by['c.cid']) && $order_by['c.cid'] == 'ASC') {
      $order_by['c.cid'] = 'DESC';
    }
    // 'torder' is for threated comment lists.
    if (isset($order_by['torder']) && $order_by['torder'] == 'ASC') {
      $order_by['torder'] = 'DESC';
    }
  }
}


How to have View output is same as node output I have a content type called poem and a View page that has path like poem/% too. There is a View page for listing the poems called /poems. The poems page will list all the poem titles linked the actual poem
   (eg: "a href="poem/1">What a world ).

I have a block in the poem view to show all the poems written by the poet.
My problem here is when I go to the node by /node/1, I can see the block that list all the poems written by the poet who wrote the node/1 but when I go like /poem/1 I am not seeing the block that list the poems. The node/1 view has bold header of the title but that's missing in my /poem/1 too.

Please help me how to make poem/1 to have the same view as the /node/1.

/poems -> this will list all the poem titles in site, title link would be
/poem/1 instead of node/1

/poem/1 -> display poem content + it should display all the titles of the poem written by the author (/poem/1)

poem list view

poem view

node view of the same poem

poem view setup

but when I go like /poem/1 I am not seeing the block that list the poems. The node/1 view has bold header of the title but that's missing in my /poem/1 too.

In the Blocks Admin UI at admin/structure/blocks be sure the Block for your block view for a poem listing is enabled for the url path = poem/*.

You can also assign blocks to regions easily with the Context module.


Generate Taxonomy Terms from Node Content Automatically In Wordpress there was a plugin that could auto-create tags based on node content . I don't know how it did this but perhaps it looked up the most common words in the body content and used them as the tags. I have some posts that have lost their tags and it would be great to be able to auto generate some new ones from posts with a script rather than having to go back through and manually do them.

I haven't achieved such content based node tagging programatically on my own. But used a module named Open Calais which uses the Thomson Reuters web service to generate and classify taxonomy term from node body content. Though it was available with free key use the number of API calls were limited. This with More Like This might serve some purpose in case you are running on Drupal 6.

Another module that might be of interest is Autocategorise which appears to do the same by subjecting node content to regular expression rather than a web service API like calais. If you wish to code the logic yourself examining the module's code might give some ideas on implementation.


custom action plugin with ConfigurationForm I am trying to create a custom action with Configuration Form Field . I am able to create Action and it is being displayed on content page ( /admin/content ) , but I am not able to find the path to configure the fields in the Action Plugin.Can anyone please let me know the path to configure the Action Plugin ?
My Code as follows :
UpdateNodeTitle.php
namespace Drupal\action_plugin_examples\Plugin\Action;

use Drupal\Core\Action\ConfigurableActionBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;

/**
 * Provides a an Update node title action.
 *
 * @Action(
 *   id = "action_plugin_examples_update_node_title",
 *   label = @Translation("Update node title"),
 *   type = "node",
 *   category = @Translation("Custom")
 * )
 *
 */
class UpdateNodeTitle extends ConfigurableActionBase {

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return ['title' => ''];
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form['title'] = [
      '#title' => $this->t('New title'),
      '#type' => 'textfield',
      '#required' => TRUE,
      '#default_value' => $this->configuration['title'],
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    $this->configuration['title'] = $form_state->getValue('title');
  }

  /**
   * {@inheritdoc}
   */
  public function access($node, AccountInterface $account = NULL, $return_as_object = FALSE) {
    /** @var \Drupal\node\NodeInterface $node */
    $access = $node->access('update', $account, TRUE)
      ->andIf($node->title->access('edit', $account, TRUE));
    return $return_as_object ? $access : $access->isAllowed();
  }

  /**
   * {@inheritdoc}
   */
  public function execute($node = NULL) {
    /** @var \Drupal\node\NodeInterface $node */
    $node->setTitle($this->configuration['title'])->save();
  }

}

action_plugin_examples.schema.yml
action_plugin_examples.configuration.action_plugin_examples_update_node_title:
  type: mapping
  label: 'Configuration for "Update node title" action'
  mapping:
    title:
      type: string
      label: Title

system.action.action_plugin_examples_update_node_title.yml
langcode: en
status: true
dependencies:
  enforced:
    module:
      - action_plugin_examples
  module:
    - node
    - pathauto
id: action_plugin_examples_update_node_title
label: 'Update Node Title'
type: node
plugin: action_plugin_examples_update_node_title
configuration: {  }

I have seen a similar Action Plugin in core as well but can not find the path to configure the Plugin. AssignOwnerNode
Another Contributed module with similar functionality custom pub

You need to install the core module Actions first to be able to configure action plugins in UI.
Then you can access the actions overview page:
/admin/config/system/actions
On the top of the page your new plugin should be present in the select list for creating advanced actions. When you select the plugin you should see the configuration form of your plugin:
/admin/config/system/actions/add/action_plugin_examples_update_node_title
Since you have already provided an action configuration in a YAML file you should also see a configured instance of your plugin in the available actions list.


Show profile2 fields only to specific user register path I am interested in showing profile2 fields only to specific user register path (I have 2 user register path).
How can I do this without using the Profile2 registration path module as another module creates the paths?
thanks

You could apply that patch to profile2_regpath.module which simply show all profile fields to its registeration patch posted here


Drupal 8: SQL Insert with 10.000 datasets exceeds 300 MB PHP memory via batch_set() I have tried to use Drupal's batch_set() function to execute a SQL insert with 10.000 items. It exceeds 300 MB of PHP memory. 512 MB of PHP memory are getting the job done. This is the case, if I use the batch_set() function and if I do not. There is currently no benefit in my use-case, either I use batch_set() or I am not using it. I expect from batch_set() to keep the PHP memory consumption low.

Here is what I am doing. After an user updates the user account, I am updating all nodes for internal purpose. This service method's code is being triggered:

$batch = array(
  'title' => 'Rebuilding user permissions',
  'init_message' => 'Start rebuilding user permissions.',
  'progress_message' => 'Completed @current step of @total.',
  'error_message' => 'Rebuilding user permissions has encountered an error.',
  'operations' => array(
    array(
      [get_class($this), 'updateGrants'],
      [$grantsByNid]
    ),
  ),
);
batch_set($batch);

The $grantsByNid contains around 10.000 items. The method which is triggered via the batch, is this:

  /**
   * @param array $grantsByNid
   */
  public static function updateGrants($grantsByNid) {
    $query = \Drupal::service('database')->insert('node_access');
    $query->fields(
      ['nid', 'langcode', 'fallback', 'gid', 'realm', 'grant_view', 'grant_update', 'grant_delete']
    );
    foreach ($grantsByNid as $nid => $grants) {
      foreach ($grants as $grant) {
        $query->values([$nid, $grant->langcode, 1, $grant->gid, $grant->realm, $grant->grant_view, $grant->grant_update, $grant->grant_delete]);
      }
    }
    $query->execute();
  }

How can I prevent $query->execute(); from causing this error:

  ( ! ) Fatal error: Allowed memory size of 201326592 bytes exhausted (tried to allocate 20480 bytes) in /home/jepster/PhpstormProjects/permissions-by-term-behat/drupal/core/lib/Drupal/Core/Cache/DatabaseCacheTagsChecksum.php on line 108

I have googled a lot and I cannot find out, why Drupal 8's database functionality is using all the memory and why the batch functionality is not preventing this.

Ivan Jaros is correct, right now you just do the work twice.

You're expecting something that is not possible.

Batch saves the operations data in the database, it has to. So you save one huge array only to load it again and store it in a separate table.

A batch makes only sense if you can actually split up the processing into smaller bits and not have all the data in one large array.

Specifically for node access processing, the API for this already exists, no need to re-invent the wheel. See node_access_rebuild(), which can do this either  in the current request (not recommended for a large amount of data) or with a batch. And you can see that there is only one batch operation without data, but if you look at it, you can see it is doing a pager query to process the whole list of nodes (there are Drupal sites with millions of nodes).


how to make conditional fields work with MEDIA I installed conditional fields for drupal 8 and i made a field be invisible or visible depending on the choice of another field which is an entity reference.  but it doesn't work at all. It works for nodes , but not media.  Any idea how to make it work for media?

It was giving an error on getType when it was a media object.
I fixed it by changing line 208 in conditional_fields.module to

if (method_exists($entity, 'getType')) {
      $bundle = $entity->bundle();


Scald : How to add several medias to a node using entity metadata wrapper? I'm looking for a solution to my problem that is pretty simple in fact.
I'm on an importing task in which I have to create programmatically a node and then populate all its fields.

As we're using the Scald module, we can add several medias to a node. But I can't figure out how to associate several medias to a node ?

I tried the following :

foreach ($file_atoms as $i => $atom) {
    $node_wrapper->field_atom[$i] = $atom->sid;
}

or :

foreach ($file_atoms as $i => $atom) {
    $node_wrapper->field_atom[$i]->set($atom->sid);
}

But I get the following error :

  Error: Cannot use object of type EntityDrupalWrapper as array

I followed the doc on this page but it does not seems to work..

Can somebody help me ?

I'm encountering the same problem with taxonomies : I'm not able to set multiple values to the node wrapper.

Your issue is that your field_atom field is not configured as multiple.

When it's not, an EntityDrupalWrapper object will give you direct access to the field, instead of having to go through the 0 delta.

Just fix the field_atom options to accept multiple medias, and your code will work fine.


change Userlogin block on header to custom How can we change userlogin block on header to custom, I am using D 7.9, theme : bartik, and how can i change the below userlogin block to custom block in image2 below.
And login button should take upto example.com/user and signup button should take out to register a new account

And image1

And image2

You need just to remove the login block and create for example a new menu or use the existing service navigation where you place the links to the login form and to the reigster form. Show this menu then in the place where the login-block was. Optionaly place a link to Logout too. Drupal will recognize if the user is logged in or not.


Use Firebird Database to Lookup Data I have installed my drupal in postgres. I've been using multiple databases in my customized module. Below is my settings.php:

$databases = array (
    'default' =>
        array (
            'default' =>
                array (
                    'database' => 'drupal-7.34',
                    'username' => 'drupal-7.34',
                    'password' => 'drupal-7.34',
                    'host' => 'localhost',
                    'port' => '',
                    'driver' => 'pgsql',
                    'prefix' => '',
                ),
            'import' =>
                array (
                    'database' => 'enrollment',
                    'username' => 'postgres',
                    'password' => '',
                    'host' => 'localhost',
                    'port' => '',
                    'driver' => 'pgsql',
                    'prefix' => '',
                ),
            'import_employee' =>
                array (
                    'database' => 'csudbnew',
                    'username' => 'sysdba',
                    'password' => 'masterkey',
                    'host' => 'localhost',
                    'port' => '',
                    'driver' => 'firebird',
                    'prefix' => '',
                ),
        ),
);

Below is my code in executing the query:

 $query = db_select('EMPLOYEES', 't1',array('target' => 'import_employee'));
 $result = $query
     ->fields('t1', array('LASTNAME'))
     ->condition('t1.EMPLOYEENUMBER','1016','=')
     ->execute();

This is where I get the error.

I aready enabled extension=php_pdo_firebird.dll in my php.inifile. What should I do next? I can query in my postgres databases except in firebird. Do I have to do more configuration?

Ive been following this tutorial. I downloaded the zip file in the site and unzip it in my drupal\includes\database\firebird.

The error is in the following line:

$query = db_select('EMPLOYEES', 't1',array('target' => 'import_employee'));

It is selecting import_employee as target, and default as key, but in your settings.php file you have a default target with a import_employee key. Failing to find the definition for the target you select, Drupal fallbacks to using default as target and (without being instructed differently), to use default also as key.

You can do one of the following:

Edit your settings.php file so that it contains information about the import_employee target and its default key. Keep in mind that the information about the database is given as $database['<target>']['<key>'], not $database['<key>']['<target>'].
Change your code to always call db_set_active() before your query.


Creating a NICE collapsible menu Does anyone know how to create an expandable menu like they have on this page?

http://www.geofunders.org/events/geocc/registration

Note: scroll down to see the menu under 'Conference Policies'. First one is 'Participant Eligibility'.

It's just simple jQuery.

SEE THIS EXAMPLE I MADE FOR YOU

In Drupal to use jQuery you need to wrap it in

(function ($) {

    //code goes here

})(jQuery);

so your code should look like this

(function ($) {

    $(document).ready(function() {
         $(".button").click(function () {
             $(this).next('.content').slideToggle();
         });
    });

})(jQuery);

Remember that you need to add to your css .content { display: none; } OR you could do it with jquery

(function ($) {

    $(document).ready(function() {
       $(".content").css("display", "none");
         $(".button").click(function () {
             $(this).next('.content').slideToggle();
         });
    });

})(jQuery);

Note: this code works assuming there are no divs in between your .button and .content. If there are divs in between them, you might need to modify the slideToggle line.


module_load_include fails on WebTestCase post I am writing test cases for my website using SimpleTest module. One of my test cases uses the following sequence

    $this->drupalGet( "myurl" array('query' => $params));
    $this->assertFieldByName('giftaid_granted','', "Giftaid checkbox exists");

    // now we will also attempt to submit a form and check that it goes out
    $this->drupalPost(NULL, array(), t('Submit'));

When I run this code, I get an exception in the test

Fatal error: Call to undefined function module_load_include() in ...sites/all/modules/mymodule/includes/entities.inc on line 3

1   0.0001  235336  {main}( )   ../index.php:0
2   0.0023  660936  drupal_bootstrap( ) ../index.php:20
3   0.0025  678144  _drupal_bootstrap_page_cache( ) ../bootstrap.inc:2236
4   0.0029  757040  drupal_bootstrap( ) ../bootstrap.inc:2378
5   0.0044  1174072 _drupal_bootstrap_variables( )  ../bootstrap.inc:2244
6   0.0046  1199928 variable_initialize( )  ../bootstrap.inc:2480
7   0.0102  1626520 array_map ( )   ../bootstrap.inc:935
8   0.0102  1631120 unserialize ( ) ../bootstrap.inc:935
9   0.0102  1652040 spl_autoload_call ( )   ../bootstrap.inc:0
10  0.0102  1652112 drupal_autoload_class( )    ../bootstrap.inc:0
11  0.0102  1652376 _registry_check_code( ) ../bootstrap.inc:3107
12  0.0143  2484552 require_once( '...sites/all/modules/mymodule/includes/entities.inc' )   ../bootstrap.inc:3186

The offending line is apparently the module_load_include('inc', 'mymodule', 'includes/shared'); on top of my entities.inc file.

As best I can guess from the trace, there is some sort of cached variable causing class autoloading in bootstrap, before module_load_include function is defined. But form submission on a normal page works just fine.

Am I using module_load_include incorrectly? Or is it some problem with the SimpleTest?

I figured it out for myself. This is an issue with SimpleTest. DrupalWebTestCase stores emails sent in the database, in a varialbe drupal_test_email_collector. If an email sent during a test case includes parameters, the parameters are saved. My parameters were classes. bootstrap.inc attempts to load and cache variables before modules are loaded. In restoring the emails with parameters, it was attempting to autoload the relevant class, and that was causing the crash.

This could happen, in principle, in other situations - any time a class got saved to a variable, though I have only encountered it with this test setup.


file_create_url() equivalent in a javascript file? I am dynamically loading a script using $.getScript() which works fine, but when using the CDN module it comes from the webserver, instead of the CDN. Is there a way to get the correct CDN path in JS, similar to how file_create_url() works?

CDN has already done its magic by the time the JavaScript file has been prepared for output, and there are no AJAX callbacks allowing it to do its magic from the JS file itself.

If you do know ahead the name of the scripts you might load (or you can iterate from your theme or module) then the trick is to inject those paths as variables directly in your theme using inline JavaScript. For example, from your module or your theme's hook_html_head_alter method in template.php, to add one file (the method would be the same for a list of files, but an array would best be used):

drupal_add_js('var my_js_file_1 = "' . file_create_url(drupal_get_path('theme', 'my_theme') . '/js/file_1.js') . '";' , 'inline');

then you can call

$.getScript(my_js_file_1);

in your code.

The magic is done through the file_create_url, which is what the CDN module processes.


Using AJAX to access the content of a view I have a simple view with one exposed filter that displays a table view of contents.(for example nodes are some addresses with the exposed filter of the city). And I made a map for cities;I want that whenever user clicks on a city in the map, the selected city become exposed filter of view and view become refreshed without refreshing the whole page.is it possible?
I thought that I can use something like:

$.get(
'/myviewpage',
{myfield=14},
function(data){  $('#SomeOtherDiv').html(data) }
);

I tried that but I got unauthorized error. if it's correct; how can I make a page view-able for everyone?
thanks

First, enable Ajax on the view. On window load, bind the click event to a custom function, let's call it getInfo(arg) and pass the arguments you need (nid, tid, or whatever you need)

Then, on getInfo() add the following code.

function getInfo(args) {
  $.ajax({
    url: '/views/ajax',
    type: 'post',
    data: {
      view_name: 'your_view_name',
      view_display_id: 'block_1', //your display id
      view_args: args,
    },
    dataType: 'json',
    success: function (response) {
      if (response[1] !== undefined) {
        var viewHtml = response[1].data;
        $('#myDiv').html(viewHtml);
        Drupal.attachBehaviors(); //check if you need this.
      }
    }
  });
}

You pass the arguments in the data array, and you get the #myDiv replaced with the view content.


Comment replies to be another comment type I need the comment replies to be another comment type. So, the normal comments should be of type "Standard". The answers to these standard comments should be of the type "Special", with more fields.

How do I achieve this?

You don't need to use two different comments you can use only one and hide the "special" fields if the comment is not a reply comment.


Create custom action for Views Bulk Operations I'm trying to add some custom actions to my Views Bulk Operations, but for some reason, they don't appear in the list.
i want to add custom button to user can apply it and node DATE update to today...

This is my code (so I guess this is a working code...)

    /**
 * Implements hook_action_info().
 */
function custom_action_info() {
  return array(
    'custom_action_callback_name' => array(
      'type' => 'entity', // Can be file, term, user, etc.
      'label' => t('Your label'),
      'configurable' => FALSE, // Doesn't need config form
      'behavior' => array('view_property'), // Uses view access rights
      'triggers' => array('any'), // Works always
    ),
  );
}
/**
 * Add action callback where you perform the action.
 */
function custom_action_callback_name($entity, $context) {

  // I DONT KNOW .....................

}

I believe your type should not be entity but the actual entity type you want to use, like node. Then it should show up on nodes.

Also VBO requires no triggers to be defined, unless you want the action to be triggered via the action module as well. For just VBO this can be an empty array.
I have no idea what behavior is, never used it.

See an example of VBO with a form here: Add multiple friends at once with user relationships


How can I add a CC field to webform email send? Does anyone have a solution to adding a CC field to the /node/[nid]/webform/emails/xxx interface?

I have a client that wants to use a decently complex conditional email send solution in Drupal 7 webform, where based on various select lists, it will send an email to two places.

"Real_Person@domain.com"
"Ticket_System@domain.com"

Allowing a real person to be notified and respond via REPLY-ALL to the email, and having the ticket system be updated with the communication in real time.

The ticket system can't handle getting a reply-to with both addresses in the single "TO:" line.

to: Real_Person@domain.com,Ticket_System@domain.com breaks the system.

Has anyone solved this? built a module?  Have guidance on how to solve?

Thank you!

I have done some similar thing to send the email to another email-address. You can use the following solution for changing the content of the email or to add an attachment or things like this...

/**
 * Implements hook_mail_alter().
 */
function MYMODULE_mail_alter(&$message) {
  // Check message id
  if ($message['id'] == '...') {
    $email_key = 'new_email_key_if_you_want';

    // Block email which is sending right now.
    $message['send'] = FALSE;

    // send original email
    drupal_mail('MYMODULE', $email_key, $message['to'], language_default(), $message['params'], $message['from']);

    // send copy of the email.
    drupal_mail('MYMODULE', $email_key, 'ticket_system@domain.com', language_default(), $message['params'], $message['from']);
  }
}

You can add this in an own module, in the MYMODULE.module.


Field inheritance (Drupal 7) I would like to make a field that is very similar to the group audience field but only displays certain types of groups.

As an experiment I hacked up:

og_field_audience_options

and I was able to remove the groups I didn't want but obviously this is not where this code belong.

Is there a way that I can create a new field that inherits most of the behavior of the group audience field and but has a slightly different way of picking which groups to display?  Or do I need to recreate the whole field from scratch?

Strictly speaking, fields can't "inherit", no, but you can almost do it anyway.

Drupal 7 comes with a generic "File" field, and a more specific "Image" field. Technically, one could say that Image inherits from File, but the way it's done is simply that for a lot of it's hook implementations, it just calls back to file.

Example code:

/**
 * Implements hook_field_load().
 */
function image_field_load($entity_type, $entities, $field, $instances, $langcode, &$items, $age) {
  file_field_load($entity_type, $entities, $field, $instances, $langcode, $items, $age);
}

As far as I know, this is as close as you can get.


Client-Side form validation issue with Fivestar module? I've set up my review system of my Drupal 7.x site some what like mentioned in this http://drupal.org/node/1308114 and I've also set that field as "Required" but it seems that "Required Field" is not working since, its allowing user to submit the review without rating the article, for that I've created my custom module containing

<?php
/**
 * Implementation of hook_form_alter()
 */
function rishihrvalidate_form_alter(&$form, $form_state, $form_id) {
    $form['#attributes']['onsubmit'] = 'return comment_cs_validate()';
    if ($form_id == 'comment-form'){
  }
}

calling the JavaScript

<script type="text/javascript">
      function comment_cs_validate() {
        if ($('#edit-field-review-value div div').hasClass("on") && $('#edit-field-review-atmosphere div div').hasClass("on") && $('#edit-field-review-service div div').hasClass("on")) {
          return true;
        }
        else {
          alert ('You must rate the listing before submitting your review');
          return false;
        }
      }
    </script>

Though the above PHP code was not perfect, it was executing correctly and behaving as desired only the problem I'm getting is while logging on my site also its taking place since I've called all the submit buttons, hence I changed the from that above one to this, but now I'm getting nothing, may I know where I might be lacking?

<?php
/**
 * Implementation of hook_form_alter()
 */
function rishihrvalidate_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'comment_form') {
        $form['#attributes']['onsubmit'] = 'return comment_cs_validate()';
    }
}

I'm not getting where is the mistake, can someone help me in this issue?

Thanks in Advance :)

Perhaps you are using the wrong $form_id

One way to check is to use Database Logging, also known as the Watchdog or Recent Log Entries, to log the $form_id. After you add this code, execute the form by performing a submit, and then check your Reports > Recent Log Entries area for the result. This may require enabling the Database Logging core module before the messages are logged and/or visible.

<?php
/**
 * Implementation of hook_form_alter()
 */
function rishihrvalidate_form_alter(&$form, &$form_state, $form_id) {
  // Log the $form_id to the watchdog
  // in this example, 'form_id' is just the log entry name. I commonly use 'wtf'
  watchdog('form_id', $form_id);

  if ($form_id == 'comment_form') {
    $form['#attributes']['onsubmit'] = 'return comment_cs_validate()';
  }
}
?>

For more information about watchdog, visit http://api.drupal.org/api/function/watchdog


How to enable menu link when creating a new node? I try to enable the menu link programmatically, here is how I do it:

function create_menu_link() {
    $node = new stdClass();
    $node->type = 'mytype';
    node_object_prepare($node);

    $node->menu['link-title'] = $menu_title;

    node_save($node);
}

But setting only the title is not working. In $node->menu there is some other variables like mlid and plid which are set to 0 it has to do with this ? The menu_name is set to main-menu:0, module is set to menu.

You'll need to create the menu item separately, using menu_link_save

$item = array(
  'menu_name' => 'main-menu',
  'link_title' => $node->title,
  'link_path' => 'node/'. $node->nid,
);
menu_link_save($item);


An illegal choice has been detected when I submit my webform module I am getting this error

  An illegal choice has been detected

when I am submitting my webform and that is happening only on the select fields , as i read on the internet it suppose to have default value but i don't know how to put it in the code I am editing my webform-form-16.tpl and I have the code like this.

$form['submitted']['material']['#title']='';
$form['submitted']['material']['#prefix']='
Material:
&nbsp;';
$form['submitted']['material']['#options'] = array('Steel'=>'Steel','Yellow Gold'=>'Yellow Gold','White Gold'=>'White Gold','Steel and Yellow Gold'=>'Steel and Yellow Gold');
$form['submitted']['material']['#suffix']='
';

Editing webform-form-**.tpl or any template file is designed to alter the theme or display of the webform. It seems you are having issue with the forms content, specifically default values.

If you are using the Form API to create your form in your own module, you will need to declare it as described in the FAPI documentation.

<?php
  $form['selected'] = array(
    '#type' => 'select',
    '#title' => t('Selected'),
    '#options' => array(
      0 => t('No'),
      1 => t('Yes'),
    ),
    '#default_value' => $category['selected'],
    '#description' => t('Set this to Yes if you would like this category to be selected by default.'),
  );
?>

The error that you are getting tends to occur when form elements are submitted that were not defined in the original form. And by the look of your template edit, that could easily be the case.

Check out your log at Administer > Logs > Recent log entries to see what is causing the error.

To get an empty entry submitted from the select options force the 'empty option' form declaration. Works like a treat.

'#empty_option'=>t('- Select -'),

Good luck.
xK