Add multiple friends at once with user relationships I am using the  User Relationships module and I created a table in Views with all of the site users.

There is a field where you can add or remove a friend. But (especially the first time) the users must be able to add multiple friends add once.
For example with check boxes and a "send friend request" on the bottom of the page.

I have tried to accomplish that with Views Bulk Operations but there is not a integration with that module.
What can I do?

Write your own integration!

Really, Views Bulk Operations is quite an easy module to write a plugin for and optionally you can submit it to the User Relationship project to have it maybe embedded in the main project. There is a complete tutorial here, but I will briefly explain each step of the process.

First off, you need to create a custom module. Create a folder with a fitting name for your module, like user_relationships_vbo or something. Add a user_relationships_vbo.info (writing .info files) and a .module file.
The module file should contain several specific functions to have it work with VBO.

The action

Implementation of hook_action_info(), this defines the action. On what entities it can act, what the action is called, how it can be configured and if it has an extra VBO configuration option.

The VBO configuration form

This is an optional form that adds settings the the Views VBO config form, allowing you to define additional settings. In your case this is not really important as you probably just want to relate users.

The bulk configuration form

This forms shows after your chose your action in VBO, and can be used to define settings for the current batch. You could for instance use this the choose to have the requester specify the relationship type. Again in the simplest form you would not need this.

The actual action

This is what will eventually relate the users. You can make this as long and as complicated as you like with all kind of notifications, etc. But the basics is to just add the relation.

So the code

Your .module file might look like this:

<?php
// The action definition
function user_relationships_vbo_action_info() {
  return array(
    'user_relationships_vbo_relate_users' => array(
      'type' => 'user',
      'label' => t('Relate users to the current user'),
      'configurable' => FALSE,
      'vbo_configurable' => TRUE,
      'triggers' => array(),
    ),
  );
}

//The per batch form
function user_relationships_vbo_relate_users_form($settings, &$form_state) {
  $form = array();
  $form['type'] = array(
    '#type' => 'select',
    '#title' => t('Choose your relation type'),
    // This assumes all users have access to all relationships. You might want to add a filter to check access somehow.
    '#options' => user_relationships_types_load(),
    '#required' => TRUE,
    '#default_value' => isset($settings['settings']['type']) ? $settings['settings']['type'] : '',
  );
  return $form;
}

// The form submission
function user_relationships_vbo_relate_users_submit($form, $form_state) {
  $return = array();
  $return['type'] = $form_state['values']['type'];
  return $return; //Note, return value here must be an array.
}

// The actual action
function user_relationships_vbo_relate_users(&$target_user, $context) {
  // Get the current user
  global $user;

  // See user_relationships_request_relationship()
  // http://api.drupalhelp.net/api/user_relationships/user_relationships.module/function/user_relationships_request_relationship/7

  user_relationships_request_relationship($user->uid, $target_user->uid, $context['type'], FALSE)

}
?>

Read the rest of the tutorial, but this should get you started.


Why could Drush not find the alias @local? I am usin Drupal 8 and Drush 8. I have ~/.drush/local.aliases.drushrc.php. That is the only alias under ~/.drush

Inside local.aliases.drushrc.php, I have

$aliases['local'] = array(
  'root' => '/var/www/html/test/testme/amber/amber_school_dev',
  'uri' => 'http://amber_school_dev.local',
);

Run this drush @local status --debug

Using the Drush script found at /home/kenpeter/.composer/vendor/drush/drush/drush.launcher using pcntl_exec
Cache HIT cid: 8.1.8-commandfiles-0-88373346a2ca94c0c49a48b75b15bd40 [0.02 sec, 3.23 MB]                                                [debug]
$aliases['local'] = array(
  'root' => '/var/www/html/test/testme/amber/amber_school_dev',
  'uri' => 'http://amber_school_dev.local',
);

$aliases['local'] = array(
  'root' => '/var/www/html/test/testme/amber/amber_school_dev',
  'uri' => 'http://amber_school_dev.local',
);

$aliases['local'] = array(
  'root' => '/var/www/html/test/testme/amber/amber_school_dev',
  'uri' => 'http://amber_school_dev.local',
);

Could not find the alias @local [0.06 sec, 6.05 MB]                                                                                [error]
Undefined index: command notify.drush.inc:60 [0.06 sec, 6.06 MB]                                                                       [notice]
Undefined index: command notify.drush.inc:60 [0.06 sec, 6.06 MB]                                                                       [notice]

drush sa in site root gives me

@none
@self
default

You are missing the <?php at the beginning of your aliases file. That's why the contents of your file are printing out when Drush tries to load them.


how to get month and year value I am using following code to build the select box for Month and year

$form['billing']['expiry_db'] = array(
    '#type' => 'date_select',
    '#title' => t('Expiry Date'),
    '#default_value' => date('m Y'),
    '#date_format' => 'm Y',
    '#date_label_position' => 'within',
    '#date_year_range' => '0:+20',
    '#required' => TRUE,
    '#prefix' => '<div class="field-wrapper-w1">'
);

I am passing following value in database

$form_state['values']['billing']['expiry_db']['month']

and

$form_state['values']['billing']['expiry_db']['year']

but it is only showing value '2' for month and value '2' for year. However I am selecting month 'December' which has value '12' in HTML. Please help

The value for #default_value must have the date() format "Y-m-d H:i:s"; the value returned in $form_state is a string.

In your case, the code you should use is the following one.

  $form['billing']['expiry_db'] = array(
    '#type' => 'date_select',
    '#title' => t('Expiry Date'),
    '#default_value' => date('Y-m-d H:i:s'),
    '#date_format' => 'm Y',
    '#date_label_position' => 'within',
    '#date_year_range' => '0:+20',
    '#required' => TRUE,
    '#prefix' => '<div class="field-wrapper-w1">',
  );

If the form has #tree set to TRUE, then $form_state['values']['billing']['expiry_db'] a string such as '2020-05' for May, 2020.

As far as I can see, the value of #date_format is only used to understand which components of a date must be returned, but the format of the returned value is always the same. Changing #date_format to 'Y-H:s' the returned value is '2020 00:00'. In you case, the code to get the month, and the year is the following one.

list($year, $month) = explode('-', $form_state['values']['billing']['expiry_db']);

References

_date_api_element_info()


How to set Panel to homepage when setting the panel's path as homepage on Configuration > Site Information doesn't work? I have created a panel for my home page and set its path to /home. I have changed the directory of the front page in Admin > Configuration > Site Information to mysite.com/home. Still, when I visit mysite.com/home, the custom panel saved to path /home doesn't populate.

I've made sure I'm saving correctly (rather than just updating) and have also cleared my cache.

Any ideas how else I might be able to fix?

Thanks in advance!

I dont know what programes interferring the home page redirect.
However, you can try variable_set('site_frontpage', 'front-page-panel-url');

http://api.drupal.org/api/drupal/includes--bootstrap.inc/function/variable_set


how to import term by name in csv file in drupal 7? I need to import a CSV with 3-4 fields with taxonomy, but I need to insert taxonomy by name. Is it possible with the feeds module?

Try Views data export

This module is designed to provide a way to export large amounts of
data from views. It provides a display plugin that can rendered
progressively in a batch. Style plugins are included that support
exporting in the following types:
CSV
Microsoft XLS
Microsoft DOC
Basic TXT
XML.

Requirements
The batched export functionality of this module requires a MySQL database.
This module also requires version 2.7 or higher of views.


How do I render a table with a checkbox on each row? In Drupal 7, I could achieve this using the following code.

$form['table'] = array(
  '#type' => 'tableselect',
  '#header' => $header,
  '#options' => $options,
  '#empty' => t('No data')
);

This doesn't work anymore in Drupal 8. I just want a page similar to the one at /admin/people. What's the correct way in Drupal 8?

The form element type "tableselect" is available in Drupal 8

  Description: A table created with a far left column of radios or
  checkboxes. Build the table headings and columns with the #headers
  property, and the rows with the #options property.

https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/8#tableselect

More info on "Adding checkboxes to a table" can be found in the handbook documentation here: https://www.drupal.org/node/945102


What all contributes to drupal page execution time? I have a site I am investigating that has major performance issues, using memcache I was able to bring number of queries down both in number and total exectution time ( from 3 secs to 230 ms) but the page execution time is eluding me ( I am looking at values outputted by devel) my understanding is that page execution time = time taken for php to execute therefore I installed APC and I can see php opcode being cached and stats showing hits in APC control panel ( apc.php shipped with APC ) but my page execution time does not go down. So I think my question is two-fold:

What all contributes to ( better slows down) page execution time? Is it just time taken to execute php?
What approaches should I take to bring down page execution time. I tried APC but not much help

P.S number of modules used on this site is just enormous ( 168 ) but right now I am not in a position to make that recommendation, its more like a fire in the hole situation.

Edit: Output of running xhprof on local instance (recommended by mikeytown), this seems to be crazy I think the later results are due to thrashing? diff runs for the same url have drastic difference and its just too much resource usage. Also not sure why is it showing values which are not from today :| (I just installed xhprof on this laptop)

Get a cachegrind of your site. xdebug or xhprof can generate one. This will tell you what functions are taking the longest to run. Until you do this, its a bad guessing game.


How to detect insertion of new item(s) into Drupal's queue? I need to trigger some code when new items are added to Drupal's queue system. My question, how to do that? How to capture that event?

Further details

I have created a custom views bulk operation which enqueues items into Drupal's queue system for further processing. Usually, the enqueued jobs would run when Cron runs. I need to execute a function when new items are added to the queue by VBO. I could query the database every minute to check for new items, but I hope it is possible to listen to that insertion event using a rule or a hook.

There is another question here with some equal requirement: Insert task to Queue only if unique

The idea is to create a custom queue class extending the original one. Your custom class only overrides the createItem method. Just copy the original one and add your custom functionality.

After that you need to let Drupal know about your new queue class.

The downside is that it would override the class of your queue for every operation on it.


Setting a date field via entitity_metadata_wrapper I am trying to set a field of date type through usage of entity_metadata_wrapper but the although the field is created as datetime in mysql, and creating a node sets it with expected YYY-MM-DD HH:MM:SS format, when using entity_metadata_wrapper it fails.  The only thing I have managed to insert is timestamps, I have tried both Iso date format and the standard one.

Here is the line I am trying to use to update:

   // sets reminder date in db
   $wrapper->field_event_reminder_date->set($reminder_date->format("Y-m-d H:i:s"));

Thanks!

I was able to get this to work in a roundabout way. I may have been able to accomplish the same thing with time(), but this read better for me as I could follow exactly what I was doing if I ever came back to the code in the future.

// Update the Acceptance Date of Current Agreement.
$acceptance_date = new DateTime(date('Y-m-d 00:00:00'));
$company_wrapper->field_acceptance_date->set($acceptance_date->getTimestamp());


Field API, Field Attach API, Field Instance API, Field CRUD API OR Schema API? I'm in my final semester for my degree in Computer Science, and we've been tasked with creating a project management system using Drupal. I thought this was great at first, we easily created a proof of concept using already built modules. And then I attempted to code.

Basic Idea:
We thought about defining our own schema for entities, but the company needs a dynamic way of defining and sharing fields (like the entity / field API already does), so we decided to stick with the built in Entity / Field API.

Entity types would be things like request, project, task, etc...

Fields would be things like select lists, questions for the request form (that could be transferred over to a project once the request was approved), and other text fields needed for the project.

I was thinking that using the field API to start with some of the needed select lists (that the admin can add/update/delete default values to) would work fine - because I defined these with the UI thinking man this is easy. Select lists such as legacy company, products, and other short lists related to telecom. But I cannot programmatically define a select list field with predefined values. How can I do this? I've googled, and searched, and followed this great article, but it does not delve much into select lists, and how to define default values, or any of the $options available for a select list [and neither do the API docs, they do not tell what values should be used, or even the default widget types].

Am I going about this all wrong? Maybe I should just create some good old crud classes and be done with it. The only problem with this is that it would be extremely difficult to make the system as dynamic as they want, or would it?

Personally I wouldn't bother doing it yourself, Drupal has it all set up for you and it's just a matter of working out the format it wants data in and you can use all the goodness of the entity/field system.

The following function is one I use all the time. Given an existing entity type, field name and bundle it will produce the code you need to run to create said field instance:

function __export_field($entity_type, $field_name, $bundle_name) {
  $info_config = field_info_field($field_name);
  $info_instance = field_info_instance($entity_type, $field_name, $bundle_name);
  unset($info_config['id']);
  unset($info_instance['id'], $info_instance['field_id']);
  include_once DRUPAL_ROOT . '/includes/utility.inc';
  $output = "field_create_field(" . drupal_var_export($info_config) . ");\n";
  $output .= "field_create_instance(" . drupal_var_export($info_instance) . ");";
  drupal_set_message("<textarea rows=30 style=\"width: 100%;\">". $output .'</textarea>');
}

For example, if you have a field called field_image attached to the standard article content type, you would export both the field creation code, and field instance creation code with this:

__export_field('node', 'field_image', 'article');

The code prints out to the standard drupal message area and can just be copied and pasted to wherever you need it.

For your specific needs, the value list for a select widget is added in the settings part of the field array, under allowed_values:

$field = array(
  'translatable' => '0',
  'entity_types' => array(),
  'settings' => array(
    'allowed_values' => array(
      1 => 'First Choice',
      2 => 'Second Choice'
    )
  ),
  // etc...
);

If you haven't seen it already check out the Examples module, there's loads of example code in there to help with entity/field manipulation.


"Filename cannot be empty in file_unmanaged_save_data()" We're using Drupal 7.20 and this error message started appearing after trying to add a new context. I removed the context condition, and even restored drush arr from a dump from Friday. All files belong to apache (chown -R apache:apache) and group/owner can do everything (chmod -R 775 * #temporarily).

The message still persists.

  Warning: file_put_contents(): Filename cannot be empty in file_unmanaged_save_data() (line 1903 of /var/www/html/includes/file.inc).
  The file could not be created.
  Warning: file_put_contents(): Filename cannot be empty in file_unmanaged_save_data() (line 1903 of /var/www/html/includes/file.inc).
  The file could not be created.
  Warning: file_put_contents(): Filename cannot be empty in file_unmanaged_save_data() (line 1903 of /var/www/html/includes/file.inc).
  The file could not be created.
  Warning: file_put_contents(): Filename cannot be empty in file_unmanaged_save_data() (line 1903 of /var/www/html/includes/file.inc).
  The file could not be created.
  Warning: file_put_contents(): Filename cannot be empty in file_unmanaged_save_data() (line 1903 of /var/www/html/includes/file.inc).
  The file could not be created.
  Warning: file_put_contents(): Filename cannot be empty in file_unmanaged_save_data() (line 1903 of /var/www/html/includes/file.inc).
  The file could not be created.

Oy! My temp folder had bad permissions.

Of course I only thought of this after I restored a back up from last Friday -- thus, overwriting all the work from this morning and Friday evening. Arg. Okay, Thanks for letting me vent here.


Add type='tel' attribute to webform field I want to add the html5 tel attribute to a particular field in my webform form in order to prompt mobile devices to display the appropriate keyboard.

I was trying this:

function my_module_form_alter(&$form, $form_state, $form_id) {

    /* add html5 phone type for phones and smarter devices to use */
    /* usage: just include the word 'phone' in the field title and have the field of type 'textfield' */

    foreach ($form['submitted'] as &$field){
        if (is_array($field) && isset($field['#title']) && stristr(strtolower($field['#title']), 'phone') && isset($field['#type']) && ($field['#type'] == 'textfield')){
            $field['#attributes']['type'] = 'tel';
        }
    }
}

but the attribute doesn't get applied and the resulting field has the type of "text"

I suspect there may be a hook for webforms that will let me adjust the output, I just can't find it.

Drupal 7 core field doesn't support HTML 5 form elements.

You should try the Elements module to do that.

  This module intends to become a repository for advanced form elements. Supports HTML 5 standards like: (url, email, search, tel, number, range)


hook_block_view called multiple times per request I am creating a module for Drupal 7 that implements the hook_block_view. I make a call to watchdog in the hook method and I noticed (while debugging) that the the watchdog method is firing three times per page refresh. Is this normal, or is it something I should be worried about. Since each call to the method makes a database query it seems that this could result in a performance hit.

It gets called everytime the block is rendered.  Truthfully, that is a bit wasteful since the params it is passed are the same.  Still, in the normal block system, each block only loads once (i.e. it can only be in one region).  This makes the logic forgivable, but yeah, it should be cached.  You can of course cache it yourself in your hook_block_view implementation.

Disclaimer: I am drunk.


Add Expression for Entity Query I've been working with the entityQuery to query the db and get an array of filtered nids however I need to add an expression to my query.

I've checked the Query class and found a protected sqlQuery attribute that has access to addExpression(). In my case I'm not extending the class but rather instantiating it through \Drupal::entityQuery('node').

Also after checking a bit I found that the Select class has a function addExpression() that does exactly what I need, but then I lose the entityQuery and has to addJoin/addField and so on for each of the fields I would like to include in my conditions.

My objective:

$expression = "
    (
        6371000
        * acos(
            cos( radians({$latitude}) )
            * cos( radians( {$latitudeField} ) )
            * cos(
                radians( {$longitudeField} )
                - radians({$longitude})
            )
            + sin( radians({$latitude}) )
            * sin( radians( {$latitudeField} ) )
        )
    )";
$query = \Drupal::entityQuery('node')
->condition('status', 1)
->condition(`field_city`,1,'=')
->addExpression($expression, 'distance');

$nids = $query->execute();

Did I miss something ? Is there any other way to achieve what I want ?

EDIT: I found this approach but doesn't seem straight forward

EDIT2: Better approach is this

I am not sure if following is what you're looking for, it helped me when I was doing something similar
$sql_snippet = <<<EOF

ROUND(
CASE $this->tableAlias.$unit_column
WHEN 'kg' THEN $this->tableAlias.$this->realField * :kg_coefficient
WHEN 'lb' THEN $this->tableAlias.$this->realField * :lb_coefficient
END
, :precision) = :value
EOF;
// The difference in this invocation of ::addWhereExpression() compared to
// the invocation in the filter handler is that here part of the DB
// placeholders come from $this->options (such as precision) and others come
// from the actual argument we have received, i.e. derived from
// $this->argument.
$this->query->addWhereExpression(0, $sql_snippet, [
  ':value' => round($arg['value'], $this->options['precision']),
  ':kg_coefficient' => $kg_coefficient,
  ':lb_coefficient' => $lb_coefficient,
  ':precision' => $this->options['precision'],
]);

}
Lifted from Here


List of certain user flagged nodes in a view I'm using Drupal 6.28 latest views and flag modules (for drupal 6 ofc). I have a node content type "group" which can be flagged. So I'm user with id2 I'll go on node/10 and flag it, then I'll go on node/11 also flag it. Now I want to display all flagged nodes by me on my user page /users/myname.

What I did so far:

1 Created a node view
2 Set up a relationship Flags: User's flagged content, checked Include only users who have flagged content. then chosen my created flag. (for content type "group")
3 added argument Flags: user uid
4 added field "title"

I have 2 flagged nodes but it shows nothing.. What I am doing wrong?

1) Create a Node View

2) Add a relationship Flags: Node flag (select the required flags and tick "Include only tagged Nodes"

3) Add another Relationship Flags : User (use the above relationship on this)

4) Add Argument User ID (named Contextual Filters in Drupal 7) and use the relationship "Flags : User"

5) Add the required fields.


add new format to description fiield of taxonomy display modes when you go to structure -> taxonomy -> VOCABULARY_NAME -> manage display
you will find the description field with no label, and with two available format : hidden and visible.

I want to add new format to this field (exactly I want add the "trimmed" format) like existing in manage display of nodes...

I used the custom_formatter module, but it didn't do the trick, because the description field is of type "Term description textarea", and custom_formatter use text, text_long... types.
I used some hooks to change how this field is displayed but no luck

any help will be appreciated
thanks in advance.

This is because the description field isn't a 'field'.
It's a term property like 'title' in node content type.
You should add your own 'description' field and you should be able to use custom_formatter module to add your format 'trimmed'.
===========================================================
Edit : Update your taxonomy term
This solution use the "View Bulk Operation" module for updating your terms.
[!]First of all, make a backup of your database !!! and put your website in maintenance [!]
After module installation, create a new View based on taxonomy term
Your results need to correspond at all terms you need to update.
Create a VBO field like the following screen :

Save your View and display it on your web site.
Go to the page where this View should appear and select all terms
In php script textarea enter this :
// Load a wrapper for the current term, access to value are easy now
$wTerm = entity_metadata_wrapper('taxonomy_term', $entity);
// Update your custom field (In example : field_mydescription) with description field
// use the format of description to keep same values (In example : filtred_html)
$wTerm->field_mydescription = array(
    'value'     => $wTerm->description->value(),
    'format'    => 'filtred_html'
);
// Save your modifications
$wTerm->save();

All your term should be updated.
Careful, if you have too many terms to update, this operation should run in background via
batch API.
Delete everything we have created for the update, put in offline minimum.
That's done !
You can achieve that operation in many different ways, this is quick fix.


How to append options and classes into a custom attribute in Twig? In our twig template we have a need to wrap certain fields with a Link field. In the existing twig template there already exist an attributes variable (accessed by adding attributes), but we have a need to have a custom one. Couldn't find any documentation on if you can pass options and attributes from one field to a custom twig attribute.

Is there a way to append all options and classes from a field's attributes into a custom attribute in a Twig template without any hook_preproceess_hook?

Existing node--article.html.twig

{{ content.body }}

{{ content.field_subtitle }}

{{ content.field_category }}

  {{ content.field_link }} /* has its own options and attributes */

Desired output

/* pass the options and attributes from field_link into the a_attr */
/* This did not result in what we wanted */
{% set a_attr = create_attribute(content.field_link.0['#attributes']) %}

{{ content.body }}

{{ content.field_subtitle }}

{{ content.field_category }}

 {{ content.field_link.0['#title'] }}

According to the syntax your declaration is a little off. The function is also create_attribute, not create_attributes.

The {{ attributes }} variable in a node twig template won't hold what you think it holds for the link tag. So, you will need to create a new one.

https://www.drupal.org/docs/8/theming-drupal-8/using-attributes-in-templates

You probably want something like this:

{% set link_attributes = create_attribute() %}
{% set link_href = content.field_link.0['#url'] %}
{% set link_title = content.field_link.0['#title'] %}

{{ content.body }}

{{ content.field_subtitle }}

{{ content.field_category }}

 {{ content.field_link.0['#title'] }}

Unfortunately, since you are wrapping fields with the value of a link field, this might be more manual than you would prefer. This is because Drupal is not rendering the field, you are creating html on the fly - link fields in particular are tricky because there is often the case of wrapping data with an anchor in say, a card display format or a clickable CTA. I am not sure if anyone has found better methods of achieving this.

I wonder if anyone has written an extension that will in fact let you render a link field but intake other fields in a tag like you mentioned in another question, so you could wrap them.


How do I add JavaScript to the administrative area? I'd like to add some Javascript into Drupal's admin area (content creation to be specific) and was wondering what's the best approach to do it: I'm using the admin theme Rubik. Shall I just add the JS as part of the Rubik theme? Should I create a sub-theme? But its just one file...

@kiamlaluno explain answer very good way

Using a module, you can follow two methods:

Implementing hook_init()
Implementing hook_form_alter()
The first method would allow you to add the extra JavaScript (or CSS) files to any administration pages, while the second method would allow you to add those files only to pages containing forms.

function mymodule_init() {
  if (arg(0) == 'admin') {
    $path = drupal_get_path('module', 'mymodule');
    drupal_add_js($path . '/mymodule.js');
    drupal_add_css($path . '/mymodule.css');
  }
}

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if (arg(0) == 'admin') {
    $path = drupal_get_path('module', 'mymodule');
    $form['#attached']['css'][] = $path . '/mymodule.css';
    $form['#attached']['js'][] = $path . '/mymodule.js';
  }
}

Replace "mymodule" with the short name of your module; replace "mymodule.js" and "mymodule.css" with the actual names of the JavaScript and CSS files.

more detials


Installed Boost module. How do you tell it is working on your site? I just installed the Boost module on Drupal 7 and activated everything properly. How do I even tell if its working properly?

View the source code of the page as you're browsing as an anonymous user. Boost inserts some metadata about the cached page ("Page cached by...") as an HTML comment:

  // Add note to bottom of content if possible.
  if ($_boost['matched_header_info']['comment_start'] && $_boost['matched_header_info']['comment_end']) {
    $expire = $_boost['matched_header_info']['lifetime_max'];
    $cached_at = date('Y-m-d H:i:s', REQUEST_TIME);
    $expires_at = date('Y-m-d H:i:s', REQUEST_TIME + $expire);
    $note = "\n" . $_boost['matched_header_info']['comment_start'] . 'Page cached by Boost @ ' . $cached_at . ', expires @ ' . $expires_at . ', lifetime ' . format_interval($expire) . $_boost['matched_header_info']['comment_end'];
    $data .= $note;
  }


Show block on all 404 / 403 pages only via context Without having to install even more modules on the site for context. I know there a boat load of plugins for context, but I was wondering if this can be achieved by just using core context:

I basically want to show a view block on all the 404/403 pages, which are just basic page nodes. The problem with context is when you choose path as the condition, it will only show up on that path, which is the 404/403 node paths only. Even if you put in something random like: foo.com/adsfadsf -- the context won't fire since its not a recognized path even though it is the 404 page.

What context recipe can restrict a block to show up on the error pages only? I know i can list out all the paths i dont want it to show up on, but thats not going to work in my scenario.

A better way to do this is create a panel page for 403 and 404 page. Add whatever you want to in the panes.

Set the 403 and 404 page path under :

Admin > Configuration > System > Site Information

There is a section called ERROR PAGES. Add both the path there.

Edit :

For context use Context Error module.


Request a new password mail without any content inside of the mail. I got a problem. When I want to request a new password due to password forgotten, the system definitely send a mail to my email address. But, this mail is without any content inside.
I check the Configuration->People->Accounting Settings. I already setup all the content. But, I can't get any content.
Hope someone can help me. Thanks.

admin/config/people/accounts
Check this section make sure this is not empty.


What may cause duplicate nodes to be created using a Rules action to Create New Entity? I am using a Rule, along with the Rules Block/Unblock User module, to create a specific type of node when a user is unblocked (a simple custom note called "Photo" that contains an image field and a token field for the title). The resulting node is authored by the newly unblocked user. The Rule is currently creating the node, but it is also creating a duplicate of that new node (with the same values). It is important that only one node be created, because I have imposed a limit on the number of nodes each user can create (5 total, including the node created by the Rule).

As a test, I removed the "user_was_unblocked" event and replaced it with "user_insert" ("After saving a new user account"), and that resulted in only one node (no duplicate), but it is important for my process that the node creation occur on unblock instead of creation.

What would cause these duplicates to occur?

Here is an export of my Rule:

{ "rules_create_default_public_photo_node_test" : {
    "LABEL" : "Create Default Public Photo Node TEST",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "user" ],
    "REQUIRES" : [ "rules", "rules_block_user" ],
    "ON" : { "user_was_unblocked" : [] },
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "node",
            "param_type" : "photo",
            "param_title" : "Default Photo for [account:name]",
            "param_author" : [ "account" ]
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      }
    ]
  }
}

According to the current status of issue # 2783453 (which IMO should be a support request), this looks like something else is happening in your site.

Something that will help you find the answer to your question, is to have a look at Rules debugging ... Within the Rules settings, experiment a bit with the debugging facilities that come with Rules. At least have a look at the "Rules Evaluation Log" (to check that the Rules logic being executed, actually matches what you expect that logic to be).

For way more details about Rules debugging, refer to the answer to "How can I display the value of a variable inside a condition?".


Trouble populating text field widget while executing node.create through Service using Rest server I have a Rest server running using the Services module which is setup to receive node and user requests.  I have also created a new content type with the following fields:

I am able to add new instances of this content type using Poster (a Firefox plugin for creating http-post requests) using an http-post to my rest server with the following body (using application/json content-type):

{
  "title":"online submission",
  "type":"basic_content",
  "field_text":[
    {
      "value":"Some Text"
    }
  ]
}

I have tried many different variations of this json string (including make it all one line) and it never seems populate the text field.  Could anyone shed any light on this?  I am willing to use a different content-type if necessary.

Field values need to be surrounded by an array, which holds all the potentially multiple entries for the field, and yet another array which holds all of the potential translations for the field.

In PHP that looks something like this:

$node->field_text['und'][0]['value'] = 'Some Text';

I haven't tested it but I'd guess the JSON equivalent would be something like this:

"field_text":
{
  "und":
  [
    { "value": "Some Text" }
  ]
}

That may need a bit of tweaking.


User based node saving I have two roles Editor and Manager. Editor can add nodes as unpublished and manager can review the nodes and approve/publish them in website.

For administration I am using default SEVEN theme for adding/editing nodes. How can i hide "Save and Publish" button to editor role only?

Can it possible by calling a template hook node_presave? I tried below code but not worked.

 function seven_node_presave($node) {
    global $user;

    if (in_array('editor',$user->roles)){
        $node->status = FALSE;
    }

}

if any body can suggest solution for this?

How can i hide "Save and Publish" button to editor role only?

You can use two ways.

Simple ways. Enable module Content Moderation in core and set permission by roles.
Use function hook_form_node_form_alter()

global $user;

if (in_array('editor',$user->roles)){
   $node->status = FALSE;
}

Drupal 8 have some different. Global user replace by
\Drupal::currentUser()

and $user->roles replace by

\Drupal::currentUser()->getRoles()


Admin menu bar covers part of the screen while working in mobile mode I think that the image I attached says it all - a part of the screen is covered by admin menu in mobile view from my pc (this is the default firefox mobile view).

It's extremely problematic when I need to check something that is at the fold of the page, i.e at the top part of the page beacuse it also being covered and I have no where to scroll-up to, and must logout to view it or check through another browser and this can be tiresome sometimes.

There is no configuration settings at admin/config/administration/admin_menu for hiding the admin_menu at the mobile screen, hence you can do 2 things:

Either inspect you site in incognito mode of Chrome or private browsing in Firefox
Permanent solution would be applying CSS for this

@media screen and (max-width: 640px) {
  #admin-menu {
    display: none;
  }
}


How can I get the fivestar module to submit the page url to the database? I know the module stores the entity_id of the "page"/node and I can translate the enity_id's (node id's) to url paths like so, so I can display them in a view:

function MYMODULE_views_pre_render(&$view) {
  // Translate the enity_id's to url paths.
  $results = $view->result;
  foreach ($results as $item =>  $data) {
    $view->result[$item]->votingapi_vote_entity_id = url('node/' . $data->votingapi_vote_entity_id);
  }
}

The problem I have is that when I add a filter to my view so that I can filter the content by url path it still requires to me add an actual entity_id in the filter field (if this makes sense).
I want to be able to extend the fivestar vote submission so that it also submits the node path. This will allow me to quickly add a filter to my view and filter the content by url path. I'm currently struggling with this and nothing seems to work. Any ideas?

what about something like this:

create a hidden field to include the path of the current node
using Rules, set an event after node save to populate that field with the nodes path
filter in views based on that field

I'm not certain if Rules will be able to pick up the new path, but I think it would trigger far enough into the process that the node path would be set.


load custom CSS/JS for each CKEditor instance on page I would like to find out  the best way to load custom CSS/JS for each textarea with CKEditor. For me, each Content Type has different CSS/JS and I would like to load them with the CKEditor on that particular page.

How do I hook into the CKEditor module to do just that?

P.S CKEditor is an independent module and not part of WYSIWYG Drupal Setup.

use hook_page_build to add or remove css or js files to the page based on the url. See the examples module for developers on how to add/remove js or css and to examples of render arrays.

your question is not so much about the CKeditor module or WYSIWYG module -- just how to customize css and js on specific criteria such as the page url.


Twitter not working on HybridAuth I have uploaded the website on pantheon. Users aren't able to login by using twitter provider on my website. I'm using the HybridAuth module. When I try to login, it shows this error

  Fatal error: Cannot redeclare class OAuthException in /srv/bindings/6349f4db8cd54067ae94453f36acb8ec/code/sites/all/libraries/hybridauth/hybridauth/Hybrid/thirdparty/OAuth/OAuth.php on line 11

How do I fix this issue? I have a Facebook login as well and it works. And both the logins work on local host.

You should update the HybridAuth library to the latest version


Drupal 7 Views Contextual Links edit Nodes and Fields I created some Views with Drupal 7 and also installed the module Contextual Links. It helps me to edit Views and Blocks. But for non-admin users like Editors etc. it would be great to even edit Nodes or Fields with Contextual Links.

So I hover a Field there should appear a Edit Link.

I couldn't find any detailed settings for Contextual Links.

Please tell me how to set this up.

At the moment, contextual links for the node are displayed only when you choose "Unformatted" as style and "Node" as row style. I already posted a feature request to allow adding contextual links when the row style is "Fields".


Breadcrumb splits my node title If I have a title that is longer than one line, then the bread crumb trail in the middle of it.

Example:
http://www.energyjustice.net/node/1948

I want the bread crumb trail to either come before or after the title.

I'm using Drupal 7.19

Just add this style to your CSS file

#squeeze .right-corner .left-corner .breadcrumb {
  position: static;
}

This will position your breadcrumbs div according to the normal flow of the page.


How do I set permissions for user roles in the install profile I have a content type which I am creating on install profile, and I want to create a user that has permissions to edit that content type. How do I create user roles and permissions for those roles in the install profile?

To add a role you can use user_role_save():

$role = new stdClass();
$role->name = 'role_name';
$role->weight = 5;
user_role_save($role);

To grant specific permissions to a role you can use user_role_grant_permissions():

$grant = array('access content', 'access comments', 'etc...');
user_role_grant_permissions($role->rid, $grant);


How do I show content in an iframe as a specific user? I want to display an external site (over which I have no control) in an iframe. Someone using my site can have or not have an account on that other site. That site requires membership (which is free) to see any content. In either case, I want to display that other site as a dummy user I made on that site. How do I do this?

I tried using the iframe module and have the iframe point to https://othersite.com/content?email=myemail&password=mypassword, but that seemingly did not do anything. When logged in with my regular user on that other site, the iframe was displayed for my regular user, when not logged in I got a page with a login button.

Can I trigger the pressing of the login button and then fill in the login form, or is it possible that that is not possible?

Edit:
Using curl, I can first log in and then using the same session get the page I want. However, how do I put that out into an iframe? I've now got a variable containing the html of the page I want to show in an iframe between fields belonging to a content type.

The thing to keep in mind here is that an iframe runs on the client side. It is basically a browser within a browser. This also means that it will use an existing session if the client is logged in on the site (you already discovered this):

  When logged in with my regular user on that other site, the iframe was
  displayed for my regular user.

The problem is that Drupal runs server side. Theoretically you should be able to use drupal_http_request() to send the login data to the other site, catch the session cookie and initiate a session. But that would initiate a session on the server, not on the client. The same with cURL, it would log the server in, not the client. So the iframe for the client would still show the login button.

In order to do something client side, your only option is probably to use javascript and perform an POST the login data to the other site. This unfortunately means that the data to login (username and password) also will be sent to the client. A little tech savvy user will be able to compromise your account on the 3rd party site. (If he changes your password, it would break your own site)

  Can I trigger the pressing of the login button and then fill in the
  login form, or is it possible that that is not possible?

Unfortunately also no, browsers implement safety measures to prevent one site form interacting with another. You cannot use javascript (or CSS or anything else) to modify the site within the iframe.

For a second I thought you can try to start the session on the server and then send the session variables to the javascript to process client side. This will not expose your credentials but will still allow someone to take over your session.

So I will conclude with no. There is unfortunately no sensible way of doing this.

Finally there are 2 more things to keep into account;

Do the terms of use of the other site allow you to share an account with multiple users (you could get into a lot of trouble)
What if the client happens to already have an account on the site? You would override his session and he would be you. I would personally hate your site if it forced me to logout and in again on another website.


hook_menu giving 404 I am trying to create module in Drupal 6.22:

function example_video_perm(){
    return array("video access");
}

function example_video_menu() {
    $items = array();
    $items['video/%nid'] = array(
        'title' => '',
        'page callback' => 'video_load',
        'access arguments' => array('video access'),
        'type' => MENU_CALLBACK,
    );
    return $items;
}

function video_load($nid) {
    print_r($nid);
}

But whenever i am typing in http://example.com/video/nid, its getting redirected to 404. Please help.

The problem is that the path associated to your menu item is using a wildcard ("%nid"), but your code is not defining an auto-loader for that wildcard.

For a wildcard such as "%nid" Drupal is looking for a function called nid_load(), which doesn't exist; if you want to use video_load(), then the placeholder should be "%video" and not the one you are using. If that part of the path is a node ID, then you should use "%node" that would cause Drupal to use node_load(), which is a function defined from the Node object and that returns a node object for the node ID passed as argument.
The auto-loader function should return an object or an array. If the auto-loader function is not returning a value, then Drupal would act as if the returned value is FALSE, which is the value that causes Drupal to return to the user the "page not found" error, as it understands the value as meaning "I didn't found what the user is looking for." Return an object (which is what node_load() does), or an array, and the user will not see the "page not found" error anymore.

In your case, the URL for the menu item defined from the module is something similar to http://example.com/video/1, or http://example.com/video/2, where 1 and 2 are (I presume from your code, as you use "%nid" as wildcard, which should mean "node ID") the node IDs of existing nodes.
Take as example the URL for the menu item associated with the node view page, which is "node/%node"; you invoke that page with, e.g., http://example.com/node/1, and Drupal shows you the content of the node with node ID equal to 1.

If you don't want to use an auto-loader, then your menu item should use a path such as "video/%" and Drupal would not look for an auto-loader function. What I reported about the URL to use to invoke the page served from your module is still valid, except that the URL could be  http://example.com/video/asdfsdfwer, http://example.com/video/2, http://example.com/video/azder54gfg because the % in "video/%" matches any string.

Bart is correct in saying that using "%nid" as placeholder in the path, when the page callback, the access callback, or the title callback doesn't get any argument derived from that placeholder, doesn't make sense.

For more information, you can look at the documentation for hook_menu(); Wildcard Loader Arguments, Wildcard usage and core's wildcards, Dynamic argument replacement (wildcard), Wildcard, ancestors and fitness; and, as general information on how Drupal menu system work, Drupal menu system (Drupal 6.x).


Add options to dropdown with ajax I am trying to use ajax in my form to dynamically add options to the dropdown, with the click of a button. The value entered in the textbox must be added to the dropdown. However i am not sure how to retain the added values in the dropdown.
Currently only the recently added value remains in the dropdown.

This is my module code:

<?php
function dropdown_menu(){
    $items['dropdown_form'] = array(
        'title' => 'Dynamic Dropdown',
        'description' => 'adding more textfields',
         'access callback' => 'dropdown_access',
         'access arguments' => array(1),
        'page callback' => 'drupal_get_form', //used during form api
        'page arguments' => array('dropdown'),
    );
    return $items;
}

function dropdown_access() {
    return TRUE;
}

function dropdown($form, &$form_state, $no_js_use = FALSE) {
   $form['field_name'] = array(
      '#type' => 'textfield',
      '#title' => t('Field Name:  String, Woodwind, Brass, Percussion'),
      '#required' => TRUE,
    );

   $field_val = isset($form_state['values']['field_name']) ? $form_state['values']['field_name'] : '';

  $form['add_to_dropdown'] = array(
      '#type' => 'button',
      '#value' => 'Add To Dropdown',
     '#ajax' => array(
      'event' => 'click',
      'callback' => 'dropdown_callback',
      'wrapper' => 'dropdown-second-replace',
    ),
    );

  $form['dropdown_second'] = array(
    '#type' => 'select',
    '#title' => 'Dynamic Dropdown',
    '#prefix' => '
',
    '#suffix' => '
',
    '#options' => get_dropdown_options($field_val),
    '#default_value' => isset($form_state['values']['dropdown_second']) ? $form_state['values']['dropdown_second'] : '',
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#prefix' => '

',
    '#suffix' => '
',
    );
    return $form;
}

function dropdown_callback($form, $form_state) {
    return $form['dropdown_second'];
}

function get_dropdown_options($key = '') {
  $options = array(
    t($key) => drupal_map_assoc(array(t($key))),
  );
  if (isset($options[$key])) {
    return $options[$key];
  }
  else {
    return array();
  }
}

function dropdown_submit($form, &$form_state) {
  print_r($form_state['values']); exit();
}

you should merge the existing vales in $form['dropdown_second']['#options'] with the one in $form_state['values']['field_name']

something like this:

$existing_options = isset($form['dropdown_second']['#options']) ? $form['dropdown_second']['#options'] : array();
$new_option = get_dropdown_options($field_val);

$form['dropdown_second'] = array(
    '#type' => 'select',
    '#title' => 'Dynamic Dropdown',
    '#prefix' => '
',
    '#suffix' => '
',
    '#options' => array_merge($existing_options, $new_option),
    '#default_value' => isset($form_state['values']['dropdown_second']) ? $form_state['values']['dropdown_second'] : '',
  );


Strange views issue on upgrade I'm upgrading a site from 8.4.8 to 8.7.7 via Composer. After a few rounds, things seem pretty good, but I'm stuck on a tricky bit: on drush updatedb the process throws an error on Views post-update. Here's the output

  views module :
    Update dependencies for moved bulk field plugin.
    Add additional settings to the entity link field and convert node_path usage  to entity_link.
    Update exposed filter blocks label display to be disabled.
    Add placeholder settings to string or numeric filters.
    Rebuild cache to allow placeholder texts to be translatable.
    Fix cache max age for table displays.
    Include views data table provider in views dependencies.

  Do you wish to run all pending updates? (y/n): y
  Malformed backend packet [error]
  Post updating views [ok]
  Failed: Exception: No entity type for field field_title on view image_paragraph_default in Drupal\views\Plugin\views\HandlerBase->getEntityType() (line 713 of .../docroot/core/modules/views/src/Plugin/views/HandlerBase.php). [error]
  The command could not be executed successfully (returned: DRUSH_BACKEND_OUTPUT_START - DRUSH_BACKEND_OUTPUT_END, code: 1) [error]
  Cache rebuild complete. [ok]
  Finished performing updates.

So, first of all, am I just missing something obvious? The view is broken in the 8.4 site, too, but I can't figure out how to modify the field or remove  the view, since all attempts throw the same error! Is there a way around that?

Thanks.

Bah, nevermind -- I realized that I can just remove the view from the config table in the db. Then  all updates are free to proceed. Thanks!


Customize user registration form by adding/modifying fields in the form and handling submit function I am new to drupal.

I need to customize a registration form by adding fields like id,mobile etc.

Can I accomplish this by creating a custom module?

If yes could anyone please help me with a brief idea on creating and overriding the default user registration submit function. I have to insert these details to another table and also have to pass the data as a service request.

Ive created a custom module with function

function module_form_alter(&$form,&$form_state,$form_id){
$form['#submit'] = 'module_form_submit';

if($form_id == 'user_register_form'){
    //print_r($form_id);
    $form['email'] = array(
            '#type' => 'textfield',
          '#title' => t('id'),
          '#default_value' => '',
          '#size' => 60,
          '#maxlength' => 15,
          '#required' => TRUE,
     );
    }
}

function module_form_submit($form, &$form_state){
  echo "test";
 exit();
}

module_form_alter is being called and I can see the new field on the registration screen but the submit function is still not called. I need to override the default drupal register submit.

I already have the following function in my theme template.php

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

  $items['user_login'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'portal') . '/templates',
    'template' => 'user-login',
    'preprocess functions' => array(
     'portal_preprocess_user_login'
    ),
  );
  $items['user_register_form'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'portal') . '/templates',
    'template' => 'user-register-form',
    'preprocess functions' => array(
      'portal_preprocess_user_register_form'
    ),
  );
  $items['user_pass'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'portal') . '/templates',
    'template' => 'user-pass',
    'preprocess functions' => array(
      'portal_preprocess_user_pass'
    ),
  );

  return $items;
}

user-register-form.tpl.php

    <?php print drupal_render_children($form); ?>

And page--user--register.tpl.php with the html

<a href="<?php echo $home; ?>"><img src="<?php echo drupal_get_path('theme', 'portal') . '/images/logo.png'; ?>"  width="100"><?php echo $createaccount; ?>

            <?php
            $elements = drupal_get_form("user_register_form");
            $form = drupal_render($elements);
            echo  $form ?>

     <?php if ($messages):?>

                <?php print $messages; ?>

        <?php endif; ?>

Is this approach fine or should I change this approach inorder to make my custom module functional?

One problem, I need to validate this form in client side, Ive added js in module_form_user_register_form_alter function as
         $form['#attached']['js'] = array(drupal_get_path('module', 'modulenamne').'/js/myjs.js',);

File is loaded but when clicked on submit the js is not working, instead the page is loading and drupal submit is executing.

If it is not crucial for you to have the additional fields in custom code, I would highly recommend you to make use of the fact that user is a fieldable entity and you can add additional fields easily to it via administration at "admin/config/people/accounts/fields" - this way you do not need to handle saving of the data and display of form elements.

When doing so, you can still make use of custom validation or submit handlers or fiddle with the form and fields easily using the same technique you are using - hook_form_alter and add your submit handler to do whatever logic you require.

Back to your approach — the reason why your submit function is not being called is that you are assigning a string to it instead of adding an element to the array. Try this:

$form['#submit'][] = 'module_form_submit'; (notice the empty brackets on the left side).

If you want to completely overwrite the submit functions array use this:

$form['#submit'] = array('module_form_submit'); - but this will cause that the user will not be created and data saved (unless you do that by hand in your custom submit handler), this also cancels whatever some contrib modules to with the registration form, so you might have unexpected issues.

Edit after comments:

If you do want to keep the default behaviour, but do your logic before everything, you can put your submit handler as first, as they are executed based on their order in the array like this:

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


Programatically add module block to dashboard Is there a way in which from my .module file I can assign a block in a specific region from Dashboard?

It can be done in a simple way by mentioning a region key to the $blocks array in the HOOK_block_info(). Follow the code for reference,

    /**
     * Implements hook_block_info()
     * @return array
     */
    function my_module_block_info() {
      $blocks = array();
      $blocks['leaderboard'] = array(
        'info' => t('Leaderboard'),
        'status' => 1,
        'region' => 'dashboard_main',
        'weight' => 99,
        'cache' => DRUPAL_CACHE_PER_ROLE,
      );

      return $blocks;
    }


Is it possible to use drush migrate-import to import custom fields? I am trying to migrate a Drupal 7 site to Drupal 8 on a new server
I have copied the db so it can be used locally.
I have run the drush migrate command and migrate-status shows a bunch of things that are ready for import.
I can import users with drush migrate-import d7_upgrade_users. However the users have custom fields associated with them and I can't find how to import those fields through drush.
Trying to export a csv from the old host is virtually impossible as it crashes out trying to do the export.

Is it possible to import all user data including passwords and custom fields from the command line using drush (or other command line tools) without the need to import everything?

I am currently working on a similar migration and had a similar problem. In my case the custom fields were part of the Profile2 module in D7. I installed the D8 Profile module and added a patch that fixes the Profile2 import

https://www.drupal.org/files/issues/2018-05-16/profile-migrate-from-profile2-D8-2957256-4.patch

After that, the custom fields were automatically created, populated and linked to the correct user.

Not sure if that is what you need.


Views - how to replace the pager with a slider I have a view of events, and want to display 10 events at a time.

Instead of the clicking the pager, I want the view to cycle to the next 10 events automatically after a set number of seconds - the view will be displayed on a monitor without user interaction.

The views_slideshow module only allows me to do this with every single item in the view.
How would I best approach this - ideally with an existing module.

Please let me know if the question is not clear.

Any help appreciated!

Views Slideshow sounds like the ticket https://www.drupal.org/project/views_slideshow.
FlexSlider might do the same, but also responsively.


How to create a theme date view with CSS styles? I created my view (datev) that contains two field (date and description).
I renamed my template views-view-datev.html.twig and views-view-fields--datev---block.html.twig.
I already have my CSS but I do not know how to use my template theme.

I want it appears like this.

I have my CSS to achieve this poster but I do not know how to add ??
how broken down the date for this display

Add 1 more Content: Even Date field.
Then for each Even Date field, select custom formatter.
for the first one put d (Note: there seems to be a bug, you will have to do this twice, as when you save the 1st time it does not change)

for the second one put F Y (Note: there seems to be a bug, you will have to do this twice, as when you save the 1st time it does not change)

Result

PS: You can add CSS classes to your field under the fields STYLE SETTINGS, no need to use template files to add css classes.

Then, for example, you add .cool { border: solid red; } to your theme's css file.


basic theming question on user module I would like to ask a very simple (for you probably!) question on theming/layout:

By default the user module displayes the "username" + "password" vertically.
I want to display these 2 fields horizontally.

To do so:

-It is the css that I have to modify, right?
-Do i have to modify the user.css or the css of my theme?
-Any ideas on how do I modify it, or what is the piece of code I have to alter?

Thank you.

You can extend Omega Theme and override the css in your global.css file. So you will have  a new theme and core files are intact.

All you need to install is  Omega Theme. And the By going to Appearence you can create a new theme and override the css files.


How can I allow a user to create a user, but not view all users? In Drupal 7, I can set the 'administer users' permission to a certain role. However I do not want this role to be able to view and filter/search all users in my Drupal site. The admin/people/create only, but no admin/people  page should be accessible because they have the capability to filter the administrator role! And able to edit it in turn.

Is there a module that can do this?

Subuser module can help to achieve this goal. A user that is allowed to create a sub users can manage them as well.


Declaration of DrushInputAdapter::hasParameterOption($values) must be compatible with Symfony I have a Drupal 8 site set up with Acquia Dev Desktop on my localhost. I am using PHP 7.0.14; everything is working fine, and the site works perfectly.

I installed Drush 8.  When I try to run drush cr all, I get this error message.

  PHP Fatal error:  Declaration of Drush\Command\DrushInputAdapter::hasParameterOption($values) must be compatible with Symfony\Component\Console\Input\InputInterface::hasParameterOption($values, $onlyParams = false) in /Applications/DevDesktop/tools/vendor/drush/drush/lib/Drush/Command/DrushInputAdapter.php on line 27

The lines causing the error are the following ones.

class DrushInputAdapter implements InputInterface {
    protected $arguments;
    protected $options;
    protected $interactive;

    public function __construct($arguments, $options, $command = false, $interactive = true)
    {
        $this->arguments = $arguments;
        $this->options = $options;

        // If a command name is provided as a parameter, then push
        // it onto the front of the arguments list as a service
        if ($command) {
            $this->arguments = array_merge(
                [ 'command' => $command ],
                $this->arguments
            );
        }
        // Is it interactive, or is it not interactive?
        // Call drush_get_option() here if value not passed in?
        $this->interactive = $interactive;
    }

With Drupal Console, I get something similar.

  PHP Fatal error:  Declaration of Drupal\Component\DependencyInjection\Container::set($id, $service) must be compatible with Symfony\Component\DependencyInjection\ContainerInterface::set($id, $service, $scope = self::SCOPE_CONTAINER) in /Users/josue/WebDevelop/drupal-8.4.0/core/lib/Drupal/Component/DependencyInjection/Container.php on line 47

Updating to Drush 9, as suggested in the comment by user3346970, is certainly one solution to this problem. If you wish to stick with Drush 8, upgrade to version 8.1.15 or later. The problem you report above was fixed somewhere around version 8.1.12.

I'm not certain about the exact versions of Drupal Console to use with each version of Drupal, but I believe that you will probably also discover that updating to the latest version should resolve things as well. The error you are seeing indicates you are crossing Symfony version 2 (e.g. in an old version of Drush or Drupal Console) with Symfony version 3 (e.g. in Drupal 8.4.0 and later).


Drupal 8 Installation Symphony routing error I am installing a second Drupal 8 site on an existing server configured to redirect a sub-domain to the new site. The Install was uneventful, but when I visit the site to confirm it is working I am met by:

The website encountered an unexpected error. Please try again later.

Inspecting the apache2 error.log i see the following:

Uncaught PHP Exception Symfony\\Component\\Routing\\Exception\\RouteNotFoundException:
"Route" search.view_node_search" does not exist." at
/var/www/html/subdomain/core/lib/Drupal/Core/Routing/RouteProvider.php line 187

I have double checked my rewrite module and it seems to be setup correctly for the sub-domain. I even tried re-setting it in the virtual host and the .htaccess file but no luck.

The directory for the sub-domain does differ in name to the actual site address, though I think this should not be a problem.

Can someone please explain what this means and how I fix it?

Clearing cache at config/development/performance worked for me.


Create a template file for view field? How do I create template file for view field, My view machine name is page_search and field name is room type.

First look into Theme information in views:

In Row style output, copy one of the template names:

This lists all available .tpl for your views and now Create an empty php file with your chosen template name in your themes template folder.


Rules (not) triggered with Bulk Media Upload Rules (not) triggered with Bulk Media Upload

I have a node type called 'uploads' that includes a user reference field to make each upload particular/available to a certain user.

I have added a rule so when a new upload is added, they are e-mailed to let them know there's something new for them to see once they're logged in.

This works fine when adding uploads (nodes) one at a time, but I'm also using "Bulk Media Upload" (https://www.drupal.org/project/bulk_media_upload) to allow for multiple uploads/node creation, at which point the rules fail with the following error:

"Unable to get the data value for the variable or parameter id. Error: Unable to get the data property uid as the parent data structure is not set."

I realize that Bulk Media Upload is on/past the outs; but I do need the functionality it provides and am unsure as to why the data isn't available doing things this way when they are doing things one at a time.  The references are made the same way in either case since Bulk Media Upload uses/requires the same values.

Edit - Ok, here's the rule being used:

            { "rules_results_uploaded" : {
                "LABEL" : "Results Uploaded",
                "PLUGIN" : "reaction rule",
                "OWNER" : "rules",
                "REQUIRES" : [ "rules", "php" ],
                "ON" : { "node_insert--uploads" : { "bundle" : "uploads" } },
                "DO" : [
                  { "entity_fetch" : {
                      "USING" : { "type" : "user", "id" : [ "node:field-for-user:uid" ] },
                      "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
                    }
                  },
                  { "drupal_message" : { "message" : "Receipt of the sample on \u003C?php echo $data[\u0027components\u0027][\u0027sample_received\u0027][\u0027value\u0027][0]; ?\u003E has been acknowledged.  \r\n\r\nAn e-mail will be sent to [entity-fetched:field-practitioner-name] at [entity-fetched:mail]" } },
                  { "mail" : {
                      "to" : "[entity-fetched:mail]",
                      "subject" : "Your Sample Results Have Been Uploaded",
                      "message" : "Dear [entity-fetched:field-practitioner-name],\r\n\r\nNew sample results are now available on your account.",
                      "from" : "results@afakewebsite.com",
                      "language" : [ "" ]
                    }
                  }
                ]
              }
            }

Again, the rule works fine when fine when adding a new node of the type 'uploads' one at a time, it just doesn't work using bulk media upload (though triggering multiple times.)  Perhaps I'm misunderstanding how BMU works.

Any thoughts or alternatives still much appreciated.

As noted, your rule is setup for serial upload operations; BMU sets the entities in a batch process, rather than one reference/file at a time.

You may be able to overcome the race condition resulting from the rule firing and batch processing by triggering the rule on node save rather than individual file uploads while editing the node.  This will ensure each file has a Drupal FID assigned and has been fully added to the files table in Drupal for referencing.


Need clarification on adding JS to content item with JS injector and drupal_add_js I want to put some js on my article. Original code form http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_hide_p

is:

    <!DOCTYPE html>

This is a heading

This is a paragraph.

This is another paragraph.

<button>Click me</button>

My article is at:   http://xuzo.com/testing/node/44

Here is what I have done

put this code in content item source code:

This is a heading

This is a paragraph.

This is another paragraph.

Click me

Put this in JS Injector box:

$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});

and this for URL:

node/44

put this in my /public_html/testing/sites/all/themes/xuzo/template.php file:

drupal_add_js('https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js', 'external');

Flushed all cache
Not working!!! ;)

Additionally...for this line of code to load JS files locally:

drupal_add_js('misc/collapse.js');

Where to put the JS file? I take it misc can be any folder name? But where to put the files in relation to root? Sites/all ?

1. Like Shrish mention your code needs to be like this

(function($) {
    // your code here
    $(document).ready(function() {
        $("button").click(function() {
            $("p").hide();
        });
    });

})(jQuery);

2. your code says $("button").click(function() { but in your html there is no button:

This is a heading

This is a paragraph.

This is another paragraph.

Click me

So change this to:

This is a heading

This is a paragraph.

This is another paragraph.

<button>Click me</button>

3. Checkmark inline js in JS Injector


How to make a custom composite field? Is it possible to create a custom field widget or use hook_form_alter() to show multiple form elements that, used together, can set the value of a single field?
For example, I added a textfield Personalization.
But on the entity edit form, I do not want users to edit the Personalization field directly; instead, I want them to check some boxes and fill in some text fields, and then I want to process that data and set the value of the Personalization field as a result of that processing.  How do I set up the extra form elements and use them to set the value of the field?
I tried to do this by override the textarea FieldWidget:
/MYMODULE/src/Plugin/Field/FieldWidget/TextareaPersonalizationWidget.php
<?php

namespace Drupal\MYMODULE\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\Plugin\Field\FieldWidget\StringTextareaWidget;
use Drupal\Core\Form\FormStateInterface;

/**
 * Plugin implementation of the 'text_textarea_personalization' widget.
 *
 * @FieldWidget(
 *   id = "text_textarea_personalization",
 *   module = "MYMODULE",
 *   label = @Translation("Personalization widget"),
 *   field_types = {
 *     "text_long",
 *     "string_long"
 *   }
 * )
 */
class TextareaPersonalizationWidget extends StringTextareaWidget {

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {

    $element['a']['#type'] = 'textfield';
    $element['a']['#title'] = 'Your fav animal';
    $element['a']['#maxlength'] = '255';
    $element['b']['#type'] = 'textfield';
    $element['b']['#title'] = 'Your fav fruit';
    $element['b']['#maxlength'] = '255';
    return $element;
  }

}

This causes two textfields to be shown instead of the textarea.  Great!  Except the value never gets saved, and I can't process the input text in hook_entity_presave().  So how can I process the input in the custom form elements and save the result in the original field?
I also tried the same thing in MYMODULE_field_widget_string_textarea_form_alter() but I had the same problem.
More details about how my site is set up
Here's my setup: I have a flag called Collection.  This flag contains a textfield, Personalization.  This textfield will contain pairs of strings for replacing text with JavaScript in order to customize the text on terms that have been flagged by the user.
Of course, I don't want users to type in arbitrary strings into a textfield; this would be a terrible UI.  So, when a user flags a taxonomy term, I want to show some form elements that allow the user to input some options for personalization.  These form elements will be different depending on which term is being flagged.  For example, if flagging the Fruits term, I want to add a text field "What is your favorite fruit?"  And on the Cakes term, I want to add a list of checkboxes "Choose all the types of frosting you like."
In other words, I want to define a custom form per taxonomy term that sets the value of the Personalization field, and I want to somehow embed this custom form on the flag add form.

Except the value never gets saved, and I can't process the input text
in hook_entity_presave().

You can add a new validate for your widget:
/**
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
  // Your logic code

  // Add validate for your widget.
  $element['#element_validate'] = [
    [$this, 'validate'],
  ];

  return $element;
}

And convert value before save:
/**
* Validate the fields and convert data before save.
*/
public function validate($element, FormStateInterface $form_state) {
    // Logic validate.
    // Code here

    // Convert value and set.
    // Field type text_long
    $value = [
     'value' => 'your value',
     'format' => 'your format'
    ];

    // Field type string_long
    $value = [
      'value' => 'your value'
    ];

    $form_state->setValueForElement($element, $value);
}


Is it possible to give to a specific user role the permission to create content only in a language? I've a Drupal 8 site using 8 languages. The site is not a multi-domain.

The Admin DE role should have only the permission to create nodes or translate nodes in German, but can view all node in all languages.

I don't find a module that can implement this functionality.
Do you have any ideas?

Create a custom module for this. I'm including some code that may help get you started. The idea behind this code (below) is preventing a user without the role 'admin_de' from editing content that has a different language than what the 'admin_de' user has set for their account. So there are some obvious differences, but this should be a good start.

In MY_MODULE.info.yml:

name: MY_MODULE
type: module
description: Allows user with particular role to edit content of particular
language.
core: 8.x

In a file called MY_MODULE.permissions.yml, include:

edit same language:
  title: 'Edit Same Language Only'
  description: 'Allow user to edit only nodes matching their account language'

In a file called MY_MODULE.module, include:

<?php

use \Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Entity\EntityForm;

/**
 * Implements hook_form_alter().
 */
function MY_MODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $currentUser = Drupal::currentUser();
  $roles = $currentUser->getRoles();

  if (in_array('admin_de', $roles)) {
    switch ($form_id) {
      case 'node_CONTENT_TYPE_edit_form':
        $currentUserLanguages = getUserLanguage($currentUser->id());
        $submissionLanguage = getSubmissionLanguage($form_state);
        $status = (Drupal::currentUser()
        ->hasPermission('edit same language') && ($submissionLanguage == $currentUserLanguages));
        if (!$status) {
          throw new \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException();
        }
        break;
    }
  }
}

/**
 * @param $userId
 * logged in user id
 *
 * @return string of language id logged in user is associated with.
 */
function getUserLanguage($userId) {
  $user = \Drupal\user\Entity\User::load($userId);
  $languageId = $user->language()->getId();

  return $languageId;
}

/**
 * @param FormStateInterface $form_state
 *
 * @return string language id of page
 */
function getSubmissionLanguage(FormStateInterface $form_state) {
  $language = '';
  $form_object = $form_state->getFormObject();
  if ($form_object instanceof EntityForm) {
    $entity = $form_object->getEntity();
    $language = $entity->langcode->value;
  }

  return $language;
}

Hope this helps!


Custom drush command not working I have used hook_drush_command to create a new drush command. This is my custom code for creating drush command.

/**
 * Implementation of hook_drush_command().
 */
function mymodule_drush_command() {
  $items = array();
  // Name of the drush command.
  $items['list-site-users'] = array(
    'description' => 'Print the list of users in the site',
    'callback' => 'drush_get_site_users',
  );
  return $items;
}

function drush_get_site_users() {
  $query = db_select('users', 'u');
  $query->fields('u', array('name'));
  $result = $query->execute();
  while($record = $result->fetchAssoc()) {
       print_r($record['name']);
  }
}

After this I have exceuted drush cc all and drush cc drush for clearing drush. Then I have executed my custom drush command drush list-site-users command, but it is throwing the below error.

  The drush command 'list-site-users' could not be found.  Run drush
  cache-clear drush to clear the commandfile cache if you have
  installed new extensions.

My drush version is 5.10.0

Try the following:

/**
 * Implements hook_drush_command().
 */
function mymodule_drush_command() {
  $items['list-site-users'] = array(
    'description' => 'Does a database cleanup.',
    'examples' => array(
      'list-site-users' => 'Retrieve list for all users',
    ),
    'aliases' => array('lsu'),
  );
  return $items;
}

function drush_mymodule_list_site_users() {
  $query = db_select('users', 'u');
  $query->fields('u', array('name'));
  $result = $query->execute();
  while($record = $result->fetchAssoc()) {
       print_r($record['name']);
  }
}

NOTE: Make sure you write the above code in mymodule.drush.inc file of any module.
Clear the cache and your drush command should work.


Views and node references I have 3 content types. Town, Hotel and Price. Hotel has a node-reference to Town, Price has a node reference to Hotel.

I'm trying to create a block view to use one the Town node page displaying a list of Hotel nodes in that town, together with the lowest Price (field_price of the Price node).

Is something like that achievable with views? I did manage to get a list of all hotels in a town by using a contextual filter, but I can't seem to get the additional step of getting the prices in the view.

A custom module would obviously be an option, but if it's possible with views, I would prefer that solution.

You cannot create a relationship from Hotel to Price. You have to go the other way.

Create a block view of Price. Configure a Relationship on the node reference to Hotel (field_hotel), and make it required. Add Content:field_price (not using relationship) and Content:Title (using the relationship) to your display, Add a sort on field_price (Ascending).

To limit the display to the Town, create a Contextual filter on field_town, have it use the relationship, and set it to Provide default value:Content ID from URL.

Configure your block to display on the Town content type, and you are done.


Migrate multi-value paragraph field I'm doing a D7 to D8 custom migration. In Drupal 7, I have a multi-value formatted text field that I am trying to map to a Drupal 8 multi-value Paragraph entity reference field.

I've separated this into two migrations. One for the paragraphs, and one for the nodes themselves. I've got the multi-value field to paragraph migration working (although I think there might be an issue with the way that I have done the IDs). I have the node migration working as well, with the exception that none of the references to the already migrated paragraph entities are being migrated.

I realize that right now, this seems unnecessary, but it's part of a feature upgrade.

Below is the code from my migration classes/plugins.

This is from migrate_plus.migration.presentation_node.yml.
Field_slide is the paragraph reference field.

'field_slide/target_id':
  plugin: migration
  migration: presentation_slide
  source: entity_id

This is the getIds function from PresentationSlide.php. This is the plugin for the paragraph migration.

public function getIds() {
  return [
    'entity_id' => [
      'type' => 'integer',
      'alias' => 'lt',
    ],
  ];
}

This is also from PresentationSlide.php. Here I am combining the entity_id and delta to form a unique id. I realize that this is a terrible way to do this, but I couldn't figure out anything better. Any tips on this are welcome.

public function prepareRow(Row $row) {
  $nid = $row->getSourceProperty('entity_id');
  $delta = $row->getSourceProperty('delta');
  $slide_id = (string) $nid . (string) $delta;
  $slide_id = (int) $slide_id;
  $row->setSourceProperty('entity_id', $slide_id);

  return parent::prepareRow($row);
}

And this is from PresentationNode.php. Here I am fetching all of the referenced fields, and passing that as an array to the migration class.

public function prepareRow(Row $row) {
  $nid = $row->getSourceProperty('nid');
  $query = $this->select('field_data_field_learning_text', 'lt')
    ->condition('entity_id', $nid);
  $query->addExpression('CONCAT(entity_id, delta)', 'target_id');

  $slides = $query->execute()->fetchCol();

  if (!empty($slides)) {
    $row->setSourceProperty('entity_id', $slides);
  }

  return parent::prepareRow($row);
}

The main issue here is that I can't figure out how to properly use a multiple column key. It seems to me that all of my issues are due to my doing this improperly.

Thanks in advance. I realize this is a lot.

[Edit]

Thanks Berdir for the help. I've taken a stab at implementing your processing plugin. However, I'm having an issue where the migration seems to be skipping right over and ignoring the process plugin.

field_slide:
  plugin: paragraph_process_base
  source: field_body_value

Feel like there is something super simple that I'm missing here.

[Edit 2]
And I had a typo... Thanks a ton!

This is not directly an answer, but it is also too long for a comment :)

When I migrated something that wasn't actually paragraphs into paragraphs, I just wrote a custom process plugin that created paragraphs on the fly, then I didn't have to bother about trying to figure out some kind of mapping/made up ID's. What you're doing definitely seems like a bad idea, as 1010 could either be delta 10 from node 10 or delta 0 from node 101.

Put two classes I used for that into a gist: https://gist.github.com/Berdir/8a650a29a670fe283589f8946354086c.

It is both a bit hacky and a fairly complicated as I needed to support importing multiple translations for separate nodes in 6.x to a single node with a single paragraph with translations in 8.x.

Also created a to-do for me to write a blog post about this. ;)


How to make a custom page.tpl.php file for a views page? I have made two pages, one for my sites Terms of Service and a second for a secondary add content page. I made both in views with a custom text field. I would like to have a custom page.tpl.php file for these pages so they can better match my theme. How would I do this? Also, If anyone has a better way for me to make a TOS page, I would appreciate the insight. I will be making  a page describing my privacy policy as well as few other things and I want to make sure Im doing this in the most efficient way.
Thanks.

I agree with sheena_d's advice above -- it sounds like what you are trying to accomplish could much more easily be accomplished by using simple pages. That said, here is one way you could do this using views overrides in your template.php theme file.

What you're after is this command:

$variables['template_files'][] = "your-new-view.page.tpl.php";

but you need to get Drupal to hook into this somehow. One way to do this is with a views preprocess function, added to your template.php file:

function <your-theme-name>_preprocess_views_view__<your-view-name>(&$variables) {
    $variables['template_files'][] = "your-new-view.page.tpl.php";
}

You would need to replicate this function for however many views you want to override the page.tpl.php file for.


What is causing the unusual output when trying to create charts in Drupal 7 using the pChart library? I have been trying to display graphs to users in my Drupal 7 website, by using the PHP library pChart   (which comes with a lot of documentation also). Using the libraries module, I have successfully enabled the pChart library.

Then I tried a basic example that came with the downloaded pChart library. Below is the code that I added in a node with the PHP filter enabled,

<?php
$name = "pChart2.1.3";
if ($path = libraries_get_path($name)) {
include($path.'/class/pData.class.php');
include($path.'/class/pDraw.class.php');
include($path.'/class/pImage.class.php');
}
/* Create your dataset object */
$myData = new pData();

/* Add data in your dataset */
$myData->addPoints(array(1,3,4,3,5));

/* Create a pChart object and associate your dataset */
$myPicture = new pImage(700,230,$myData);

/* Choose a nice font */
$myPicture->setFontProperties(array("FontName"=>$path.'/fonts/Forgotte.ttf',"FontSize"=>11));

/* Define the boundaries of the graph area */
$myPicture->setGraphArea(60,40,670,190);

/* Draw the scale, keep everything automatic */
$myPicture->drawScale();

/* Draw the scale, keep everything automatic */
$myPicture->drawSplineChart();

/* Render the picture (choose the best way) */
$myPicture->autoOutput("pictures/example.basic.png");
?>

However, with no errors, warnings or notices, I only get the below unusual output:

My Question: So what is this and what am I doing wrong?

The output you are seeing is simply the PNG file that is being outputs it would be a text file. That is because Drupal already sets the "Content-type" header to "text/html; charset=utf-8," while the method you are calling is setting it to "image/png."

   function stroke($BrowserExpire=FALSE)
    {
     if ( $this->TransparentBackground ) {imagealphablending($this->Picture,false); imagesavealpha($this->Picture,true); }

     if ( $BrowserExpire )
      {
       header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
       header("Cache-Control: no-cache");
       header("Pragma: no-cache");
      }

     header('Content-type: image/png');
     imagepng($this->Picture);
    }

   /* Automatic output method based on the calling interface */
   function autoOutput($FileName="output.png")
    {
     if (php_sapi_name() == "cli")
      $this->Render($FileName);
     else
      $this->Stroke();
    }

What you could do is:

Use pChart to create a file containing the chart you want to show
Output a  tag that references the created file

If imagepng() used the PHP stream wrappers (which is true for file_get_contents()), the following code would work.

/* Render the picture (choose the best way) */
$uri = file_create_filename('example.basic.png', file_build_uri('pictures'));
$myPicture->Render($uri);
echo('');

In this case, the code is slightly more complex.

/* Render the picture (choose the best way) */
$uri = file_create_filename('example.basic.png', file_build_uri('pictures'));
$instance = file_stream_wrapper_get_instance_by_uri($uri);
if ($filename = $instance->realpath()) {
  $myPicture->Render($filename);
  echo('');
}

I wrote a conditional statement around $filename = $instance->realpath() because DrupalLocalStreamWrapper::getLocalPath(), the method called by DrupalLocalStreamWrapper::realpath(), can return FALSE when it cannot determinate the real path.

file_create_filename() is a function that returns a unique filename; in the case there is already a file with the name passed as argument, the function adds a number at the end of the filename, checking every time the file doesn't exist already. If "example.basic.png" is the name of an existing file, the function will try with "example.basic_0.png"; if there is already a file using that filename, it will try with "example.basic_1.png"; the loop is continued until the function find a filename that is not already used.

In the case you need to the filename to a function, as in this case, try first the file_create_filename($filename, file_build_uri($directory)) approach, when you are not sure the function to which you are passing the filename is using PHP stream wrappers; only in the case it doesn't, you should use file_stream_wrapper_get_instance_by_uri() as in the second snippet.


buy one get one free Ubercart discount module? Can I use some module to make offers in ubercart
I have to make an offer of 2x1 type (buy one, get one free)
or buy 2 and get 1 free type of offers

It looks like Ubercart Discounts (Alternative) can do you you ask:

  Features

  Filter both products required for the discount to apply and qualifying products that receive the discount based on multiple products, taxonomy terms, node authors, or product classes.
  The above filters allow for a discount like: buy 3 of any of X product and get a discount on any of Y product.
  Attempts to automatically add free products to the cart for codeless discounts.
  Discount # of products, a percentage or a fixed amount off.
  ...

I don't have any personal experience with the module, but it looks promising.


Audio File Field is empty (null) on drupalgap app What i want to do is create/view podcast node type inside DrupalGap App in Android.
I am using drupal 7 on Centos 7.
drupal module: audiofield (https://www.drupal.org/project/audiofield)
drupalgap module added on www\app\modules: audiofield (http://drupalgap.org/project/audiofield)
I am using HTML 5 player (default). But also tried before jplayer.

On content type named podcast i have fields:
title, body and
audio file with File (as type) and Audio Upload (as widget).

Permission given:
Audio: Download own files
Audio: Download All Audio Files
Media->Use the media browser
Podcast: Create new content
Podcast: Edit own content
Podcast: Delete own content

even i gave:
Add and upload new files
View own private files
View own files
Audio: Edit own files
Audio: Delete own files
Audio: Download any files

In browser i can listen and download and create new Podcast. All work well.
In my android app (drupalgap) when viewing, i can see a player but nothing happens when i press play or download button. And when i try to create a podcast in the audio file field, DrupalGap shows Null and nothing else below.

P.S. I can provide test account if need be

Any suggestions?

Thank you

The problem was that the url of the source audio file was wrong. It happened after i deleted originalsong.mp3 and reuploaded it. So, system gave it new name originalsong_0.mp3 (Note the _0 at the end of the filename). Probably drupal keeps track of files uploaded even when they are deleted so when i upload same mp3 with same filename it gets _0, _1 etc.
Null object appears at www.example.com/mobile-application but when project is compiled and run in real Android device it works out of the box. Play button works but not Download button(minor problem for me).


Where is links__system_main_menu defined? I searched for links__system_main_menu, but just find usages of this theme. Where is it defined?

Drupal 7 core doesn't actually define this function.

links__system_main_menu is a theme hook pattern of the form [base hook]__[context]. When links are themed with theme('links__system_main_menu', $vars), theme() will search for and use theme_links__system_main_menu() if it has been defined. If not, it will use theme_links().

See theme() for the official documentation of this behavior. Chapter 3 of Drupal 7 Module Development does an excellent job of explaining this and provides several examples.

BTW, the same principle applies to template files. If, for example, we call theme('node__article__1', $vars), theme() will search for a node--article--1.tpl.php file, and then for node--article.tpl.php, finally falling back to node.tpl.php if neither of them are defined.


Drupal way of sending push notification to android devices I am trying to send push notifications to Android, and Apple iOS devices. To store the device tokens, I am using cocoa rest client. For iOS devices that is fine, but I didn't understand how to store RegId and token for the Android devices. as we have only 4 attributes, namely:

token
uid
type
timestamp

Generally, for Android we have to store RegId and device token, but in the table we don't have any attribute to store Regid. I am giving post values as type=android,token=device token.

Will this help me to send push messages to Android devices? Without RegId, I think it is not possible.

I am using the Push Notifications module.

Try the Push Notifications module. I've never done this -- but you're basically asking how do I send X message type to a user (SMS, Email, whatever). I've sent emails and SMS messages before ...

Beyond wanting to send this notification from within drupal/php ... there isn't anything really drupal specific in your question in terms of the drupal API.

If you dont userstand the protocol or APIs you want to talk to I would suggest you research them more as well. I would start by looking at the source code for the PushNotifications module and see how it handles the logic of what you are asking about ...


Use existing serial field with same counter across content types how do I use existing Serial field in other content types with same counter db table?
Have 2 CCKs, cck-A has a serial field (auto increment) (ParticipantNumber), added same ParticipantNumber serial field (add existing field) in cck-B.
But the serial field value for both CCKs have independent auto incremental value.

How do I make the ParticipantNumber values be incremental (and Unique) across cck A and B? (just like node nid)

Instead of Serial type, I added Integer field, and added the same field (add existing field) in other content type as well. And In the hook_entity_presave, I query for the MAX(field_value), increment and assign for the current node/entity.


Twitter module Oauth 'TwitterException' with message 'Unauthorized' When trying to authenticate a Twitter account using the Twitter and OAuth modules, I get the following error

  Could not obtain a valid token from the Twitter API. Please review the configuration.

I have since found that The following error is recorded in Watchdog

  exception 'TwitterException' with message 'Unauthorized' in /var/www/html/sitex/public/sites/all/modules/twitter/twitter.lib.php:151 Stack trace: #0 /var/www/html/sitex/public/sites/all/modules/twitter/twitter.lib.php(114): Twitter->request('https://api.twi...') #1 /var/www/html/sitex/public/sites/all/modules/twitter/twitter.lib.php(51): Twitter->auth_request('https://api.twi...', Array) #2 /var/www/html/sitex/public/sites/all/modules/twitter/twitter.pages.inc(343): Twitter->get_request_token()

  [Abridged]

Having checked out the URL which is generated and sent off by drupal_http_request I get the following error message

  Failed to validate oauth signature and token

I have checked the following

Followed https://drupal.org/node/1346824
Reinstalled both the Twitter and OAuth modules
Ensured my OAuth Consumer key is correct
Ensured my OAuth Consumer secret is correct
Ensured I have Read & Write permissions
Ensured my server time is within 5 minutes of Twitter's as per this thread
Ensured my server is running extension=php_openssl.dll
Ensured my callback URL is correct - http://mywebsite.com/twitter/oauth

Note that I am not on localhost, nor is my host behind .htaccess

Visiting my callback URL results in the following error at /admin/config/services/twitter

  The connection to Twitter failed. Please try again.

I am not on localhost, but have tried the suggested 127.0.0.1 callback URL regardless.
I do a version compatible/containing "Patch 5" as mentioned here
I'm using the following versions of the modules

Twitter 7.x-6.0-alpha2+1-dev (But have tried 7.x-5.8 too)
OAuth 7.x-3.1
Core 7.22

I haven't enabled the following- Do I need to?

OAuth Provider UI
Twitter actions
Twitter Post
Twitter Signin

I'd appreciate it if anyoneis able to provide insight!

Thanks

This just started working with no change- I can only assume it was a temporary problem with Twitter at the time.

To some degree a useless answer, but the question gives others a list of things to try in the same situation and allows me to mark this question as resolved.


Node access based on view mode I have a content type with multiple fields. Some of the fields are accessible to everyone and there are other fields for which the access is controlled.

Example: There is a content type called Reports with fields like title, summary, body etc. Title and summary should be visible to everyone but the access to body field is controlled.

For implementing this I need to have 2 view modes. one of them will have the fields title and summary displayed with the rest of the fields hidden. The other view mode will have only the body field visible. I am planning to implement the hook hook_node_access to derive the access permissions for the node. So how can I get the view mode in this hook so that I can have my access check based on the view mode.

I did some searches but I couldn't find any module that does this. But you can implement the hook_node_view() like this:

function YOUR_MODULE_node_view($node, $view_mode, $langcode) {
    global $user;
    //verify that the user is not loged and the view mode is full view
    if(in_array('anonymous user', $user->roles) && $view_mode == 'full') {
        //denied the access
        drupal_access_denied();
        //avoids other hooks are invoked
        drupal_exit();
    }
}

I tested the above code and it works.