How can I use jCarousel with swipe event in drupal for touch screen? In my project, I used the jCarousel module and View slideshow module for my items.When I tested with mobile devices,I saw there is a problem for navigation. I can't scroll well . So I would like to add some script for this problem.I already added some script for My View SLide Show from this website (https://gist.github.com/eristoddle/5011106). Fortunately , it works well with View Slideshow but it not works with jCarousel. I need to know which script is appropriate with my problem. Please let me know how can I do? Thanks in advanced.

You can use

Swipe event
jQuery.event.swipe

On swipe you can trigger left and right navigation event.

Reference:

Swipe


Really customized themes I've been toying around with Drupal 7 for a couple of weeks now, and I think I understand how the theming system works, but I have a question.

I'm looking at Zen's default theme right now, and I understand that you're supposed to tweak the CSS files in the starterkit to begin building a more substantial sub-theme, but what if I wanted to change the layout of the page altogether?

Currently the Zen theme has the regions laid out something like this (please pardon the massively crude drawing, I just wanted to illustrate something):

And if I wanted it to be laid out like this instead:

Which of the theme files am I supposed to edit/hack? I'm assuming it's either page.tpl.php or html.tpl.php. Or is this something that's supposed to be done with CSS?

Like Countzero said, regions is the Drupal way. If we have a look at the seven.info file of the Drupal theme Seven:

regions[content] = Content
regions[help] = Help
regions[page_top] = Page top
regions[page_bottom] = Page bottom
regions[sidebar_first] = First sidebar
regions_hidden[] = sidebar_first

You could simply add your banner here.

regions[content] = Content
regions[banner] = Banner
regions[help] = Help
regions[page_top] = Page top
regions[page_bottom] = Page bottom
regions[sidebar_first] = First sidebar
regions_hidden[] = sidebar_first

page.tpl.php would be the best place to print your banner, again we have a look at the Seven theme.

  <?php print $breadcrumb; ?>
  <?php print render($title_prefix); ?>
  <?php if ($title): ?>

<?php print $title; ?>

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

<?php if ($page['banner']): ?>

<?php echo $page['banner']; /* echo is faster then print */ ?>

<?php endif; ?>

  <?php if ($secondary_local_tasks): ?>

<?php print render($secondary_local_tasks); ?>

  <?php endif; ?>

    <?php if ($messages): ?>

<?php print $messages; ?>

    <?php endif; ?>
    <?php if ($page['help']): ?>

        <?php print render($page['help']); ?>

    <?php endif; ?>
    <?php if ($action_links): ?>
<?php print render($action_links); ?>
<?php endif; ?>
    <?php print render($page['content']); ?>

    <?php print $feed_icons; ?>

Hope this helps. Of course this is absolutely basic stuff and should only help you getting started.


How to make link unchangeable when using Pathauto? Link for each node is made with Pathauto based on several fields.
Those fields are required so when user makes the node first time, link is generated.

I would like to leave these links unchangeable if user changes something later in those fields (which is needed).

I consider this would be better solution then auto301 each link as this would cause thousands of them later on which is bad for SEO.

How to make link that is created first time by Pathauto unchangable even if the user changes fields that are part of pathauto tokens ?

This is an option in the pathauto settings (Configuration » Search and metadata » URL aliases » Settings) under Update action. Set it to Do nothing. Leave the old alias intact. and pathauto will not update the path alias after its initial creation.


Add product thumbnail to user/%/purchased-files? I've managed to add an extra field in the Purchased Files page, as well as hide the address limit, however I cannot figure out how to actually get the product thumbnail in there, like there is on the cart page. Below is what I'm working with so far, any ideas how to get the image associated with that file in the empty field?

You need to change page callback for path user/%/purchased-files in hook_menu_alter() and your custom callback should be based on code of uc_file_user_downloads() function, you need to change it, add new column with product image. I guess you need to change query in that function to get more data from 'uc_file_products' table about the product id, and based on that you can get all product info etc


How do I add classes to form elements in the theme layer? I want to do it in template.php. The form ID is page_node_form, and there are six form text fields. The default class is "form-text."

I want to add "text1," "text2," etc after "form-text" to each input text class. How can I do it?

This is the HTML:

<input gtbfieldid="10" id="edit-field-14sq-und-0-value" name="field_14sq[und][0][value]" value="" size="12" maxlength="10" class="form-text" type="text">
<input gtbfieldid="10" id="edit-field-14sq-und-0-value" name="field_15sq[und][0][value]" value="" size="12" maxlength="10" class="form-text" type="text"> ....

This is an ideal situation for a preprocess function.

I don't have Drupal 7 working to test at the moment, but something like this in your template.php should do the trick.

function mytheme_preprocess_textfield(&$vars) {
  static $counter = 0;
  $counter++;
  $vars['element']['#attributes']['class'][] = 'test' . $counter;
}


How can I get documentation on a variable listed in the Features UI provided by Strongarm? When looking through the list of variables provided by Strongarm, there are several that sound like they might be useful to include but what they actually refer to is impossible to guess from the name alone (e.g., mail_system).  How can I quickly look up unknown variables to see what it is that they do?

Unfortunately, this is a shortcoming of the Variables system in Drupal: there is no centralized place documenting what they do. This is one reason why it is recommended that modules implementing their own advanced configuration (more than a few key-value pairs) do so using their own tables in hook_schema(), where everything can be documented. That having been said, you can grep around for where they're set/read from your Drupal root:

grep -rn 'variable_[gs]et(' . | grep 'foo_variable'

By checking the documentation for the functions in which they're set, you can typically glean their purpose.


How can get five star rating data in drupal 6 services views? i am using drupal 6.x, added five star(fivestar module) rating functionality to a node in my site.
Everything working fine but i want to users rated data in drupal json services for mobile development, In json services i m getting nodes every data except rating.. so can you please help me. How can i get the users rating data in json services(Services_view module).

Thanks in advance.

You can use Services views module to achieve this,

Procedure :

Using services views you will need to add all your required fields on your views.

Step 1: For adding new view navigate to

[your-site]/admin/structure/views/add

Step 2: Adding your fields

You will fetch the resource as below,

http://example.com/<endpoint path>/views/<view name>


hook_block_view_MODULE_DELTA_alter gets fired twice I'm trying to change the content of a block when a specific node is displayed. The code works fine.
BUT
the hook custom_block_view_block_1_alter gets called twice.
that is GOT MY NODE is displayed twice.
How come?

<?php
/**
* Implementation of custom hook_node_load
*/

$count=0;
function custom_node_load($nodes,$types){
  foreach($nodes as $key =>$node){
    if($node->type=="person"){
      drupal_set_message("Person Node loaded");
      $customised_value="WAHAHAHAHAHAHAHAHAHAHAHA";
      $node->customised = $customised_value;
      variable_set('my_person_node',$node);
      drupal_set_message("WAHAHA");
    }
  }
}

/**
* Implementation of hook_block_view_MODULE_DELTA_alter
*/
function custom_block_view_block_1_alter(&$data, $block) {
  global $count;
  if($block->delta=="1"){
    ++ $count;
    $block->title="HERHE";
    $my_nodes=variable_get('my_person_node');
    dpm($block);
    $data['subject']="HEHE";
    $data['content']="<strong>".$my_nodes->customised."</strong>";
    drupal_set_message("GOT MY NODE".$count);
  }
}

I faced a similar issue recently and the problem was the team had created both a module and a theme with the same name so Drupal was executing the same hook twice (once for the module and once for the theme). Renaming the theme solved the problem.


Change timezone display format in user edit page In drupal 7 timezone field in user edit will be like Asia/Kolkata: Friday, October 9, 2015 - 17:24 +0530. I want to display it like Asia/Kolkata. I have tried the method specifed in https://drupal.stackexchange.com/a/177073/50991 but not working. How to change the display format

You can do it with below code

    function yourcustomodulename_form_alter(&$form, &$form_state, $form_id) {
    if($form_id=='user_profile_form'){
 $form['#after_build'][] = 'yourmodulename_after_build';

    }
    }
function yourmodulename_after_build($form, &$form_state) {
      $options = array();
      foreach(timezone_identifiers_list() as $timezone) {
        //$options[$timezone] sets the value for date_default_timezone select
        //$timezone set the display for select
        $options[$timezone] = $timezone;
      }
      $form['account']['timezone']['timezone']['#options'] = $options;
return $form;
}


How to access services_views the correct way? I am trying to fetch some views with the services_views module. Sadly enough I keep getting the response: "404: Not found: Display  on view my_view_name could not be found".

I am using Views 3 and I defined for test a view with a 'page' display id. (default display id is not a "default" anymore)

I know that I have to pass the display_id argument but simply can't make it work.

Here is the calls I am trying to use:

http://www.mywebsite.com/rest/views/my_view_name.json?display_id="page"
http://www.mywebsite.com/rest/views/my_view_name.json?display_id=page
http://www.mywebsite.com/rest/views/my_view_name.json?parameters[display_id]="page"
http://www.mywebsite.com/rest/views/my_view_name.json?args[display_id]="page"

In the resource definition for the service it is clear that display_id has to be passed as an argument.

'args' => array(
  'view_name' => array(
    'name' => 'view_name',
    'type' => 'string',
    'description' => 'The name of the view to get.',
    'source' => array('path' => '0'),
    'optional' => FALSE,
  ),
  'display_id' => array(
    'name' => 'display_id',
    'type' => 'string',
    'description' => 'The display ID of the view to get.',
    'source' => 'param',
    'optional' => TRUE,
    'default value' => 'default',
  ),...

Is there anyone who managed to make this work?

Thank you.

On a Drupal.org issue page for this module, someone suggests the following for the 7.x version.

The arguments are passed in the usual url format, for example:
http://example.com/my_endpoint/views/view_name?display_id=default&args=123&offset=0&limit=10&return_type=FALSE

Multiple arguments can be used like this:
http://example.com/my_endpoint/views/view_name?display_id=default&args[0]=abc&args[1]=123&offset=0&limit=10&return_type=FALSE

I've been trying to get this working on 6.x but haven't succeeded yet.


Override Search module's textfield CSS ID this is what I am using to override the Search module's submit button's CSS ID:

function hook_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'search_block_form') {
        $form['actions']['submit']['#attributes']['id'][] = 'custom_css_id';
    }
}

Now I want same thing for the textfield input.

It is the same thing as you did above

$form['search_block_form']['#attributes']['id'][] = 'custom_css_id';


Notifications during a file download As a newcomer to Drupal 7, I'm trying to understand how auditing and events can be used together.

For example, I have a content type of document, which is basically a name field and a file.  I would like an email to go out whenever an authenticated user downloads the document and also have a report that shows how ( and when ) downloaded the document.  Does anyone have any suggestions on the best way ( modules, design patterns, etc ) to go about setting this up?

Thanks in advance

Download Count can produce file download statistics.

Additionally, because Download Count has Rules integration, you can create a Rule that will send an e-mail when a file is downloaded.


How to transfer data between 2 fields I have profile 2 installed. I added a new field called "maiden name" to my profile form using the "add existing field" option. I had previously created this field in the default user registration form.

Now I want to delete the field (maiden name) from the user registration form. Please how can I transfer the data/values to the new field in my profile 2 form.

Thank you.

This in untested code so you will need to adjust the paths to get the correct values however it shows the general approach to take:

$uids = db_query("SELECT uid FROM user WHERE status=1")->fetchCol();

foreach($uids as $uid) {
    $account = user_load($uid);
    $profile2 = profile2_load_by_user($account, 'profile_2_type_name_here');
    $profile2['maiden_name']->field_maiden_name[LANGUAGE_NONE][0]['value'] = $account->field_maiden_name[LANGUAGE_NONE][0]['value'];
    profile2_save($profile2);
}


Check when the last time someone visited a specific node I need to make sure my users are visiting a specific node. What could I accomplish this?

A counter would be nice (e.g. "viewed three times by User234 in the past week"). Would that be hard to implement?

The Statistics module that is part of Drupal already get that information. Its hook_exit() implementation contains the following code.

  if (variable_get('statistics_enable_access_log', 0)) {
    drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION);

    // For anonymous users unicode.inc will not have been loaded.
    include_once DRUPAL_ROOT . '/includes/unicode.inc';
    // Log this page access.
    db_insert('accesslog')
      ->fields(array(
      'title' => truncate_utf8(strip_tags(drupal_get_title()), 255),
      'path' => truncate_utf8($_GET['q'], 255),
      'url' => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '',
      'hostname' => ip_address(),
      'uid' => $user->uid,
      'sid' => session_id(),
      'timer' => (int) timer_read('page'),
      'timestamp' => REQUEST_TIME,
    ))
      ->execute();
  }

The data contained in that table are reset after 72 hours. statistics_cron() contains the following code.

  // Clean up expired access logs (if applicable).
  if (variable_get('statistics_flush_accesslog_timer', 259200) > 0) {
    db_delete('accesslog')
      ->condition('timestamp', REQUEST_TIME - variable_get('statistics_flush_accesslog_timer', 259200), '<')
      ->execute();
  }

The Statistics module has a setting page (admin/config/system/statistics) that allows you to decide when the access logs are discarded; you can choose to discard then when they are older than 1 week.

The Views module has code to expose in a view the data saved from the Statistics module; you can add a field to expose the number of times a node is viewed in a view.

Alternatively, you can create a custom module basing on the Statistics module's code. In this case, you would need to implement the code for integration with the Views module, if you need it.

As side note, hook_exit() is probably going to be removed from Drupal 8; if you are using it in a Drupal 7 module, you will need to change your code when porting it to Drupal 8.


Published-Draft articles are not searchable I am using Drupal 8.3.x and Search API 8.x-1.5.

I am new to Drupal and Search API. I have a clarification on Search functionality.

I have created a article where Title and Body fields are indexed. I have published the article.

When I search for the keyword of Title or Body, article found in search results.

After that I modified the article and saved as draft.

When I am trying search the article with modified text. The article is not returning in the search results.

Can someone please let me know, if this a known issue with the search or it is the expected behaviour? If yes, any specific reason for implementing like this?

is this a known issue with the search or it is the expected behaviour?

It’s very much the expected behaviour

  If yes, any specific reason for implementing like this?

Yes. Only published content should be visible, unpublished content should not. That’s the whole point of the distinction between the two states.

If unpublished content appeared in search results (without manual intervention if there was an edge-case requirement  to do so), that would be a major bug.


Use conditions in views rewrite I have a view that shows an overview of "experiences".
The problem I am having is they switch HTML on every row.

so the first will be:

Image text

then the second will be:

Text Image

I tried using conditionals in the rewrite result.
But they seem to not work as shown below:

This outputs:

Is there a fix or workaround for this?

The following answer is from Drupal 7 post, long time ago but I guess the methodology is still the same.

Basically in your views template you can specify that logic.

https://www.drupal.org/node/1932102#comment-7182640

if (row is even)
  // display order 1
else {
  // display order 2
}

Update: There is port of the views conditional module available on github.

https://github.com/anandtoshniwal93/views_conditional/blob/master/README.md
You can reuse it in your view like that....

Views Conditional field (if row is even)

  print rewrite field 1 (which is the first combination order)

Viws Conditional field (if row is odd)

  print rewrite field 2 (which is the second combination order)


Adding custom code on flagging a node I am using the Flag module on my site. In which function should I add my custom code that is executed when users click on the flag button?

If you enable the Trigger and the Flag actions modules, you can assign a group of actions that is executed when a user or a node is flagged by a user.
Flag integrates also with Rules, and it allows to execute rules when a flag is used for users or nodes.


How can I bulk update the language for all content? I have a site that has been duplicated from an english site and has been translated into Italian.

I installed Italian as a language and have set it as default. However, all of the nodes created in the cloned site are still set to "english".

How can I bulk update the language for all content, either programmatically or directly with SQL?

Load the nodes entities and set its langcode column

For example:

$w_node = entity_load('node', $nid);
$w_node->set('langcode', $data_langcode);
$w_node->save();

To do it in bulk, i guesing that you should create a new action to be available in the defaults bluk operations for the admin/content view


How to add a javascript function after uploading file I make a form using FAPI, and this form contains a file managed field. I want to show an alert after uploading the file ("uploaded successfully"), and a confirmation ("Are you sure you want to delete file") when deleting the file.

This my code.

$form['my_file_fid'] = array(
  '#type' => 'managed_file',
  '#title' => t('Files'),
  '#default_value' => variable_get('my_file_fid', ''),
  '#upload_location' => 'public://',
);

I tried to add #file_value_callbacks, but I don't know how to use it.

I tried to make a javascript just to alert when I click upload,remove button but it doen not work I tried to make it general to all input to check that js is correct now all inputs are clickable but upload and remove button not

jQuery(document).ready(function() {
         jQuery('input').bind('click',function() { alert("hi") });
 });

I make this js to check jquery ajaxSuccess function

You could just bind something to the jQuery ajax success event on the page where your form is displayed.

You can bind ajaxSuccess to any jQuery object, try something like this if you're experimenting:

<script>
  (function ($) {
    $(function () {
      jQueryObject = $({});
      jQueryObject.ajaxSuccess(function(event, XMLHttpRequest, ajaxOptions) {
        /* do something whenever an ajax call is successful */
      });
    });
  })(jQuery);
</script>


Is there any way to display a taxonomy sorted by another taxonomy? I'm working on a homepage for a student paper and I'm needing some way to display 3-4 arbitrary pieces of content from each section every week (I.e., top stories) in a panel for each section.

In order to do this, I'm thinking I'll use the Weight module to create a list of top stories for the week via that Taxonomy, which I would then like to group by another taxonomy term, "section".

How would I go about doing this?

Many thanks!

I would look into the Flag module.  With it, you could flag certain content and then use Views to show just that content. You could also create different flags for different sections, etc.


How do I use the Rules module to unpublish content when End Date is hit? I have a Content type called Event, has a Start Date and End Date.

How do I use the Rules module (version 8.3.0-alpha1) to:

Publish the Event on the Start Date and
Unpublish it on the End Date?

My priority is to Unpublish the content when the End Date is hit.

Note: If Rules isn't the way to go, what would be a better way to unpublish a piece of content based on a supplied End Date?

I have this functionality on a D7 site I run, and we use the Scheduler module instead. Looks like there is an alpha release for D8 you could try: https://www.drupal.org/project/scheduler


Image Gallery not loading random thumbnails This has been happening for... perhaps for years.

I have an image gallery here http://windwanderer.com/image

When I load any page of this gallery, only SOME of the thumbnails are loaded and the rest show the default text.

Which thumbnails load and which do not changes with each load. Try it, go to the link above and see which images are shown (you may need to scroll down) then click "reload" on your browser. Some of those that looked to be unavailable will be loaded and some of those that loaded correctly the first time will now appear as thought the image can't be found.

The error occurs in Firefox, Midori, and even Dolphin browser running on Android phone!! Haven't tested it with iexplorer.

I believe this problem may have persisted over an upgrade from Drupal 5.x to 6.x

My guess was that it had something to do with the cache. Here is what I have done:

I've emptied it
turned off page caching
rebuilt the derivative images multiple times

... yet the problem persists.

I would really appreciate any help. Please be patient, though, as I don't sit at my computer every day and it may take me time to test solutions.

Cheers
Jesse

  SITE STATS: Drupal Version: 6.x-2.9 Image Gallery Version: 6.x-1.1 Was
  using acidfree albums in 5.x but changed to image gallery (views) when
  upgraded to 6.x The view states "Overridden Node view: image_gallery"
  Views Version: 6.x-2.16 Was using image toolkit: "GD2 image
  manipulation toolkit" but have just changed to "ImageMagick Toolkit"
  in attempts to solve this problem.

I just checked out your site and all images showed up. It took some time, but all images did show up. Looking at it further, it appears that you have your file system set to private. Go to admin/settings/file-system/settings and change the Download method to public. If this is not an option, then I would look at implementing xsend in apache and installing the drupal module http://drupal.org/project/xsend

Unless you have some VERY good reasons to set your file system to private, I highly recommend using a public file system.


How to change user info with a rule when Points are granted to user (using userpoints module)? I need to create a rule to change info of a user when this user is granted with points using the http://drupal.org/project/userpoints module.

I need the rule to have a condition and action like:

if total points of the user are greater than 1000 --> then set the field passed to 1

The field passed is a field that I added at admin/config/people/accounts/fields

My problem is that I can't load the Total points of the user in the conditions of the rule

I already have the userpoints_contrib module enabled.

I think that was added recently in dev: drupal.org/node/1109992


Remove the 'read more' and 'Add new comment' links on the home page How do you remove or modify the list of links shown after the content?

In your theme's template.php file, add this snippet:

function THEMENAME_preprocess_node(&$variables) {
  if ($variables['is_front']) {
    unset($variables['content']['links']);
  }
}

Remember to clear the cache afterward. And replace THEMENAME with your actual theme.


How To get transaction details in commerce checkout complete page Can anyone please help to get the transaction details in commerce checkout complete page. I could get using hook_commerce_checkout_complete($order). I can show the success/Error transaction and order details in drupal_set_message. But Exactly I need show in checkout complete page instead of message box. Please help how to do. Thank you.

In general, for Drupal 7, you could do the following:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function  MODULE_form_commerce_checkout_form_complete_alter(&$form, &$form_state, $form_id) {
  $order_id = $form_state['order']->order_id;
  // Use the entity field query to get transaction entities.
  $query->entityCondition('entity_type', 'commerce_payment_transaction')
    ->propertyCondition('order_id', $order_id);
  $result = $query->execute();
  if (!empty($result) && !empty($result['commerce_payment_transaction'])) {
    // Load the Payment Transactions
    $transactions = commerce_payment_transaction_load_multiple(array_keys($result['commerce_payment_transaction']));
    $form['payment_status']['#markup'] = '
' . t('Payment Pending') . '
';
    foreach ($transactions as $transaction) {
      if ($transaction['status'] == "success") {
        $form['payment_status']['#markup'] = '
' . t('Payment Received!') . '
';
        break;
      }
    }
  }
  else {
    $form['payment_status']['#markup'] = '
' . t('Error. No Payment Transactions.') . '
';
  }
}


Errors when running Cron I can't run cron; see the video capture I created.

If I click "Run cron" in the admin menu I'm redirected to another URL.

If I go to mysite.com/cron.php, I get the "Access denied" message.

If I click "Run cron" in the admin menu I'm redirected to another URL.

You have a node using the PHP filter, and calling drupal_goto(). That node is then indexed, the PHP code is executed, and you are then redirect. Don't do that ;)

  I can't run cron; see the video capture I created.

You need to specify a cron key when accessing cron.php directly. You can find a link with the key on your Status report page (admin/reports/status).


Form states with "and" and "or" conditions Using form API in D7, I need to use from states to setup a visible input with this condition :

field1 = value A AND (field2 = value B OR value C OR value D)

Something like this, but this example doesn't run :

'#states' => array(
      'visible' => array(
        array(':input[name="question_inhabitant_type"]' => array('value' => 'owner')),
        'AND',
        array(':input[name="question_building_type"]' => array('value' => 'house100')),
        'OR',
        array(':input[name="question_building_type"]' => array('value' => 'house150')),
        'OR',
        array(':input[name="question_building_type"]' => array('value' => 'house200')),
      ),
    ),

Any idea?

You can use or/xor in form states. For and, continuation of the conditions is enough. For example your code the condition can be written as:

'#states' => array(
  'visible' => array(
    array(':input[name="question_inhabitant_type"]' => array('value' => 'owner')),
    array(
      array(':input[name="question_building_type"]' => array('value' => 'house100')),
      'or',
      array(':input[name="question_building_type"]' => array('value' => 'house150')),
      'or',
      array(':input[name="question_building_type"]' => array('value' => 'house200')),
    ),
  ),
),

Note: jQuery 1.7 doesn't support OR/XOR's for #states. So, make sure you have latest jQuery version on you site (>1.7).

Unfortunately the above code didn't worked as expected. Please help through your comments to correct it. Also meanwhile you can try this code:

'#states' => array(
  'visible' => array(
    ':input[name="question_inhabitant_type"]' => array('value' => 'owner'),
    ':input[name="question_building_type"]' => array(
      array('value' => 'house100'),
      array('value' => 'house150'),
      array('value' => 'house200'),
    ),
  ),
),


Meaning of Error: Cannot redeclare bootstrap_preprocess_region() I'm setting up a Drupal Bootstrap subtheme, and ran into this fatal error when trying to clear my cache. Something seemed to want to redeclare a bootstrap preprocess function:

  Error: Cannot redeclare bootstrap_preprocess_region()

This caused the whole site to go down and Drush to fail any time I tried to clear or rebuild the cache.

Why is this happening?

This was happening because I'd copied .func.php files from the templates folder of the Bootstrap parent theme into my base theme alongside .tpl.php files. Bootstrap is relatively unusual in that it has files in the templates folder alongside tpl files that will break the site if they're treated like standard theme tpl files.

While the .tpl.php files are to be copied as normal, to override the contents of the other files, you are expected to copy their appropriate contents into your subtheme's template.php file or into a new .func.php file, and substitute your subtheme name for the bootstrap part of the function name.

There's some more information on the theme registry docs page.


Is there a way I could display a token (for exmaple user ID) as a default field content to a content type? Is there a way I could display a token (for exmaple user ID) as a default field content to a content type?

Id like to display a node form to users
/node/add/content type

when a user goes to that page the field "name" automatically displays the user id.

name: [user:uid] - something like that

Is it possible, If so, how can I achieve this?

Thanks

Do you want it to be editable or not?

Either way, its going to take a small custom module with hook_form_alter or hook_form_FORM_ID_alter if you want to target a specific form.

If you want it editable:

http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#default_value

If you want it set at a value:

http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#value

Start with downloading and enabling devel and a small module with just this to get a list of all the form elements on a page:

function YOUR_MODULE_NAME_form_alter(&$form, &$form_state, $form_id) {
  dsm($form_id);  // print form ID to messages
  dsm($form);  // pretty print array using Krumo to messages
}


Facet pretty path providing no result I have used commerce kickstart and created product display page with facet filter.I have used Facet API Pretty Paths module to use simple URL.But it makes no result behaviour.Without facet pretty path, facet filter working good, but URL makes quite complex.

Unfortunately this is a bug in Facet API Pretty Paths module.
take a look at https://www.drupal.org/node/2423029 and ask maintainer to solve or suggest a solution for it.


in drupal 7 's view, how to comment without redirecting to content type page? I make a view for a specific content type, the path of content type and the path of the view are different. Now I put a form into the view, in order to comment on that content type. However whenever I comment on the view page, the view page will redirect to the path of content type, so the question is how can I comment without redirecting to the content page but staying on the view's page, perhaps working with ajax?

There is an Ajax comments module you can use to post comments without refresh and this post shows how to combine it with views.


Entityform Submissions in a view I have an EntityForm referenced on a node and I need to show submissions on a view where :

Node Author can view all submissions
Submitter view his own Submission (for edition purpose)

How can I do so?

Ended up using two blocks with contextual filters, one that shows up for the node author and the other for Submitters.


Filtering a views result two month ago from now I'm using drupal 7.
I building a views with date filter but how to filter the nodes between the date i will select and two months earlier?
I tried with relative date value but i did not knew how i should set it correctly.
Thanks.

enable the Date Views sub module in the DATE module. Then goto views and expose the date field . There you can set the operetor between and the 2 dates there


how to get the original entity on hook_entity_presave? i actually need it for the content_moderation_state entity

 function hook_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
if ($entity->getEntityTypeId() !== 'content_moderation_state' ) {
    return;
}
$moderation_state = $entity->get('moderation_state')->getString();

 //code to get the original entity moderation state

Use $entity->original to get the original entity:

function hook_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {

  if ($entity->getEntityTypeId() !== 'content_moderation_state' ) {
    return;
  }

  $moderation_state = $entity->get('moderation_state')->getString();

  //code to get the original entity moderation state
  $moderation_state_original = $entity->original->get('moderation_state')->getString();


Drupal sub directory url I just started using Drupal today and I couldn't help but notice (or I'm blind) there is no way to add a sub directory style URL besides using an alias. I want to have a category, for example, named "lessons" and then the next part of the URL would be the title of the lesson.

e.g. http://www.example.com/lessons/lesson1

It just seems like there should be a better way to accomplish this rather than using aliases manually. So my question is, is there a way to do this without aliases? I mean automatically so when I add new content (an Article), I can select the appropriate category it should be in. Thanks

http://drupal.org/project/pathauto

this module do what you want ... this module generate url automatically depending on the node title... and you can add prefix or suffix to the automatic url path that generated by this module

if you are using drupal 6 then you can configure this module from

http://yoursite.com/admin/build/path/pathauto


D7 Views: Rewrite multiple field into one with custom separators This is a follow-up to a recent question of mine, that was solved easily. The construct is very similar, but this time I need to add conjunction characters (in my case a comma and a space: ", ") when rewriting the field.

Here's the setup: In a node type, I have three fields: (1) methods, (2) geography, (3) keywords. All three fields are textareas where comma-separated values are entered. These fields are hidden on normal node view (node type -> manage display), but there is a views block showing these values.

Now, I want all of the fields' content to appear as a single field with a label with additional commas between.

An example: a node has the following values (1) methods: "evaluation, regeneration" (2) geography: "Denmark, Germany" and (3) keywords: "rivers, restoration".

If all (or at least keywords) fields are filled, the desired result is easy to achieve in the block:

Methods: no label; exclude from display; no result behaviour: hide if empty, hide rewriting if empty; rewrite results: ", [methods]"
Geography: no label; exclude from display; no result behaviour: hide if empty, hide rewriting if empty, no result output: "[methods]"; rewrite results: ", [geography][methods]"
Keywords: label "Keywords"; no result behaviour: hide if empty, hide rewriting if empty, no result output: "[geography]"; rewrite results: "[keywords][geography]"

For the above example this produces

Keywords: rivers, restoration, Denmark, Germany, evaluation, regeneration

Thus, the required commas (between restoration and Denmark as well as between Germany and evaluation) are added correctly. This also works, if either methods or geography are empty or even both, output looks like:

Keywords: rivers, restoration, evaluation, regeneration
Keywords: rivers, restoration, Denmark, Germany
Keywords: rivers, restoration

Now the culprit. If keywords' field is empty, there are two scenarios.

Both geography and methods are empty, also. Then the whole (rewritten keywords) value is also empty and label is not displayed.
Either or both geography and method have values. Then there is a superfluous comma at the start of the value like

Keywords: , Denmark, Germany
Keywords: , evaluation, regeneration
Keywords: , Denmark, Germany, evaluation, regeneration

The actual question:
How should I setup the view to avoid this starting comma if keywords' field is empty?

The only easy way I found is to make the keywords' field required so there is always a value present. But I'd like to set it up without marking fields mandatory and without changing the fields' types or widgets.

You could rewrite the output of the field with your comma (but without conditions), then exclude from display and use a global textfield to output the field again with your conditions, so if the field is empty it won't show the comma.


Can't connect to a remote MySQL during installation, drupal uses unix_socket instead of host? I'm installing a drupal site on a cloud, which has a remote database cloud service.

But I found that drupal seems ignore the host I give and use unix_socket to connect the remote database.

Here is the Set up database screen during installation. I'm sure database name, username and password are correct. I have try ip address and domain name in the host field. The socket field leaves empty.

And I got:

  Failed to connect to your database server. The server reports the following message: SQLSTATE[HY000] [2002] Invalid argument.

I'm not familiar with PHP and mysql, I don't know a better way to find out what Invalid argument is. I So I do some grep and add some print_r() in [drupaldir]/includes/database/database.inc:

$driver_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
print_r($dsn);print_r($username);print_r($password);print_r($driver_options);
// Call PDO::__construct and PDO::setAttribute.
parent::__construct($dsn, $username, $password, $driver_options);

This is what I got (add a few line break, and replace the real name and password):

mysql:unix_socket=;dbname=demo_db
demo_username
demo_password
Array ( [1000] => 1 [20] => 1 [3] => 2 )

Is this mean, Drupal installation ignores the host what ever I give and just use unix_socket even it's empty?

I think I have located this issue. includes/database/mysql/database.inc, line 32:

// The DSN should use either a socket or a host/port.
if (isset($connection_options['unix_socket'])) {// will be TRUE if unix_socket is ''
  $dsn = 'mysql:unix_socket=' . $connection_options['unix_socket'];
}
else {
  // Default to TCP connection on port 3306.
  $dsn = 'mysql:host=' . $connection_options['host'] . ';port=' . (empty($connection_options['port']) ? 3306 : $connection_options['port']);
}

$connection_options['unix_socket'] will be an empty string if we leave it empty on the page. So this test will be TRUE. Replace isset with !empty solve this issue:)


How to have node id value set depending on some other id? I have database table which I need to import it in drupal database (basically create a node for each row of database table ) .
 The non drupal database has mim Id .
I want to create a node which would have the mim Id == node id
So in all, how can I achieve such that Drupal's ID node will be SAME as article ID (this ID is used in an external media CDN server).

I tried looking at the CDN module but could not find a solution for the same

Take a look at migrate module and this hands-on guide (disclaimer: I work for that company, so to balance: lullabot's guide ) Both are good to understand everything that's necessary for what you asked.

You might want to consider creating a field_old_node_id field to ease on the transfer if you can't set the ID through this, and use Pages module to create a separate /node/%nid page that uses that field instead to display the node.


Access a field from page.html.twig template I would like to display an image above the page header.
The image is stored in a field (its name is “image”) related to a node (its type is “article”).
I can display {{content.field_image}} using the node--article.html.twig template.
But as the

{{ title }}

lives in the page-title.html.twig template I can no longer access the image.

Can someone help me finding the right way to write a preprocess function?
I already used

function [my_theme]_preprocess_page(&$variables) {
  $site_config = \Drupal::config('system.site');
  $variables['site_name'] = $site_config->get('name');
  $variables['site_slogan'] = $site_config->get('slogan');
}

But I can't find a way to do the same again with my image

The page title has its own preprocess hook. You may want to use hook_preprocess_HOOK() to add your image to the variables. As it is using the page-title.html.twig template, the theme registry HOOK is called 'page_title'.

Following is an excerpt from a theme's page title preprocess function of a D8 theme that is adding the URI of an image with an image style applied along with the page title. Maybe you find it useful as inspiration for your use case:

use Drupal\image\Entity\ImageStyle;

/**
 * Implements hook_preprocess_HOOK() for page title images.
 */
function mytheme_preprocess_page_title(array &$variables) {
  $image = '';

  // Load the image entity from current route.
  if (
    !empty($node = \Drupal::routeMatch()->getParameter('node')) &&
    $node->getType() == 'page' &&
    $node->hasField('field_image') &&
    $image_entity = $node->field_image->entity
  ) {
    $style = ImageStyle::load('title_image');
    $image = ($style->buildUri($image_entity->getFileUri());
  }

  $variables['image'] = $image;
}


How does drupal updates check work? I don't have an external crontab set up for my Drupal site.  How can Drupal search for updates in this case?

There should be a crontab task for Drupal. If there is none, it falls back to Poormanscron - integrated into Drupal core since 7.x

  The module inserts a small amount of JavaScript on each page of your site that when a certain amount of time has passed since the last cron run, calls an AJAX request to run the cron tasks. However, this approach requires that your site gets regular traffic/visitors in order to trigger the cron request.

When check is initiated, it loops over modules and checks their status from URLs determined in function _update_build_fetch_url define at line 287* of update.fetch.inc file, in update core module.

For more details, examine update core module, code is pretty well documented.

Information valid for Drupal 7.25, may slightly change with version.


Getting menu links: correct chain of API functions In my module, I need to create sort of a menu block consisting of certain menu items collected from various menus, and flattened into one level.

I'm not sure about the correct chain of the Menu API functions to call. My first attempt was as follows:

function _MYMODULE_block_view(){
  $html = '';

  $menu_link = menu_link_get_preferred('node/287');
  $html .= theme('menu_link', $menu_link);
  dpm($menu_link);
  return $html;
}

but it raises an error about several #attributes missing, so I guess this is not the right kind of object to get markup from. The API docs don't really help in understanding what kind of objects/parameters are returned/expected by functions, hence the question.

Edit:

Having given what Drupal complained about, the code now is as follows:

function _MYMODULE_block_view(){
  global $language;
  $langcode = $language->language;

  $html = '';

  $paths = array(
    'node/287',
    'node/3',
  );

  foreach($paths as $path){
    $translations = i18n_get_path_translations($path);
    if(!empty($translations[$langcode])){
      $i18n_path = $translations[$langcode]['href'];

      $menu_link = menu_link_get_preferred($i18n_path);
      $link = array(
        '#theme' => 'link',
        '#text' => $menu_link['link_title'],
        '#path' => $path,
        '#options' => array('attributes' => array('title' => $menu_link['link_title'])),
        '#below' => NULL,
        '#title' => $menu_link['link_title'],
        '#href' => $path,
        '#attributes' => array(),
        '#localized_options' => array(),
        '#prefix' => '
',
        '#suffix' => '
'
      );
      $html .= theme('menu_link', array('element' => $link));
    }
  }

  return "
$html
";
}

It does not spit out errors but... should I really trust it?

Since you're using menu_link_get_preferred() I'm guessing Drupal 7 here...

Theme functions have changed, and parameters now need to be named in an associative array passed to the theme function. So per the theme_menu_link() docs:

$html .= theme('menu_link', $menu_link);

becomes

$html .= theme('menu_link', array('element' => $menu_link));


Bypass Redirect Rule which acts on user login, while logging through one time login link I have a redirect rule in place which takes user to home page after login, I need to bypass this rule when a user logs in with one time url login link which is sent in account creation email.

I am assuming there should be condition I need to put in the redirect on user login rule,but I am not finding it.I tried by putting a condition that if the site current page url is account one time login url then rule should not trigger,but its not working as the condition does not satisfy.

Got answer for it https://drupal.org/node/480584 #25.
In brief the key was text comparison in the current page url to match if user/reset exists.

{ "rules_am_redirect_user_logins" : {
"LABEL" : "AM redirect user logins",
"PLUGIN" : "reaction rule",
"REQUIRES" : [ "rules" ],
"ON" : [ "user_login" ],
"IF" : [
{ "NOT text_matches" : { "text" : [ "site:current-page:path" ], "match" : "user\/reset" } }
],
"DO" : [ { "redirect" : { "url" : "user-home" } } ]
}
}


Drupal 7 views Contextual filters with Blocks, default value doesn't work properly , wield I have a view created that show content based on the url:
eg:
domain.com/projects/[username]/[projectname], which shows a project of a specific user, that works well.
Additionally, I want to show the related projects of this user on the sidebar, so I create a block view, using the Contextual filters and the default value.

because my url is projects/username ,By using the default value -> raw value from URL,  so I set the path component as 2. but that doesn't work for me.
eg:
suppose my username is  "abc".

in the preview, if the url path is "projects/abc", it doesn't show anything although the username is in the 2ed component of url path.

if the url path is "abc/*", it will show the related content, meaning as long as the username is in the first argument of the url path, it works.

I don't what happens, it seems that configuration of path component as 2 doesn't work. I am so puzzled , what happened ?

If your first contextual filter is your username filter then it will respond to the first argument passed in the preview textfield, no matter what default value you have specified. Your default value is for when an argument is not passed. So, entering "projects/abc" in the Preview with contextual filters box will pass 'projects' to your username filter, but passing a valid username as the first argument as in "abc/*" will work correctly.

It sounds like you've got it set up correctly to me. Have you tried deploying your block view on an actual page?


Is there an easy way to load a related entity from an entity? I have a content entity that references another entity, ie:

public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
  $fields = parent::baseFieldDefinitions($entity_type);

  $fields['other_entity_id'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Other Entity'))
      ->setSetting('target_type', 'other_entity')
      ->setDisplayOptions('form', array(
        'type' => 'options_select',
        'weight' => 0,
      ))
      ->setDisplayConfigurable('form', TRUE);

Is there an easy way for me to load the other entity from the entity that references it?

You can use the entity field property. ie:

public function getOtherEntity()
{
  return $this->get('other_entity_id')->entity;
}


using hook_form_alter on a same form from 2 different modules How will a predefined form behave if we have two different forms that implement hook_form_alter?

I would explain my question by an example, because currently I got a crash on it:

I have a predefined user_login form in user.module

I created two new blocks called author_login and creator_login. Each of these module using the form user_login and adding new validating properties for each form by using function hook_form_alter().

The new validating properties are:

For author_login block: if user doesn't have author role, user will not be logged into system, error: "you don't have author role"
For creator_login block: if user doesn't have creator role, user will not be logged into system, error: "you don't have creator role"

But the problem is: the new login block I created works fine if only one of two modules is enable. If I enable both modules, no user cannot log in to the system through these module.

For example, I have both modules enabled, I go to author_login block and log an user named Mark, who has role Author, to the system, an error message displayed: "the user Mark doesn't have creator role". And similar to creator_login block.

Why does this happen? I thought that the hook_form_alter will alter different properties to each new module we created, make each new form works separately. But from this case I encountered, it seem like the user_login form validate all new properties that I added by using hook_form_alter. And how can I avoid this as I want these two form to work separately?

It sounds like you're altering the same form to provide the additional validation so it is expected that both the author and creator validation checks will be carried out when both modules are enabled.

If you want to continue using the same form for both blocks then I would suggest wrapping the code within your validation callbacks to check which form you are currently validating.


Get order title value from $order variable I have to get order status and order title from $order variable. I can get order status by $order->order_status. But I can't able to get order title. So how to get order title value from $order variable programmatically.

I am using the below hook :

  function hook_uc_order($op, $order, $arg2) {
     if ($op == 'update') {
       if (($order->order_status == 'payment_received') && ($order->title == 'My Product')) {
         // Do something with the $order object.
       }
    }
  }

Here $order->order_status is working individually but $order->title is not working. How to get Order Title?

Looking forward for this answer.

You can get the order title from this method.

   uc_order_page_title($order)

check out all the methods you need for ubecart. ubecart drupal 7 API


How to extend a view plugin style implemented by another module? I have some requirements that leads me to extend the functionality of a views plugin style implemented by a contrib. module by adding some fields and validations in it's configuration form.

I started to implement a custom module to alter this by extending the contrib_views_plugin_style Class implemented by the contrib. module using the views API. I added the fields with no problem but I'm worried about the render method because I don't want to have a copy of the contrib. plus my custom code and I still not sure if this is the best way to do this.

I plan to post this to d.o by posting a patch or maybe another contrib. module but it would be nice if I could keep just the new code and didn't have to have any duplicated code.

Here is the contrib module code:

http://drupalcode.org/project/leaflet.git/blob/refs/heads/7.x-1.x:/leaflet_views/leaflet_views_plugin_style.inc

There is another way to achieve this goal?

PS. I prefer to start without hacking the contrib module but if there is no way to do this it's OK.

First you need to have a my_module.views.inc, which can have basically the same contents as http://drupalcode.org/project/leaflet.git/blob/refs/heads/7.x-1.x:/leaflet_views/leaflet_views.views.inc, but with changed names.

You can leave the handler the same, in which case you need to leave the path the same too. Otherwise you can create your own hadler in my_module_views_plugin_style.inc along the lines of

class my_module_views_plugin_style extends leaflet_views_plugin_style {
   // ...
}

You then only need to define any methods that you want to modify:

function option_definition() {
  $options = parent::option_definition();
  // your changes here
  return $options;
}

You also need a theme file. If you are modifying the display at all, you probably need to just copy the theme file over from the dependency, and change the 'theme' line in my_module.views.inc.


Form Alter: How to check if a node has a Field Type My module provides a field. In hook_form_alter() I need to change only those nodes that have this field set up. (I can't operate use hook_field_form_alter() because it does operates changes for other things than my own field.)

How can check if my field belongs to the node?
Is there an easy function to check if the field type exists in $form?

Otherwise, if I need to look at $form the problem is that I can't know the machine name used for the field by the admin/drupal as it looks like something like $form['my_field_namedbyuser'].

If you are searching for specific field then see the code below

 function hook_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'form_id_name') {
        $abc = array();
        foreach ( $form_state['field'] as $key => $value ) {
            $abc[$key] = $key;
        };
}
    }

From this $abc variable you will get all the field name and then you can check from this array to see if the field you want exists or not using any of the php functions.
For e.g.
you can use array_key_exists('field_name', $abc);


Variable in html.tpl.php This seemingly simple task proved more difficult than I imagined.. I'm trying to get a variable from themename_preprocess_html to my html.tpl.php.

The code I have in my template.php file:

<?php
function themename_preprocess_html(&$variables) {
  $variables['test'] = "Hello world!";
}

And in my html.tpl.php file I have:

<?php print($test); ?>

Unfortunately, the variable isn't displayed in the page. It says:

Notice: Undefined variable: test in include()

I'm trying to do this so I can use node fields to determine variables in my stylesheet.

Is there any way I can print all available variables in my html.tpl.php?

Try using get_defined_vars() to get the list of all the variables on a page.

  get_defined_vars — Returns an array of all defined variables

Source - http://php.net/manual/en/function.get-defined-vars.php


https - Works for the homepage but fails for all other pages Running D7 7.43 on Debian 8 with Apache 2.4.10. Everything seems to be set up properly to run https. I go to my dev site https://example.com and all is great. But the moment I go anywhere else (e.g. https://example.com/WhatEverpage_I_go_To I get error 404,

The requested URL /WhatEverpage_I_go_To was not found on this server.

I seem so close but yet not there yet. Where do I look to get this thing working for any page on my site, not just the homepage?

Important note, I changed /etc/apache2/site-enabled/default-ssl.conf

From
DocumentRoot /var/www/html

To
DocumentRoot /var/www/drupal

Before doing that not even the homepage would work.

Thanks.

Check to make sure you are using the default .htaccess file. It sounds like your mod_rewrite settings are not working properly and/or not handling the https url.


Do migrate module migrations continue in background if terminal session ends? I'm working on a migration that involves some long migration times - many hours to migrate some tables. I use the drush commands to perform my migrations, but often something happens in the middle. The window closes by accident, or I lose my Internet connection for a minute, whatever. When I open a new terminal and run 'drush ms' I see my migration marked "importing"... but is it really going to finish at some point?

I believe not. That is why Migrate supports a reset option migrations if they are orphaned or otherwise fail. Typically you run migrations as a shell user (yourself) on the system. Unless you're using something else to keep your processes alive -- they die when the terminal they're connected to die.


How to create a menu child of an other menu? How can I create a menu child of an other menu.
Drupal menu are links to pages or an other content type.
I want a main menu that can expand sub menus by clicking on a menu item.
So, there is a module that can create menu children of a menu?

You can use the Menu block module

  .. allows you to display blocks of menu links starting with any desired level of a menu and limited to any desired depth.

  .. you can choose to expand all menu links with children or to root
  the menu tree to a specific menu item.


Is there any way to access the user tables on drupal? I want to ask where the information about users is saved in the database, since I could not find any corresponding entries in the sql file. I would like to share the user tables with another CMS, namely question2answer.com, so I do not have to maintain two user databases.

The users are saved in the database table 'users'.


View to display all child taxonomy terms I have a content type called "Unit Staff" with a term reference field called "Department". I also have a vocabulary called "Person" which is using a paragraph field consisting of a date field and the same "Department" vocabulary as a term reference. Every department has several child terms. I want to create "Unit Staff" pages where I only select the unit name and a block will display all persons using the taxonomy term.
I have already all page views for every department but if something needs to be changed, I have to go through +30 pages and update them manually. I hope this way to be able to use one view for 30 units/departments.
In other words, I need a view for child taxonomy terms whose parent term is defined in a node taxonomy reference field.
Any help is appreciated.

You actually want to list sibling entities, with another level of complication in between: the paragraph reference.
Both Unit staff and Person reference Department taxonomy, only the Person does it through a paragraph.
Had there been no paragraf and the reference was direct you could simply follow the sibling taxonomy tutorials to get what you want.
Here's an example:
Building views relationship with location
and one with additional complexity:
Views Contextual Filter by taxonomy in field collection
In your case the chained Relationships will be:
Unit staff to Department term reference > Reverse Relationship from Department to Paragraph > Reverse Relationship from Paragraph to Person.
Then you add the Person (Term Name) to your Fields, it will use the last Relationship.
This gives you a list of Unit staff nodes, each with related Persons.
If you want to show a block of Persons on Unit staff pages add the Contextual ID filter for the ID, Default value ID from URL (the most common case). Place the block on Unit staff pages, adjust the contextual options, and the block will show Persons related to the Department of that Unit staff.


How to make sure my behavior is triggered before AJAX? I have a form elements that looks like this:

  $form['properties'][$property->idProperty] = array(
    '#title' => $property->Label,
    '#ajax' => array(
      'callback' => 'mymodule_filter_ajax',
      'wrapper' => 'mymodule-filter-result',
      'method' => 'replace',
      'effect' => 'fade',
    ),
    '#attributes' => array(
      'autocomplete' => 'off',
      'class' => array('exclusive'),
      'exclusivity_group' => array ( $property->ExclusivityGroup )
    ),
  );

The point of it is to have only one element from each group used at a time. To enforce that exclusivity, I created behavior like this:

(function($) {
  Drupal.behaviors.behavior_name = {
    attach: function (context, settings) {

      $('select.exclusive', context).on('change', function(){
        // Make all not selected
        $("[exclusivity_group='"+$(this).attr('exclusivity_group')+"']").not(this).find("option").attr('selected', false);
        // select "all"
        $("[exclusivity_group='"+$(this).attr('exclusivity_group')+"']").not(this).find("option[value='all']").attr('selected', true);
      });
    }
  };
})(jQuery);

Note that both code blocks above are simplified, please don't criticize it too much as this is not actual code I'm using posted verbatim.

How can I make sure my behavior acts before AJAX? If it happens to act after AJAX, I may end up with two fields set to something other than 'all', and that's specifically what I wanted to avoid. I may use $triggering_element to detect if it was one of "exclusive" fields, and I probably will, even if only as a secondary precaution, but I would strongly prefer to have things happening right in the JavaScript part.

I tried using this answer, but I don't think I understand how it works. I tried:

  $('select.exclusive', context).each(function(){
    console.log($(this).attr('id'));
    Drupal.ajax[$(this).attr('id')].options.beforeSubmit = function (form_values, element, options) {
      console.log(element.html());
    };
  });

First console.log returns IDs as expected. And it works, beforeSend is, indeed, changed as it should, it's function gets executed when needed. Sadly console.log(element.html()); returns content of a whole form, not the triggering element of AJAX, so I'm not able to safely enforce exclusiveness - I don't know which element was changed last, so no way to select other elements.

I got it working now. The way to do it was:

Get all elements that are in "exclusive" groups using classes, .each over them
For each element, change beforeSubmit using $(this).attr('id') as index for ajax table
Because I was not able to get element to point to a specific element (it always pointed to entire form), I used helper variable at the beginning of .each loop.

Resulting code is like this:

(function($) {
  Drupal.behaviors.behavior_name = {
    attach: function (context, settings) {

      $('select.exclusive', context).each(function(){
        var triggering_element = $(this);
        Drupal.ajax[$(this).attr('id')].options.beforeSubmit = function (form_values, element, options) {
          // Make all not selected
          $("[exclusivity_group='"+triggering_element.attr('exclusivity_group')+"']").not(triggering_element).find("option").attr('selected', false);
          // select "all"
          $("[exclusivity_group='"+triggering_element.attr('exclusivity_group')+"']").not(triggering_element).find("option[value='all']").attr('selected', true);

        };
      });
    }
  };
})(jQuery);


How to send html/plain-text mails based on user settings? Using mail function i am send mails to multiple users with comma separated values in Drupal 8. But in that mail id users, some users selected mail preference as html and some users selected plain-text settings. So how can i send the html/plain-text mails programatically based on users settings?

If we are talking about hardcoding (not interface), you have to loop through the
addressee list, load that user, and based on his preferences send html, or plain text.


Let users download and set induvidual blog themes Drupal 7 I want to enable users customize their own blog appearance and theme the same way it is being done in multi-user blogging sites such as wordpress.com, tumblr.com, typepad.com, etc.

Users can set a theme to their blog
Users can manage some settings regarding ther blog appearance (background color, fonts, etc.)
Users can download themes or even make their own themes available for others.
The theme setting only affects the user blog page (but not the general site layout).

Any possible suggestions to make part of those requirements implemented quickly?

Letting them download and put up whatever theme that they want sounds like it might be a major security issue for your site, since they could put whatever PHP that they want into the theme files and it would run. I'd suggest making a specific set of themes you have picked available and letting users choose from those. There are modules like Theme key to enable using different themes: http://drupal.org/project/themekey


How to invite multiple users when editing user account? I've installed the Invite module. I see that there is an extra block that you can active. When you do this you will see a block like this on your page:

But I would like to have this field on my user/edit page. And make sure that they can enter multiple e-mail addresses separated by , .

But how can I do this?

You question consists of actually 2 questions:

... have this field on my user/edit page.
... enter multiple e-mail addresses separated by , .

To answer the 2nd question (= ... enter multiple e-mail addresses separated by , ), have a look at the issue about Multiple emails support for Invite form. The patch contained in comment nr 5 of it can be used to
create a new invite entity for each email address. Attention: it seems that this patch still needs to be rerolled for the latest dev version (which is also what explains the "needs work" status of this issue).


Node alias with taxonomy term I have the content type 'machine' that uses two vocabularies (producer, category).
I would like to create node alias like [language]/machines/[producer-name]/[title-raw]; [producer-name] is from the vocabulary.

Could anybody give me any advice?

The Token module provides very simple and limited taxonomy options. It will only provide the top most term of the top most vocabulary by weight.

The simplest solution will be to use a module like this: http://drupal.org/project/taxonomy_token

It will allow you to configure custom tokens for exactly the term/vocab you need.


Is there a patch for SA-CORE-2018-002? How can I apply patch for my Drupal 6 site which is working quite fine until now?

I've checked the patch in Drupal 7. It's using sanitize(). How do I add it in Drupal 6?

At the same time I'm working to have it upgraded to Drupal 8.

Per the official the FAQ about SA-CORE-2018-002:

  I manage a Drupal 6 site, is a fix available?

  Yes, Drupal 6 is also affected and the Drupal 6 Long Term Support project has patches available.

The issue for this is [core] Add D6LTS patch for SA-CORE-2018-002.  The issue has a patch from a security team member and further information.

2018-03-30 update:

Per a security team member in a recent comment:

  Please just upgrade Drupal core rather than patching!

  Note also the D6lts patch and corresponding github releases for that
  and Pressflow 6 were updated to fix a subtle flaw in the released
  security fix that was affecting a couple contrib modules including
  Organic Groups (og) for Drupal 6.

  https://github.com/d6lts/drupal/releases/tag/6.43

  https://github.com/pressflow/6/releases/tag/pressflow-6.43.124


Making File Size visible to anonymous users I have media installed for file handling, and am displaying download links for my files using display suite.  I have the file size being loaded in as a dynamic field loading token [file:size].

Everything works fine while I'm logged in as admin, but when I view the page as an anonymous user, the file size no longer shows up.  Any thoughts?

Permission should be given for that file type in case of anonymous user.

Because if size is visible to authenticated user and not to anonymous user, then it must be a permission issue.


Solr search, number of results I'm trying to find a way to display the number of resuts in a solr search.
I need to display it in search-results template.

Thanks for any hint

The link given is a nice one to deal with the default search result number count. In Apache Solr you can use the following code to get the total number of documents returned in the search result.

if (apachesolr_has_searched() && ($response = apachesolr_static_response_cache())) {
  $returned_doc_num = $response->response->numFound;
}


Theme a taxonomy terms page How do I theme the tag/taxonomyterm page on my site? Can I use a  panels page for this?

You could use panels. Heres a good guide to setting up page manager with panels.

http://drupal.org/node/1582906

or you could use templates...

taxonomy-term--[vocabulary-machine-name|tid].tpl.php
base template: taxonomy-term.tpl.php

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

taxonomy-term--tid.tpl.php
taxonomy-term--vocabulary-machine-name.tpl.php
taxonomy-term.tpl.php

  Note that underscores in a vocabulary's machine name are replaced by
  hyphens.

See: http://drupal.org/node/1089656


How to use lazy_builder to load and replace content asynchronously In my tests, I was able to make content be loaded asynchronous with

function callback_function() {
    sleep(5);
    return ['#markup' => time()];
}

...

$build['timestamp'] = [
  '#lazy_builder' => ['callback_function', []],
  '#create_placeholder' => TRUE,
];

In the case above, drupal renders whatever it wants to render and after the 5 seconds from the sleep it prints the timestamp. So it runs asynchronous.

But when having placeholders attached, it will waits 5 seconds before rendering everything, its not asynchronous. Like the code below:

$build['#markup'] => 'The timestamp is [timestamp]';
$build['#attached']['placeholders']['[timestamp]'] = [
  '#lazy_builder' => ['callback_function', []],
  '#create_placeholder' => TRUE,
];

My ultimate goal is to have for example "The timestamp is 1498827840" and then get it replaced to "The timestamp is 1498827845" after the 5 seconds sleep.

Normally placeholders are used for elements that are not cacheable, like a timestamp, so that the rest of the render array no longer depends on the dynamic data and can be cached. On a cache hit the placeholder gets replaced by the result of the lazy builder. This is the asynchronous part.

What you are trying to do looks more like asynchronous loading of web content in the browser. You can use BipPipe for this, but then don't put a sleep command in the lazy builder, try to solve this in javascript.


Prevent items from being indexed so it won't come out on search Drupal 7 - Can you you exclude an entire content type (or just selected entries from it) from being indexed so they won't come up in a search result? I'm just assuming that indexing is the answer but the main point is that neither of the items will come up on a search result.

You can use the Search API module in Drupal 7 to give you this granular control over your search indexing and results.

You will need at least one other module to use the Search API,
namely one that defines a service class (e.g. search_api_db ("Database search"),
provided with this module).

Creating a server
(Configuration > Search API > Add server)

The most basic thing you have to create is a search server for indexing content.
Go to Configuration > Search API in the administration pages and select
"Add server". Name and description are usually only shown to administrators and
can be used to differentiate between several servers, or to explain a server's
use to other administrators (for larger sites). Disabling a server makes it
unusable for indexing and searching and can e.g. be used if the underlying
search engine is temporarily unavailable.
The "service class" is the most important option here, since it lets you select
which backend the search server will use. This cannot be changed after the
server is created.
Depending on the selected service class, further, service-specific settings will
be available. For details on those settings, consult the respective service's
documentation.

Creating an index
(Configuration > Search API > Add index)

For adding a search index, choose "Add index" on the Search API administration
page. Name, description and "enabled" status serve the exact same purpose as
for servers.
The most important option in this form is the indexed entity type. Every index
contains data on only a single type of entities, e.g. nodes, users or taxonomy
terms. This is therefore the only option that cannot be changed afterwards.
The server on which the index lies determines where the data will actually be
indexed. It doesn't affect any other settings of the index and can later be
changed with the only drawback being that the index' content will have to be
indexed again. You can also select a server that is at the moment disabled, or
choose to let the index lie on no server at all, for the time being. Note,
however, that you can only create enabled indexes on an enabled server. Also,
disabling a server will disable all indexes that lie on it.
The "Index items immediately" option specifies that you want items to be
directly re-indexed after being changed, instead of waiting for the next cron
run. Use this if it is important that users see no stale data in searches, and
only when your setup enables relatively fast indexing.
Lastly, the "Cron batch size" option allows you to set whether items will be
indexed when cron runs (as long as the index is enabled), and how many items
will be indexed in a single batch. The best value for this setting depends on
how time-consuming indexing is for your setup, which in turn depends mostly on
the server used and the enabled data alterations. You should set it to a number
of items which can easily be indexed in 10 seconds' time. Items can also be
indexed manually, or directly when they are changed, so even if this is set to
0, the index can still be used.

Indexed fields
(Configuration > Search API > [Index name] > Fields)

Here you can select which of the entities' fields will be indexed, and how.
Fields added by (enabled) data alterations will be available here, too.
Without selecting fields to index, the index will be useless and also won't be
available for searches. Select the "Fulltext" data type for fields which you
want search for keywords, and other data types when you want to use the field
for filtering (e.g., as facets). The "Item language" field will always be
indexed as it contains important information for processors and hooks.
You can also add fields of related entities here, via the "Add related fields"
form at the bottom of the page. For instance, you might want to index the
author's username to the indexed data of a node, and you need to add the "Body"
entity to the node when you want to index the actual text it contains.

Index workflow
(Configuration > Search API > [Index name] > Workflow)

This page lets you customize how the created index works, and what metadata will
be available, by selecting data alterations and processors (see the glossary for
further explanations).
Data alterations usually only add one or more fields to the entity and their
order is mostly irrelevant.
The order of processors, however, often is important. Read the processors'
descriptions or consult their documentation for determining how to use them most
effectively.


Display of content-type I've got custom content-type with several groups and fields.

I want to change default display of that content-type. In which file can I find appropriate code?

You need to create that file - copy the node.tpl.php file to

node--your_content_type.tpl.php

and take it from there. Here's the relevant page from the handbook for Drupal 7

https://drupal.org/node/1089656

Alternatively, if you're just getting started with node templates, you may find it easier to install and enable the content templates module so you can add and modify node templates from the administrator backend:

https://drupal.org/project/contemplate

  The Content Template (a.k.a. ConTemplate) module allows modification of Drupal's teaser and body fields using administrator defined templates. These templates use PHP code and all of the node object variables are available for use in the template. An example node object is displayed and it is as simple as clicking on its properties to add them to the current template.


Non-blocking HTTP request with Guzzle Is there a Drupal 8 way to do non-blocking HTTP client request using Guzzle?
I don't need to wait for the answer of The HTTP post, as that is slowing  down the site.
I already seen Non-blocking asynchronous HTTP requests, but I want to know if someone have a Drupalier solution.

There is no "Drupal 8 way." Drupal 8 relies on Guzzle as its HTTP client library so it doesn't have a built-in solution for this.
While the Guzzle client library has GuzzleHttp\Client::requestAsync(), it's not a non-blocking asynchronous method; the method will block once it has initiated the network request since it needs response data for promise methods.
In order to do something akin to your linked question (using fsockopen() / fwrite() to open a socket, send HTTP headers, & close) with Guzzle, you'll need to use a different handler than the default ones Guzzle provides. Guzzle has some documentation on to do this.
It should be noted, even the linked solution isn't non-blocking in the event there are network connection issues (e.g. if the host is unreachable, fsockopen() has $timeout set to 30, so it would  block for 30s before timeout was hit). PHP being single-threaded prevents true non-blocking asynchronous execution within PHP code.


How to convert Mutual User Relationship to Reciprocal? I had a relationship set up on my website (let's call it "Friends"), and many of my users have used it. It was a Mutual relationship. That relationship is being used to provide access to the user's nodes via Panels... for example, if User A and User B become friends, then User A can see User B's nodes, and User B can see User A's nodes.

I recently converted the (mutual) Friends relationship to One Way with the possibility of Reciprocation, because I now need to allow User A to request access to User B's nodes without giving User B access to User A's nodes. If User B then decides to request access to User A's nodes, they can do so because of the reciprocation setting.

That functionality is working fine for any new Friends. The problem I am having is that any Friend relationships that existed before the relationship was changed from Mutual to One Way/Recip are not acting like reciprocated relationships; they are acting like One Way relationships. Therefore, if User A was the one who requested the original mutual Friend relationship, they now own the One-Way relationship with User B, and User B does not own a reciprocal relationship with User A.

I need for the formerly Mutual Friend relationships to now be One Way with Reciprocation. How can I do this? Is there a way for me to edit it in the database perhaps? I definitely cannot ask all of the users to un-friend and re-friend their existing relationships.

Thanks!

I found the issue... I had to update the Relationship IDs in the database for the originally-Mutual relationships because they shared the same RID, thus making each RID unique. The one-way/reciprocal relationships do not/cannot share the same RID.


Is my web hosting company's "Full Backup" sufficient protection before an update? I'm learning how to work my little Drupal site, which is currently hosted on HostGator. It's well past time to update, and I want to make sure I'm safely backing up my site.

HostGator can facilitate "Full Backups" of my files, which they describe thus:

A full backup includes all of the files in your home directory, your MySQL databases, and your email forwarders and filters. You can back up your account to preserve your data, or to move your account to another cPanel server.

Thank in advance, and/or apologies if this is a crap question.

You need two things to restore a Drupal site: A copy of the database and the folders that hold Drupal.

I'm not familiar with shared hosting, but I'm guessing that Drupal is installed in your home directory as opposed to /var/www or /srv/www.

That means a full backup does give you everything you'll need to restore Drupal. Make sure you know how you'd restore it though. No point backing up if your not sure where the files are and how to restore them.

If you want to extra safe or do it yourself, install the Backup and Migrate Module, make a backup and make a copy of your Drupal root directory. (That's the one with sites, includes, themes etc. in it).

Then if you want to restore Drupal. Delete the bad Drupal root directory and put your old drupal root directory back in. Install Drupal as normal, enable backup and migrate module (it'll be there because you've put in your modified Drupal root folder) and then restore from the Backup and Migrate backup.


Webform submission token for multivalue download field I'm trying to setup a webform that sends links which can be accessed to download a file.
It's working with the first file already, but I can't figure out how to create the token for the other files referenced in a multivalue field:
What's working (for one file):
Here is your requested download: <a href="[webform_submission:node:field_gated_download:entity:field_media_file:entity:url]" target="blank">[webform_submission:node:field_gated_download:entity] </a>
I have tried:
[webform_submission:node:field_gated_download:entity:field_media_file:entity:url:0]
[webform_submission:node:field_gated_download:entity:field_media_file:entity:url:und:0]
[webform_submission:node:field_gated_download:0:entity:field_media_file:entity:url]
[webform_submission:node:field_gated_download:und:0:entity:field_media_file:entity:url]

in almost every combination. It's not working.
Can someone lead me in the right direction?

One approach to this issue is to interpret tokens on your own via hook_tokens().
hook_tokens() is called every time a token is interpreted and gives you an opportunity to determine how that token is interpreted. Even though the token [webform_submission:node:field_gated_download:entity:field_media_file:entity:url] is already defined, it may be necessary to also implement hook_token_info() or hook_token_info_alter() in order to define additional modifiers to the token.
It's possible that you might discover the exact token syntax that you need by inspecting the arguments passed into hook_token_info_alter().
Here are two tutorials that cover using both hook_token_info() and hook_tokens() in order to perform custom token processing.

https://www.cloudways.com/blog/create-custom-drupal-token-modules/
https://medium.com/thefirstcode/tokens-replacement-patterns-in-drupal-8-d309132ba13d


how to change the background image based on the node (the hard way) I'm trying to change the background image of my site based on what node the user is viewing (not just what node type, but specifically what node). I have added an image field to my node type called background image. Basically, I'm trying to go into my html.tpl.php file and inject a style right into the body tag, for isstance

background-image:url('../images/mybg.jpg');

I'm hoping to grab the image field from node that is loaded, but I'm having trouble figureing out hoe to access a nodes field from the html.tpl.php file (i need to do it from here becuase that's where the body tag is). I've added a pre-process function to my template to try and find the correct field, but i've hit a dead end

function mytheme_preprocess_html(&$vars) {
     dpm($vars);
}

the array that is traced makes no sense to me, and I'm unable to find the field. Is there a better way to do this

The simplest (not necessarily the cleanest) way to do this is:

function mytheme_preprocess_page(&$vars) {
  $node = menu_get_object();
  if ($node->nid) {
    // We're on a node page
    if (isset($node->field_background_image[$node->language][0]['fid'])) {
      // Load the file object
      $file = file_load($node->field_background_image[$node->language][0]['fid']);

      // Get a web accessible URL for the image
      $path = file_create_url($file->uri);

      // Add the background to an inline CSS tag
      drupal_add_css('body { background:url(' . $path . ') left top no-repeat !important; }', 'inline');
    }
  }
}


Field Info API as REST We would like to get label for the field.

As per previous question: How do I get a field label by the field name?

But I need to get this through the REST API of Drupal.

Could anyone please suggest what should be the approach to use the Field API from as REST service.

Simply you need to create a custom resource as described here.

In the call back put the piece of code answered here

taking args int he resource, But I suggest using field_info_field as it only takes the field name and returns all details as an array that you could choose what you need to return


Show the latest post from multiple content types I have three different content types like news, events, meetings. Using views i need to display only one post (the latest one) from each of this content type.

Created a view, filter criteria for all four content types selected....and stuck.

This would probably best be fixed by creating view blocks and creating a separate view for each of the content types.  Then display the blocks in the region as needed.  Or you can create a custom page template and embed the views inside that


Programmatically added comment form on node page doesn't work I have attached a view which displays comments to basic page content type using EVA module. I've also implemented the following to have the "add comment" form displayed just above the comments list:

/**
 * Implements hook_views_pre_build().
 */
function mymodule_views_pre_build(&$view) {
  if ($view->name == 'page_comments') {
    if ($node = menu_get_object()) {
      $comment = new stdClass;
      $comment->nid = $node->nid;
      $form = drupal_get_form('comment_form', $comment);
      $form['#redirect'] = current_path() . '?page=' . (int)$_GET['page'];
      $header = drupal_render($form);
      $view->add_item('default', 'header', 'views', 'area', array('content' => $header, 'format' => 'full_html'));
    }
  }
}

It should work like this:

on page /node/12, which contains the node, comment list and the "add
comment" form, the user enters new comment and submits
the page reloads quickly
the submitted comment appears in the comment list on the same page,
together with another "add comment" form

What actually happens:

as above
user is redirected to page /comment/reply/12 which also contains the
node, comment list and the "add comment" form
however, the previously submitted comment is lost, it doesn't appear
in the database or anywhere else
the user can then again enter a comment and submit
if he does so, he is redirected to page /node/12#comment-1561, which
contains the node, comment list and the "add comment" form
the second submitted comment is on the comment list

So there are two problems with my added form: comment is not submitted and there is redirection. What needs to be done to make it work the way it should?

I'm not sure about the failure to submit, but drupal_get_form caches the form config, so making changes to the #redirect after calling it will be lost by the time the form submits. You'd need to use hook_form_alter for that change to persist.

As an alternative, you might consider the AJAX comments module. In theory that will work with a manually embedded comment form, and it'll sidestep your current issue while providing a slightly better UX for comments site-wide.


Default date field values like "today +10 hours 30 minutes" I have a date_field Date (ISO format) as a Pop-up calendar. I would like to have it as a default value: today 10:30
In php the

strtotime("today +10 hours 30 minutes")

serves me well. Also

strtotime("today 10:30 am")

If I put it in the "Relative default value" field, the time gets not parsed. It is always the current time.

strtotime("noon")

or

strtotime("midnight")

has the same effect. Bug? How to get the default date to "today 10:30 am"?

The best way to control the default output of form elements is through the drupal Form API.

You have two scenarios:

If you created the form with the form api and have a date popup in your form, you can use the method described in this post to set the #default_format of the #default_value of the form element.
If you didn't create the date popup in the form element with the form api, meaning you added it as a field to an entity through site configuration, you can still make a small custom module solution.  Make a custom module and implement hook_form_alter, find the field in question and set the #default_value using the method mentioned in #1


User variables defined in hook_variable_info() in rules I'm declaring the varialbes of a custom module in hook_variable_info(). Now I'd like to access some of them in rules. How can I do that?

The reason for this is that the Variable module gives me the chance to added fine grained access control for this values. Otherwise I would be forced to give users full access to administer rules.

Update: I found this issue: Make Drupal variables accessible with data browser in rules
To be honest I don't fully understand what it is saying.

As the Rules module uses tokens, and the Variable module implements hook_tokens(), you should not do anything.

If the value returned from that implementation of hook_tokens() is not the value you would expect, in a module of yours you could implement hook_tokens_alter() to alter the token values returned by the Variable module.

Reading Entity property information, I get fago means code similar to the following one should be used.

function mymodule_entity_property_info() {
  $info = array();

  // Add meta-data about the variables exposed from the Variable module.
  $properties = &$info['site']['properties'];

  // ...

  return $info;
}

I didn't find any information about the parameters passed, for example, to the setter callback, even though entity_property_verbatim_set() is defined as entity_property_verbatim_set(&$data, $name, $value, $langcode, $type, $info).

function entity_property_verbatim_set(&$data, $name, $value, $langcode, $type, $info) {
  $name = isset($info['schema field']) ? $info['schema field'] : $name;
  if (is_array($data) || (is_object($data) && $data instanceof ArrayAccess)) {
    $data[$name] = $value;
  }
  elseif (is_object($data)) {
    $data->$name = $value;
  }
}

Vice versa, entity_metadata_user_set_properties() is defined as entity_metadata_user_set_properties($account, $name, $value).

function entity_metadata_user_set_properties($account, $name, $value) {
  switch ($name) {
    case 'roles':
      $account->roles = array_intersect_key(user_roles(), array_flip($value));
      break;
  }
}

entity_metadata_user_entity_property_info() uses that setter callback in the following definition.

  $properties['roles'] = array(
    'label' => t("User roles"),
    'description' => t("The roles of the user."),
    'type' => 'list<integer>',
    'getter callback' => 'entity_metadata_user_get_properties',
    'setter callback' => 'entity_metadata_user_set_properties',
    'setter permission' => 'administer users',
    'options list' => 'entity_metadata_user_roles',
    'access callback' => 'entity_metadata_user_properties_access',
  );


How do I theme exposed filters? I'm theming a Drupal 8 Views page. I created the twig template file and can output the 2 exposed filters with the code below. The problem is that nothing happens when I click Apply on the exposed filters. It's probably missing some attribute, but I can't figure out how to do it.
Has anyone done this?

{% if exposed %}
  <div class="view-filters form-group">
    {{ exposed.field_category_target_id }}
    {{ exposed.field_address_locality }}
    {{ exposed.actions }}
  </div>
{% endif %}

Here are the printout of the exposed variable

This is not possible in a Views template. Form elements rendered here can't be submitted because they are not in a html form (between <form>/</form>).

You need a custom form template so that you are inside of the form. For the Views exposed form there is already a customizable form template in core:

/core/themes/stable/templates/views/views-exposed-form.html.twig

{#
/**
 * @file
 * Theme override of a views exposed form.
 *
 * Available variables:
 * - form: A render element representing the form.
 *
 * @see template_preprocess_views_exposed_form()
 */
#}
{% if q is not empty %}
  {#
    This ensures that, if clean URLs are off, the 'q' is added first,
    as a hidden form element, so that it shows up first in the POST URL.
  #}
{{ q }}
{% endif %}
{{ form }}

You can copy this twig to the /template folder of your theme and start theming the form elements:

  {{ form.field_category_target_id }}
  {{ form.field_address_locality }}
  {{ form|without('field_category_target_id', 'field_address_locality') }}

See How do I assign a template to the user edit form? for more info how to add and use these form templates in other forms.


redirecting midway out of a webform wizard I am building a webform that has multiple pages. The idea is that the user leaves the wizard after each page that he submits. When he later returns, he automatically starts the form on the unanswered page.

The reason for this behaviour is that doing so, we can keep the records of all the 'sub-surveys' together as one single submission.

I successfully have set up custom handlers based on the example module. I can see that the handler is working.

To accomplish the desired scenario, I thought that it is probably best to log the user out in the {submitForm} function of the handler and set the redirect ($form_state->setRedirect).

The redirect doesn't happen, but the logout does. What I end up with now, is that the user sees his next page, but can't submit it because he is actually logged out. It's fine that he can no longer submit. But it's not ideal that he sees the next page in the form. That is why i try to redirect.

I read in another question on stackexchange that the redirect should be set in the confirmForm, but that doesn' work either. Maybe because confirmForm only happens at the end of the wizard or something.

Any suggestions on how to redirect after (each, or some based on a condition) pages from the wizard?

Thanks.

The logout is probably losing the user's session with the $form_state

A very simple solution is to redirect the form to /user/logout?destination=REDIRCT_PATH.


Hide a div on webform submission using ajax I am new to drupal i  am using webform ajax module to submit my webform , its submiting values properly after validating them , but along with this i want to hide a div also on submit . what is the best way to do this

The most effort-free way to hide something i can think to goes trough some CSS.

Inspect the div you want to hide for its id, then just add a rule in your theme CSS

#id { display: none; }


How to run a rule for a specific user? I want to redirect a specific user when he logs in.

There are 4 users.

Each one must go to a different url.

Under the rule I have

What do I need to put in for the conditions?

There are many other methods to do it, but I prefer this method,

Try this on your Rules module.

  Events: User has logged in.

  Condition: User has role

  Actions: Page redirect


Filtering PrivateMsg types by "sent" or "inbox" I'm wondering what approach programmatically I should take when displaying message links that are either sent to the user loading the list, or sent out to other users.

Using some modifications to the example code listed at http://drupal.org/node/624528, I've loaded all unread and read messages regardless of author:

foreach ($query->execute() as $key => $thread) {

if ($count <= 25) {
                        // Generate a link with the subject as title that points to the view message page.
                        $items[] = array(
                            'data' => 'thread_id . '">' .
                            '

' .
                            '
' . $username . "
" .
                            '
' . $thread->subject . "
" .
                            '
' . format_date($thread->last_updated, 'short') . "
",
                            'class' => array($class),
                            'id' => $key
                        );
                        $count++;
                    } else {
                        break;
                    }

and the output is done through a theme() call. I'm seeing that messages sent return null in $thread->participant. Would this be a sufficient use case to track for sent messages?

From the page that you linked to:

// Replace 'inbox' with 'sent' to display sent messages or 'list' to display all messages.
$query = _privatemsg_assemble_query('list', $user, 'inbox');

Note that the privatemsg_filter module needs to be enabled for that to work.