Why does the count of the Menu badge not decrease after page is viewed?

Part 1 - It does seem to work as designed

Since your question is about a "Menu badge", I'm assuming you are using the (great!) Menu Badges module to create such badge, whereas you also created a view (using the Views module).

To make it all work, your view should show the number of rows corresponding to the "activity logged by the Message module" (as in your question).

And the view seems to be OK if there is no activity (it shows "O").
However, if the count remains the same later on, then it must be because the result of your view doesn't change either. If you want that number produced by the Menu Badges module to change, then you must make sure that the view produces the correct number. So if that number doesn't change, it is about sure (not just probably ...) because something in the filter of your view is not correct. Like does your view only select the rows which have some kind of "new activity" indicator? If not, what other filter do you have to make that number decrease?

So IMO this is not a bug in the module, but rather just a customization error in your view (head over to Part 2 for more details on that).

Part 2 - What you're missing in your view

I think Part 1 of my answer is "the" answer to your question, but here is an attempt to also, partially, answer your additional comment (which is really a new question I think):

  If there is new activity, the number does increase, but do not decrease or disappear as in case of private messages. What I have understood so far of menu badges is that you have to put something in the fields section and turn on aggregation so that it knows what to count. Currently I am using Message:Message ID in the field. What filter I should use?

Not sure where the "private messages" refers to (I'm just going to consider that as "a" type of messages). But you're right about that "you have to put something in the fields section and turn on aggregation so that it knows what to count": that is the "clue" about what the Menu Badges is all about. Let's consider the Message View (where the below screenprints originate from) that comes with the Message module, i.e.:

Here is a screenprint with the design details of that view:

If you'd use the Add button for "fields", and then filter the available fields for "Message:", you would only get these fields:

Language
Message ID
Render message (Get text)
Rendered Message
Timestamp
Type
User uid

Obviously, none of these fields contain any information if it is yes or no a "new" message. So that's what you're missing and why out-of-the(-message)-box you cannot get this to work. To better explain this (what you're missing): have a look at the "tracker" view (disabled by default), which has the fields "Content:Has new content" and  "Content:Has new comments". Those are 2 perfect fields to use if you want to use Menu Badges to get notified whenever there is new content, or new comments.

A possible compromise, and maybe partial solution for your scenario could be that you'd use the Timestamp field as your filter. E.g. if you'd filter it like "only the ones from the last 24 hours", that should have some effect.

Part 3 - How to get it to work anyway

There is a way to get this to work anyway ... Because messages are fieldable. So simply (hm, hm) add a boolean field like "Message is new" (Yes/No). It'll then also show up in the list of fields you can select from in your view (in the list of available fields as in Part 2). And with that you have a perfect solution for what you're trying to get to work.

However, there is one more challenge left: add appropriate logic to maintain the value of that boolean field. If you wonder how to do that (also), just ask a new question.


How would I be able to get the full URL from an image field?

Have you seen the answer of this question?


Looking for a hook called before any session is created

If you wish to manage the session as mentioned in your comment, you can completely replace the default session handling by setting the variable session_inc to the path of an include file that defines the functions expected by Drupal.

In your settings.php file:

$conf['session_inc'] = 'sites/all/modules/my_session_handler/session.inc';

And in session.inc you will need to implement the following functions:

drupal_save_session
drupal_session_commit
drupal_session_destroy_uid
drupal_session_initialize
drupal_session_regenerate
drupal_session_start
drupal_session_started

You may want to start by copying Drupal's default session.inc and modifying it to suit your needs.  Keep in mind that any of the functions in the default session.inc starting with an underscore are considered private, and not necessary to implement in your custom session.inc.


Node access, Cron, and DANGEROUS_ACCESS_CHECK_OPT_OUT'

I read it more as "Dangerous, Access Check Opt Out"


How to disable a feature whose checkbox is grayed out?

This is true for Module page and Features page:

The page should list out the dependencies and modules/features that are dependent on that module/feature so you would have to turn off those modules/features before you can turn off the one that is disabled, if you use drush it will tell you that you are turning off all dependent modules when you perform drush dis modulename

One thing to note: on some setups that dependency list may be collapsed. Certain developer/helper modules will collapse those options on the modules page so you may have to click to expand but the reason why a module could not be disabled is b/c it is a dependency for another module so unless you are using drush like mentioned above you will need to turn off all the modules listed as needing that module to operate first.


How can I play an already uploaded video inside an Amazon S3 bucket? And how can I use the String Authentication on it?

I'm answering this, hoping I can help anyone else with the same problem.
If you're trying to play videos already uploaded to your S3 Amazon account, you won't find an appropriate Drupal Module to do so. (see this).
What I did is to get myself an Amazon Cloudfront account and protect the videos manually with an expiration date; then I pasted the video (using the player jwplayer), and I controlled the access to that node using any of the node access modules.


How to show new nodes in a Group node view for users who are not a Group member?

... After creation the node is not listed in the group nodes ... While checking it, the user is not a member of the group. If I add the user as a member it works fine.

I'm reading the above like "For users who are not a member of the group, I want the nodes to be listed in the group nodes also". To implement this:

you need to correctly configure the permissions for what in the Group module is called "Outsider".
you should NOT have to "add members dynamically while creating node in the group", as in your question (that's not how the Group module is supposed to work or be used).

And to configure the permissions for Outsider, you can use either of those techniques (using Group-Type-x to indicate the type of group):

Grant permissions to group role at /admin/group/types/manage/Group-Type-x/permissions, so that a user who is not member of a group, receives the Outsider permissions for that group.
If you need to distinguish between outsiders based on what roles they have in the global scope, then (and only then) you should use the "Advanced outsider permissions" page, located at /admin/group/types/manage/Group-Type-x/permissions/outsider. There you'll find all roles as defined in /admin/people/permissions (= the global scope).

With the above in mind, and looking at your question details, it seems to me that there are 2 possible solutions (depending on how you want it to work):

If all outsiders should have similar access Then Tune the Group permissions at /admin/group/types/manage/Group-Type-x/permissions.
If outsiders of selected global roles should have specific access Then  Tune the Group permissions at /admin/group/types/manage/Group-Type-x/permissions/outsider. Note that the image shown in your question (about "Advanced outsider permissions") does not show anything that you already gave some permissions to role "Manager" (there is not even 1 checkmark below role "Manager").

BTW, about your "If I add the user as a member it works fine.": that seems to confirm that you correctly configured your permissions for members of the group. But by "adding a user as a member", such user is no longer considered an "Outsider". So you really need to fix your permissions for "Outsider".

PS: If for Anonymous users you want similar access permissions as for  "Outsider", then you also need to configure those permissions via  /admin/group/types/manage/Group-Type-x/permissions.


echo "<pre>"; print_r($variables); echo "</pre>";

That's not how it should be done, instead, install the Devel module.
This will allow you to do:
dump($variables);

If you haven't turned caching off, for developing purposes, then you will have to flush all caches to see the dump.

In addition, if you also install the kint package/library with:
composer require kint-php/kint

now you could also do:
kint($variables);

Related: Welcome to Kint 101


Custom pseudo field not rendered when no other field has content

So I found my fault - when you describe a field the render array needs to have an array of field items. So the $build-array needs to look like this:

$build['igb_title'][] = array(
      '#type' => 'html_tag',
      '#tag' => 'h2,
      '#value' => $entity->label()
    );

In field_group_remove_empty_display_groups it is checked if a field as at least one item:

$has_items = isset($element[$name][0]);

If $has_items is false the field group is emptied if there is no other field with a value. I think I might need to go deeper into this render array thing...

Best,
Tobias


How to use pager or term limit for taxonomy_get_tree($vid)?

Add a counter into your for each statement that counts the array index and terminates after X number of items.  That'd fix it.


I had a similar problem. In a submit handler, tried to run dsm($form_state). This caused all submit handlers to not run. If I run $form_state['complete form'] = NULL; before the dsm(), it works. I presume it was too big with the complete form in there.


List all nodes by logged in user in a custom module

There is module available https://drupal.org/project/usercontent still if you want to do it in custom module then here is the code:

global $user;
  $node_query = db_select('node', 'n')
  ->fields('n',array('nid'))
  ->condition("type", "node type")
  ->condition("uid", $user->uid)
  $node_result = $node_query->execute()->fetchAll();


It's hard to impossible to know where this error come from without adding some debug statements before the line 980.

Try enabling devel.module and adding following code on line 977:

dpm(func_get_args());
dpm($info);

This will reveal which theme hook is being called and its parameters (variables). It should give enough clues to help you find where the error comes from.


How to set custom access for a custom page?

Here's an example which prevents anonymous users from resetting their password.

services.yml:

services:
  mymodule.route_subscriber:
    class: Drupal\mymodule\Routing\MymoduleRouteSubscriber
    tags:
      - { name: event_subscriber }

src/Routing/MymoduleRouteSubscriber.php:

<?php

namespace Drupal\mymodule\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class MymoduleRouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {

    if ($route = $collection->get('user.pass')) {
      $route->setRequirement('_custom_access', '\Drupal\mymodule\Access\ResetPasswordAccessCheck::access');
    }
  }

}

src/Access/ResetPasswordAccessCheck.php:

<?php
namespace Drupal\mymodule\Access;

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessResult;

class ResetPasswordAccessCheck {

  /**
   * A custom access check.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   Run access checks for this account.
   */
  public function access(AccountInterface $account) {

    return $account->isAnonymous() ? AccessResult::forbidden() : AccessResult::allowed();

  }

}

I've updated the documentation to clarify what return value is expected: https://www.drupal.org/docs/8/api/routing-system/access-checking-on-routes

Forum access example

You only need the route subscriber in services.yml:

services:
  yrv_page_access.forum_route_subscriber:
    class: Drupal\yrv_page_access\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

RouteSubscriber:

<?php

namespace Drupal\yrv_page_access\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

class RouteSubscriber extends RouteSubscriberBase {

  protected function alterRoutes(RouteCollection $collection){
    if ($route = $collection->get('forum.index')){
      $route->setRequirement('_custom_access', '\Drupal\yrv_page_access\Access\ForumAccessCheck::access');
    }
  }
}

Access check:

<?php

namespace Drupal\yrv_page_access\Access;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Session\AccountInterface;

/*
 * Custom access to the forum page
 */
class ForumAccessCheck {

  public function access(AccountInterface $account){
    return AccessResult::forbidden();
  }
}


Webform image select element is dispalying another image while used in webform handler

Finally, I am decided to go with "Business rules" module which will allow to create any content type and transfer all data from webform submission to the created node by setting up a few actions to be triggered on the rule event: entity insert of type webform submission.

See video tutorials here: https://www.youtube.com/channel/UC3jgO5Yt-5y__VVT74qRgSg


Missing bundle entity, entity type paragraphs_type from field_instance.yml file

I believe you need to change the expected_value: field_collection_item to match your field_collection_items


how generate chart from Views Aggretation Plus

Now I can do that,

(a) Exclude the Company field
(b) In the VAP setting, disable the summary sum in the footer
(b) Then use highcharttable module to create the pie chart.


How to appened a new 'class' attribute to a custom field ? - twig drupal 8

Normally I would say to call addClass() on the image.attributes variable in your image Twig file, but I believe images don't have a lot of template suggestions (everything goes through image.html.twig) which means that your class will be added to all images. Likely not what you're looking for...

Option one, inspect the variables in image.html.twig and see if they give you the information you need to determine when to add the new class. If so, do it in the Twig template (attributes.addClass('new-class')).

Option two, implement hook_preprocess_image in your theme's .theme file. Something like this:

function MYTHEME_preprocess_image(&$variables) {
  if (some_way_to_figure_out_if_this_is_the_right_image) {
    $variables['attributes']['class'][] = 'new-class';
  }
}

Hope that helps. (Edited for better code formatting).


Implement hook_token_info and hook_tokens

I found out. It was because I tried to implement hooks in my template rather than doing it in my module.


If you want to create content-type (not content) then this is link admin/structure/types where all content types are listed (in drupal7). But If you are talking about create content then you can add content node/add here all types will be listed.


I need a advanced search block (by using views) on home page of site

For Drupal 7 you can create mentioned output via setting Filters and set the option "Expose this filter to the user"
Moreover, you can add checkbox using BEF(Better Exposed Filters).
I hope this helps. :)


How to determine module path in drush which is outside of Drupal root?

In Drush, the right way to do this is to use drush_invoke_process() to call a Drush function in coder that calls coder_review_reviews() for you, and returns the result as the function result of the Drush command implementation.  I did not check to see if coder does this.

If the service you need is not exported, the alternative is to call drush_get_commandfiles().  The result you will get is a key / value pair, where the key 'coder' has the value of the full path to the coder.drush.inc file.

When commands do not export the functionality you need, it is better to submit a patch on their project providing the access you need. Directly including .inc files and calling internal functions is fragile, and at risk of breaking in new versions of the project.


How to add fields to 'content' format in Views

Here are the steps:

First you need to configure "share this" module:

Go to Configuration >> Web services >> Sharethis (admin/config/services/sharethis)

select the Node Types where you want to use this.

Then go to content type manage display settings and in custom display settings check the modes which you have used in view.

That's it.


Drupal site Phonegap application field collection

make sure a field collection exists if you want to go through the Field collection module. Then write the custom php code make sure to use the field collection api. here is an example. another example.

You will have to use AJAX from your phone gap app and send the data you are collecting to your server then use the drupal code to process and insert.
AJAX from phonegap to PHP

Let me know if you need any more help, i'm just really busy as of late or I would provide a more detailed answer. It's difficult not having the code in front of me.


Accessing Content: Path field within views_view_unformatted TWIG template

You access the fields from the entity. That are not the fields from the view. And in the entity there is no field path.

Look for the path in the row content. This is a good advice not only for the path, but for all fields, because in the entity the field values are the raw data from the database and not formatted for output. That doesn't make a difference for the id and the title though, because they are plain alphanumeric, but you really should do it for more complex fields. And for computed fields like path you have no other choice, if you don't want to compute the field again yourself.


Show clrcle overlay instead of marker in google map?

The view settings should allow you to choose the marker style. Don't have the module installed to check but a comment on the "Provide Gmap marker field for use in Views listing" feature request illustrates how I remember it:

  Under style: GMap in your view try clicking on the setting icon next
  to where it says GMap. An option box should appear below the view with
  some options:

  Marker handling: By content type (for node views)
  By term (for node views)
  Use single marker type


In the original query, you're using LEFT JOIN, so that will return results for the priority table, even if there is no successful join to the city table.

To match that query, use ->leftJoin instead of ->join

https://api.drupal.org/api/drupal/includes%21database%21select.inc/function/SelectQuery%3A%3AleftJoin/7.x

Otherwise, your query should be correct and you don't have a priority for chicago.


Show system message to user when node is published

System messages are displayed only once and for the current user. In your case it would be more appropriate to send an email when the node has been published.

To do so, create a following Rule:

Event: After updating existing content; restrict it by content type if necessary.
Condition: User has role(s), select administrator role and check Negate to make sure this rule does not get triggered for administrators.
Condition: Data comparison, for Data to compare select that node-unchanged:status equals to Unpublished. This is to make sure old node was unpublished.
Condition: Data comparison, for Data to compare select that node:status equals to Published. This is to make sure new node is published.
Action: Send mail and configure it the way you want.

Hope this helps.


If you are wanting to use the nid of the node reference field inside a node template, you could grab it as $node->FIELDNAME[0]['nid'] (D6 anyway, add an ['und'] or something similar in the mix for D7 :)  Otherwise, a lot of other examples are given in the article @refineo references above.


How to display label and field output inline

According to default field.html.twig file template which is use to render fields, you have to set #label_display => 'inline'
and #title => 'Your label'
Most of themes render inline label and content when class field--label-inline exist, but it is possible that you remove this css style from your theme.


Define entity in module and edit existing items

You have two problems in that code. First of all, you assume that having a didyouknow-id in the URL, is enough for Drupal to know where to get your object, the second problem is that your page argument is off.

This simplified code:

$items['admin/structure/didyouknow/manage/%didyouknow/edit'] = array(
  // …
  'page arguments' => array(1),
);

will pass on "structure" as an argument, not the %didyouknow id, nor a didyouknow-object, which is why you get an error about a "non-object". Argument indexing start with 0 => admin, so (as already mentioned by LToomre) you need to have:

'page arguments' => array(4),

It is also important to note that Drupal will not automatically know how to load your entity, you are required to provide the load function yourself.

As an example, look at the epay module, which has a menu hook like this:

$items['payment/epay/callback/%epay_hash'] = array();

The named argument %epay_hash, is automatically mapped to a _load function:

function epay_hash_load($hash) {}

which takes the URL argument as parameter, performs the DB queries necessary to load your object, and then returns it.


How does contextual menus work in Drupal 7?

I'll put my temporary solution here for now anyway in case it will help someone.

What I did was just creating a new theme function (?) in my module

$themes['contextual'] = array(
    'template' => 'contextual',
    'variables' => array('links' => array(), 'destination' => null)
);

Then I defined my contextual.tpl.php

        <?php foreach($links as $url => $title): ?>

            <?php echo l($title, $url,
                array('query' => array('destination' => $destination))) ?>

        <?php endforeach; ?>

Finally, to use it, wherever there is a need for a contextual menu, add the class contextual-links-region to the container div of the node (or whatever), and inside the div I use my function, for example:

<?php echo theme('contextual', array('destination' => 'node/'.arg(1),
    'links' => array('node/'.$somenode->nid.'/edit', t('Edit node')))); ?>


How to alter default value of select in webform

For multiple selects use an array for the default value:

$element['#default_value'] = array('foo', 'bar');


Display Custom User Profile Fields in a Block on All of Their Published Pages

You should take a look at the Context module.

  Context allows you to manage contextual conditions and reactions for
  different portions of your site. You can think of each context as
  representing a "section" of your site. For each context, you can
  choose the conditions that trigger this context to be active and
  choose different aspects of Drupal that should react to this active
  context.

  Think of conditions as a set of rules that are checked during page
  load to see what context is active. Any reactions that are associated
  with active contexts are then fired.

Or a simpler solution might be to change your path from "their-name/content" to "user/their-name/content" and only show the block on "user/*/content".


Translating a taxonomy term does not populate content into fields

I have found one compromise solution that needs Replicate & Replicate UI modules:

Go to relevant taxonomy term and click 'replicate'
Edit replicated taxonomy term as necessary and switch language
Create a new 'translation set' to link the two taxonomy terms as
translations of each other

This solution isn't suitable for my end-users because of the third step. The 'translate' feature for nodes automatically links the two pieces of content as translations.


Adaptive theme css which stylesheet to use?

The AdaptiveTheme site has a lot of great documentation to help explain this.

In general, you should use global.styles.scss to style elements that will look the same across all devices, and the individual responsive stylesheets (e.g. responsive.desktop.scss) for device-specific styles. If you want to override something in global.base.scss, you're probably best off doing it in global.styles.scss, depending on how fundamental the change is.


How to properly inject mutable config to the controller?

There are two other ways to inject dependencies into a controller, and a third alternative.

1. Implement ContainerInjectionInterface

This does technically add a dependency to the container. In a unit test, the container would need to be set with \Drupal::setContainer() with a mock object of the config factory and config object.

`

  public static function create(\Symfony\Component\DependencyInjection\ContainerInterface $container) {
    return new static($container->get('config.factory'));
  }

  public function __construct(\Drupal\Core\Config\ConfigFactoryInterface $config_factory) {
    $config = $this->config_factory->getEditable('loremipsum');
  }

`

2. Make the controller a service.

This is recommended by all of the Symfony developers that I have asked, and none have been concerned by any performance impact of making all of Drupal's routes use services.

This is subjective, and there is some contention about the practice.

3. Use a Form class that extends ConfigFormBase instead.

But, why would a controller want MutableConfig instead of ImmutableConfig? A Form class extending ConfigFormBase instead. A form is probably the best place to modify configuration values such as a class that extends ConfigFormBase.


Are you using Relationships? It's right there in the views edit page. Since you're showing nodes, you are probably going to need to declare you want to show taxonomy term fields.


How to remove Home title from the home page?

I think there is no way to remove it from the BO:
You can use code to remove it something like:

/**
 * Implements hook_preprocess_HOOK().
 */
function myTheme_preprocess_page(&$variables) {
  if($variables['is_front']){
    drupal_set_title('');
  }
}


Upload multiple files through a single file dialog?

Can you try Multiupload Filefield Widget and or Multiupload Imagefield Widget

I think those modules can help you.


Javascript file is being included but console.log wont work

You need to attach complete libraries, not single library files. Your module has the name helloworld, this is the first part before the slash. In your libraries.yml you have defined the top key helloworld, this is the library name and the second part after the slash:
$attachments['#attached']['library'][] = 'helloworld/helloworld';

This line will attach all JS and all CSS listed under that specific library.
Sidenote: Try to use Drupal.behaviors instead of $(document).ready, this is the Drupal-way to do stuff like this. Otherwise you might run into problems with Ajax-calls or lazy-rendered blocks rendered with BigPipe module.


Can't access value of dropdown modified by Ajax

You shouldn't build the form element in your callback.  You want something like this:

function admin_select_meeting_type_form($form, &$form_state) {
  $meet_types = drupal_map_assoc(array('conference' => 'conference', 'event' => 'event'));
  $form['meet_types']=array(
    '#type' => 'select',
    '#title' => t('Select meeting type:'),
    '#options' => $meet_types,
    '#required' => TRUE,
    '#ajax' => array(
      'callback' => 'ajax_select_meeting_type_callback',
      'wrapper' => 'meetlist-div',
      'effect' => 'slide',
      'method' => 'replace'
    ),
  );
  $form['meet_container'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
  );
  if (!empty($form_state['values']['meet_types'])) {
    $form['meet_container']['meet'] = array(
      '#type' => 'select',
      '#title' => t('Select meeting:'),
      '#options' => drupal_map_assoc(array('test', 'test2')),
      '#required' => TRUE,
    );
  }
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save')
  );

  return $form;
}

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

// Implement ajax update of meeting select field
function ajax_select_meeting_type_callback($form, &$form_state) {
  if ($form['meet_types']['#value']) {
    return $form['meet_container'];
  }
}


how to catch when node is being promoted?

You can do it using hook_node_presave ...

Below is the code which works for me... Trick is here you need to make sure if node is new and promoted take action.. If node already promoted that means you are editing a node... You need to check whether original was unpromoted and after edit it is promoted then take action...

function YOURMODULENAME_node_presave($node) {
  if ($node->is_new && $node->promote == 1) {
    drupal_set_message("NODE PROMOTED");
    // Take Some Action
  }
  else if ($node->promote == 1 && $node->original->promote == 0){
    drupal_set_message("NODE PROMOTED");
    // Take some action
  }
}


How to pre-populate fields on a node creation form based on fields from Profile2 module?

I created a hook_form_FORM_ID_alter() function in a helper module that tests to see if the node has a NID and if so if it is not in the operation preview. Then I populate the default values of the form with the companies profile information so they can change it later.

// We need to set the default of the Job Listing fields on a new Job Listing form */
function helper_form_job_listing_node_form_alter(&$form, &$form_state) {
  // test if node for has been assigned a NID. If not then populate fields with default data */
  if (empty($form['nid']['#value']) && (!isset($form['#node']->op))){
    $profile = profile2_load_by_user ($form['uid']['#value'], 'business_profile');
    // We currently do not know what the profile language is */
    // Organization name
    if (isset($profile->field_job_organization['und'][0]['value'])){
      $form['field_job_organization']['und'][0]['value']['#default_value'] =  $profile->field_job_organization['und'][0]['value'];
    }
    // Set the default address
    if (isset($profile->field_resume_address['und'][0]['thoroughfare'])) {
      $form['field_resume_address']['und'][0]['#address']['thoroughfare'] = $profile->field_resume_address['und'][0]['thoroughfare'];
    }
    if (isset($profile->field_resume_address['und'][0]['locality'])) {
      $form['field_resume_address']['und'][0]['#address']['locality'] = $profile->field_resume_address['und'][0]['locality'];
    }
    if (isset($profile->field_resume_address['und'][0]['administrative_area'])) {
      $form['field_resume_address']['und'][0]['#address']['administrative_area'] = $profile->field_resume_address['und'][0]['administrative_area'];
    }
    if (isset($profile->field_resume_address['und'][0]['country'])) {
      $form['field_resume_address']['und'][0]['#address']['country'] = $profile->field_resume_address['und'][0]['country'];
    }
    if (isset($profile->field_resume_address['und'][0]['premise'])) {
      $form['field_resume_address']['und'][0]['#address']['premise'] = $profile->field_resume_address['und'][0]['premise'];
    }
    if (isset($profile->field_resume_address['und'][0]['postal_code'])) {
      $form['field_resume_address']['und'][0]['#address']['postal_code'] = $profile->field_resume_address['und'][0]['postal_code'];
    }
  }
}


Import orders from xls/csv to drupal commerce

I wrote a script to import orders. Here is the workflow I followed

imported all users using user_import module, the orders belongs to.
Created a custom database tables with columns needed to make an order.
Imported the excel/csv file to custom table after formating data.
Created a script to import orders and create customer profile linked to a order

Here is the script

/*
 * Helper function to facilate order import functinality.
 */

function mymodule_name_order_import_($email, $product_sku, $order_created_date, $quantity, $status, $billing_fields, $payment_method) {

  // Get product id.
  $product = commerce_product_load_by_sku($product_sku);
  $product_id = $product->product_id;

  $user = user_load_by_mail($email);
  $uid = $user->uid;

  if (!empty($uid)) {

    // Set order status.
    if ($status == "Pending") {
      $status = "pending";
    }if ($status == "Completed") {
      $status = "completed";
    }

    // Keeping order status to pending. -- Need to Change as per order. --
    $order = commerce_order_new($uid, $status);

// Save the order so its ID is assigned.
    commerce_order_save($order);

// Order created date in time stamp.
    $date = DateTime::createFromFormat('m/d/Y', $order_created_date);
    $order->created = $date->getTimestamp();

    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);

//add products to order by ids array
    $product = commerce_product_load($product_id);

// Create a line item with quantity 1 and this product.
    $line_item = commerce_product_line_item_new($product, $quantity, $order->order_id);

// Save the line item to get its ID.
    commerce_line_item_save($line_item);

// Add the line item to the order using the wrapper.
    $order_wrapper->commerce_line_items[] = $line_item;

// Get Billing Profile.
    $profile_billing = mymodule_name_order_import_map_billing_fields($uid, $billing_fields);

// Map billing address to order.
    $order->commerce_customer_billing[LANGUAGE_NONE][0]['profile_id'] = $profile_billing->profile_id;

// Get Shipping Profile.
    $profile_shipping = mymodule_name_order_import_map_shipping_fields($uid, $billing_fields);

// Map billing address to order.
    $order->commerce_customer_shipping[LANGUAGE_NONE][0]['profile_id'] = $profile_shipping->profile_id;

// Payment Method
    if ($product_sku == "25PDVDP") {
      $order->data['payment_method'] = "payment_commerce_2|commerce_payment_payment_commerce_2";
    }
    elseif ($product_sku != "25PDVDP") {
      if ($payment_method == "Credit Card") {
        $order->data['payment_method'] = "credit_cart|custom_import";
      }
      if ($payment_method == "PayPal") {
        $order->data['payment_method'] = "paypal|custom_import";
      }
      else {
        $order->data['payment_method'] = "na|custom_import";
      }
    }

// Save the order.
    commerce_order_save($order);
  }
  else {
    print "This user doesn't exists : " . $email;
  }
}

/**
 * Helper function to map billing fields.
 * @param $uid user id of user to make billing profile for.
 */
function mymodule_name_order_import_map_billing_fields($uid, $billing_fields) {
  $profile_billing = commerce_customer_profile_new('billing', $uid);
  $profile_billing->commerce_customer_address = array(
    LANGUAGE_NONE => array(
      0 => addressfield_default_values()
    )
  );

// Full Name(Required)
  $profile_billing->commerce_customer_address[LANGUAGE_NONE][0]['name_line'] = $billing_fields['name_line'];

// Country(Required)
  $profile_billing->commerce_customer_address[LANGUAGE_NONE][0]['country'] = $billing_fields['country'];

// Address 1(Required)
  $profile_billing->commerce_customer_address[LANGUAGE_NONE][0]['thoroughfare'] = $billing_fields['thoroughfare'];

// Address 2
  $profile_billing->commerce_customer_address[LANGUAGE_NONE][0]['premise'] = $billing_fields['premise'];

// City(Required)
  $profile_billing->commerce_customer_address[LANGUAGE_NONE][0]['locality'] = $billing_fields['locality'];

// State(Required)
  $profile_billing->commerce_customer_address[LANGUAGE_NONE][0]['administrative_area'] = $billing_fields['administrative_area'];

// Postal Code(Required)
  $profile_billing->commerce_customer_address[LANGUAGE_NONE][0]['postal_code'] = $billing_fields['postal_code'];

//Business name(Required)
  $profile_billing->field_business_name[LANGUAGE_NONE][0]['value'] = $billing_fields['field_business_name'];

// Who runs your front desk?(Required)
  $profile_billing->field_who_runs_your_front_desk_[LANGUAGE_NONE][0]['value'] = $billing_fields['field_who_runs_your_front_desk_'];

// Email address for the front desk person(Required)
  $profile_billing->field_email_address_front_desk[LANGUAGE_NONE][0]['value'] = $billing_fields['field_email_address_front_desk'];

// Phone(Required)
  $profile_billing->field_phone[LANGUAGE_NONE][0]['value'] = $billing_fields['field_phone'];

// Save billing profile.
  commerce_customer_profile_save($profile_billing);

  return $profile_billing;
}

/**
 * Helper function to map billing fields.
 * @param $uid user id of user to make shipping profile for.
 */
function mymodule_name_order_import_map_shipping_fields($uid, $billing_fields) {
  $profile_shipping = commerce_customer_profile_new('shipping', $uid);
  $profile_shipping->commerce_customer_address = array(
    LANGUAGE_NONE => array(
      0 => addressfield_default_values()
    )
  );

// Full Name(Required)
  $profile_shipping->commerce_customer_address[LANGUAGE_NONE][0]['name_line'] = $billing_fields['name_line'];

// Country(Required)
  $profile_shipping->commerce_customer_address[LANGUAGE_NONE][0]['country'] = $billing_fields['country'];

// Address 1(Required)
  $profile_shipping->commerce_customer_address[LANGUAGE_NONE][0]['thoroughfare'] = $billing_fields['thoroughfare'];

// Address 2
  $profile_shipping->commerce_customer_address[LANGUAGE_NONE][0]['premise'] = $billing_fields['premise'];

// City(Required)
  $profile_shipping->commerce_customer_address[LANGUAGE_NONE][0]['locality'] = $billing_fields['locality'];

// State(Required)
  $profile_shipping->commerce_customer_address[LANGUAGE_NONE][0]['administrative_area'] = $billing_fields['administrative_area'];

// Postal Code(Required)
  $profile_shipping->commerce_customer_address[LANGUAGE_NONE][0]['postal_code'] = $billing_fields['postal_code'];

// You sould pass the entire $profile object as parameter.
  commerce_customer_profile_save($profile_shipping);

  return $profile_shipping;
}

function jh_order_import_run($jh_product_sku = '') {

  //$jh_product_sku = '25PDVDP';
  $result = db_select('jh_order_import', 'joi')->fields('joi')->condition('product_sku', $jh_product_sku, '=')->execute()->fetchAll();

  foreach ($result as $key => $value) {
    echo "<pre>";
    print_r($value);
    $country = array('United States' => 'US', 'Canada' => 'CA',
      'Australia' => 'AU', 'United Kingdom' => 'GB', 'South Africa' => 'ZA');
    $jh_bill = array('name_line' => $value->full_name, 'country' => $country[$value->country],
      'thoroughfare' => $value->billing_address_1,
      'premise' => $value->billing_address_2,
      'locality' => $value->billing_city,
      'administrative_area' => $value->billing_state,
      'postal_code' => $value->billing_postal_code,
      'field_business_name' => $value->billing_bussiness_name,
      'field_who_runs_your_front_desk_' => $value->billing_front_desk_name,
      'field_email_address_front_desk' => $value->billing_front_desk_email,
      'field_phone' => $value->billing_phone,
    );
    $payment_method = $value->payment_methods;
    mymodule_name_order_import_($value->email, $value->product_sku, $value->order_date, $value->quantity, $value->status, $jh_bill, $payment_method);
    print "imported " . $key;
  }
}

NOTE: the above script is use case specific, so it will need modifications per need, but might be helpful to start with. I am using drupal commerce API's to import orders, customer profiles that's all.


Theme Suggestion for overridding page-title.html.twig file?

You can do this by adding your own suggestion. In your theme's ThemeName.theme file add a hook_theme_suggestions_HOOK_alter() for the page title:

// Add content type suggestions, e.g. page--node--article.html.twig.
function ThemeName_theme_suggestions_page_title_alter(array &$suggestions, array $variables) {
  // Are we looking at a node?
  $node = \Drupal::routeMatch()->getParameter('node');
  // Object check required, sometimes it's a string, yes, really. Who knew?
  if (!empty($node) && is_object($node)) {
    array_splice($suggestions, 1, 0, 'page_title__' . $node->getType());
  }
}

Then create templates per node type, e.g. page-title--article.html.twig, page-title--custom-content-type.html.twig etc.

Edit: rather than the array_splice you can just push suggestions onto the array, e.g.:

  if (!empty($node) && is_object($node)) {
    $suggestions[] = 'page_title__node';
    $suggestions[] = 'page_title__node_' . $node->getType();
  }

array_splice() is just a trick I commonly use to position suggestions in the $suggestions array so I can control when they are picked up and used.


Try Commerce Recurring Framework module

Overview
Provides a rules, field and entity based approach to recurring billing
for Drupal commerce.
Features
Auto-generate new orders based on recurring configuration decoupling
payment from recurring process and leveraging the payment
responsibility directly to the payment method.

Also For more details about how you can use this  Read Recurring payments in Drupal


What about getting the arrays of nids for each of the tids you want to search with taxonomy_select_nodes($tid) and then intersect the lists with array_intersect. There should be a more Drupalistic way however...


How do I add an additional database for migration?

You are on the right track. You can use

services:
  legacydatabase:
    type: mysql

And do a lando rebuild to spin up a second DB server. If you did not specify the credentials you can check them with lando info.

To use db-import (or export) you have to specify which host to use. By default it uses 'database' and not legacydatabase or whatever you called your second DB server. As per the documentation:
Options:
  --host, -h      The database service to use                  [default: "database"]

So the command to use in your case would be:

lando db-import --host legacydatabase [your_mysql_file]


Here you go: the Field Permissions module, which (as stated on its project page) "... allows site administrators to set field-level permissions to edit, view and create fields on any entity."


How to deny access if url is changed manually?

I've managed to solve this.

In my hook_form I have:

$querystring = drupal_get_query_parameters();

So for this case I just need to check if the user in the url is in the array of users allowed. If not, I can deny the access to the page (I still don't know how to deny the access though)


How to migrate content edits in Drupal from staging to live environment

I use readonlymode when migrating my sites, which I daily do to migrate localhost content to remote host.
I use drush's sqlq command to restore which better than BackupRestore module.

For proper migration, you must compare sites/all folder with that of live one. You also need to copy sites/default/files to the live one.

My typical restore goes like as in this Perl script:

chdir ("$home/public_html/$site") or die "Unable to change to site dire=$home/$site\n";

( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) =   localtime(time);

$mon++;

$year += 1900;

my $file = "$inputdir/$prefix-sql-dmp-$mday-$mon-$year.sql";

-r "$file.gz" or die "$file.gz does not exists\n";

#compare modules
my $modulesfile="$inputdir/$prefix-all-$mday-$mon-$year.tar.gz";
my $modulesdir="$home/public_html/$site/sites/all";
if( -f $modulesfile)
{
run_cmd("$home/scripts/gij-restore/dircmp.sh $modulesfile $modulesdir");
}
run_cmd ("gunzip $file.gz");

run_cmd ("drush cc all");

run_cmd_ignore ("drush cron");

run_cmd ("drush vset site_readonly 1");

run_cmd ("drush sqlq --file=$file");

run_cmd_ignore ("drush pm-disable --yes devel ");

run_cmd ("drush cc all");

run_cmd_ignore ("drush cron");

run_cmd ("drush vset site_readonly 0");

unlink "$file" or die "Failed to delete $file";

print "Site restore success\n";

sendemail($site,"Restore success!");


How to set Form API's password_confirm in/visible depending on prior select list input?

A container around the password_confirm did the trick! Fieldset works too.

$form['user_select'] = array(
  '#type' => 'select',
  '#options' => array('' => '- ' . t('None') . ' -') + _get_users_by_role('Subadministration'),
  '#required' => TRUE,
  '#description' => t('Chose account'),
);

$form['pass_wrapper'] = array(
    '#type' => 'container',
    '#states' => array(
      'invisible' => array(
        ':input[name="user_select"]' => array('value' => ''),
      ),
    ),
  );

$form['pass_wrapper']['confirm_password'] = array(
  '#type' => 'password_confirm',
  '#required' => TRUE,
  '#description' => t('Type same password in both fields'),
);


How can i limit the drop down list of countries in exposed filter?

fetchAllKeyed requires a 2-column resultset. You only have 1 column l.country in your resultset. I'm infering from your question here ...

Did you make a views exposed filter ?
Can you add a relationship to the view on the parent node to filter to the countries set on that node(s)?


Why does the upload progress bar reset at 40% when uploading large files?

I was able to fix the Upload Progress so that it didn't stop at 40% (2 GB).
This is a temporary fix:
I uncommented the ondrej repo in the sources list (/etc/apt). This gave me access to uploadprogress 1.1.3-3 which has a couple of patches that the PECL repo doesn't have.
Then I got the source code:
apt source php7.3-uploadprogress

cd php-uploadprogress-1.1.3

And changed:
int read_bytes;

to:
unsigned long int read_bytes;

and recompiled from the source:
phpize; ./configure; make; make test; sudo make install; sudo service apache2 reload

It seems like the references to int were all changed except the reference to read_bytes. The maximum value of an int is 2GB.


In your theme's template.php file:

/**
 * Implements hook_form_FORM_ID_alter().
 */

function YOURTHEMENAME_form_user_login_block_alter(&$form) {

    unset($form['links']);
    return;

}

In this function you have access to the form as an array. Usually I enable devel module and do a dsm($form) . In your case dsm() will not work because you need to be logged in to be able to see the output. I used var_dump($form) to see the form and used unset() function to remove the links.


Checkout problem - there are two possibilities that fixed it, as I re-enabled Extra Panes and Coupon UI at the same time.

I had set an extra field in Customer Shipping Profile. I didn't think it was dependent on Commerce Extra Panes, but when I disabled that module the process broke.

It could also be that the coupon UI module provides the text box on the checkout process, so when I disabled that it broke it.

Thanks for everyone's help in the comments above :)


You need to replace the token first with it's actual value.  You can do this with token_replace();

I haven't used simplenews yet, but you will need to do something along the lines of:

<?php if (token_replace('[simplenews-category:name]', array('node' => $node)) == 'fishing'): ?>
 Go fishing   <?php else: ?>
 Go sailing    <?php endif ?>

Once [simplenews-category:name] has been converted, string comparisons should work as intended.

As a note, you will likely need something other than array('node' => $node) to get this to function.


Adding a field to users from a module.install file

It is possible, in the same way forum_enable() adds a new field to the "forum" content type; the only difference is that "entity_type" and "bundle" are both set to "user."

// Create the 'taxonomy_forums' field if it doesn't already exist.
if (!field_info_field('taxonomy_forums')) {
  $field = array(
    'field_name' => 'taxonomy_forums',
    'type' => 'taxonomy_term_reference',
    'settings' => array(
      'allowed_values' => array(
        array(
          'vocabulary' => $vocabulary->machine_name,
          'parent' => 0,
        ),
      ),
    ),
  );
  field_create_field($field);
}

// …

// Create the instance on the bundle.
$instance = array(
  'field_name' => 'taxonomy_forums',
  'entity_type' => 'node',
  'label' => $vocabulary->name,
  'bundle' => 'forum',
  'required' => TRUE,
  'widget' => array(
    'type' => 'options_select',
  ),
  'display' => array(
    'default' => array(
      'type' => 'taxonomy_term_reference_link',
      'weight' => 10,
    ),
    'teaser' => array(
      'type' => 'taxonomy_term_reference_link',
      'weight' => 10,
    ),
  ),
);
field_create_instance($instance);

You can implement a similar code in the hook_enable() implementation of your module, or in the hook_install() implementation; in the first case, you should check if the field doesn't already exists, or field_create_instance() raises an exception.

To verify the field doesn't already exist, you can use code similar to the following one, where $instance is the same array as used in the previous code:

$prior_instance = field_read_instance($instance['entity_type'], $instance['field_name'], $instance['bundle']);
if (empty($prior_instance)) {
  field_create_instance($instance);
}


Why isn't there a pager and it doesn't show two records per page?

The code is wrong: Once you extend the query object, you need to save it, or it will get lost. The correct code is the following one.

$query = db_select('node', 'n');
$query = $query->condition('n.type', 'article', '=')
  ->fields('n', array('nid', 'title', 'uid'))
  ->extend('PagerDefault')
  ->limit(2);

$result = $query->execute();

foreach ($result as $node) {
  echo $node->title . "<br/>";
}

In my case, the result is the following one.

  Appellatio Fere Huic MetuoLudus Vereor

See the note shown on Extenders:

  Note that $query is not altered in place. The new object is returned from extend(), and if it is not saved to a variable it will be lost.


How do I download a JPG file from the server?

You can set the response headers from the PHP code to trigger a browser download of the file, e.g, something like:

function digitaliq_bcgrd_variable_file_download($filename) {
  $tmp = variable_get('file_public_path', conf_path().'/files').'/tmp';
  $filepath = $tmp . '/'. $filename;
  if ($data = file_get_contents($filepath)) {
    $file = new stdClass();
    $file->contents = $data;
    $file->filename = $filename;
    return EXAMPLE_serve_download($file);
  }
  drupal_not_found();
}

/**
 * Serve a file for download
 * @param $file
 * An object keyed with filename and contents
 */
function EXAMPLE_serve_download($file, $type = 'application/octet-stream') {

  if (empty($file->contents)) {
    drupal_not_found();
  }

  $headers = array(
    'Content-Type'              => $type,
    'Content-Disposition'       => 'attachment; filename="' . $file->filename . '"',
    'Content-Transfer-Encoding' => 'binary',
    'Pragma'                    => 'no-cache',
    'Cache-Control'             => 'must-revalidate, post-check=0, pre-check=0',
    'Expires'                   => '0',
    'Accept-Ranges'             => 'bytes'
  );
  if (ob_get_level()) {
    ob_end_clean();
  }
  foreach ($headers as $name => $value) {
    drupal_add_http_header($name, $value);
  }

  drupal_send_headers();
  print $file->contents;
  drupal_exit();

}


Changing Commerce Credit Card option to read something else

Alter the form that has the form_id of commerce_checkout_form_review:

/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_commerce_checkout_form_review_alter(&$form, &$form_state) {
 $form['commerce_payment']['payment_method']['#options']['commerce_payment_example|commerce_payment_commerce_payment_example'] = t('AWESOME PAYMENT');
}

The #options array will hold a list of payment methods that are keyed by the payment_method followed by a pipe (|) and then an instance_id. Just update the title accordingly.


Show a summary calculated from webform submitted values on the submission preview page only (not on form) and re-use in e-mail handler

It's not the way i'd prefer to do it, but as far as putting customization on the preview page, there is at least an alternate template available for that:
 FILE NAME SUGGESTIONS:
   * webform-submission-data--preview.html.twig
   * webform-submission-data--webform-10152--preview.html.twig
   * webform-submission-data--webform-10152.html.twig
   x webform-submission-data.html.twig

Rather than use the overall template above, we decided to do most of the work in a preprocess function for a key element on the webform.  This only affects the preview page, as it's about the HTML display not the form element.
function example_preprocess_webform_element_base_html__example_element__specific_instance(&$vars) {
  $rows = example_summary($vars['webform_submission']);
  $vars['table_summary'] = [
   '#type' => 'table',
   '#rows' => $rows,
  ];
}

We can take the {{ table_summary }} variable we added there and include it in the custom template for that element, webform-element-base-html--example-element--specific-instance.html.twig.


Check out phpSimpleSAML. There's also a similar post here:
https://stackoverflow.com/questions/7763999/magento-and-moodle-integration

Drupal can also support LDAP based logins but your sessions between both apps won't carry over so you will need a single sign on solution as mentioned above.


PDO Exception Error - How to resolve this?

Could be a MySQL configuration issue - see http://dev.mysql.com/doc/refman/5.5/en/too-many-connections.html

Or, quoting after http://drupal.org/node/930876#comment-4519490:

  If MySQL connections are not closed
  properly, then you might have an error
  within the code somewhere, that leads
  the script to end prematurely.

  In standard cases, connections are
  properly closed.

  Look at the detailed error log of your
  server, or activate on page error
  reporting if you're on a develpment
  site. You might find something useful,
  such as a forgotten dsm() somewhere
  with the devel module not being
  activated.

  The error might not be displayed and
  leads the site to look as usual, but
  the PHP process is not ended properly,
  leaving MySQL connections opened.

Start with checking your error logs and try to find out why this could be happening there.


In general, every .tpl.php file has an equivalent preprocess function for it.  And, in general, the preprocess function and template files have the same name (in the Drupal sense).

The function you want is template_preprocess_views_view_table().  You can place this in a module, or in your theme.  Just name it accordingly.

Look at the default preprocess function for how the $view gets pulled out and/or dpm($variables['view']).  You will likely need to examine it to limit the function to just the view/display you need.

You can also try implementing MYMODULE_preprocess_views_view_table__commerce_cart_form() to limit to just that instantiation, but I don't recall if the Views module will do this.

The Theme Developer module can also help out tracking down what preprocess functions get called for each .tpl.php file.


When you are implementing hook_schema_alter(), the table's schema is not changed.
You are informing the modules calling drupal_get_schema() (which is then called by functions such as drupal_write_record()) what the actual schema is. If you altered a database table without implementing hook_schema_alter(), the functions/modules using drupal_get_schema() would get the schema implemented by the module using that database table, which is not anymore the one describing the database table.

You need to first alter the existing database table using db_change_field(), taking in consideration the following note:

  IMPORTANT NOTE: To maintain database portability, you have to explicitly recreate all indices and primary keys that are using the changed field.


The issue was that it was removing the HTML element so the second call had no HTML to replace.  Changed to either use ajax update or on the call back wrap the return in the div again


Order product ID field returns "0" in Views

I've also experienced this issue by creating hook_views_data_alter adding  the following code into it:

$data['uc_order_products']['order_product_id']['field'] = array(
    'handler' => 'views_handler_field_numeric',
);

I have noticed that the order_product_id had no handler so since the return of this field is the ordered product id I just went ahead and used the handler that comes with Views views_handler_field_numeric.

If you'd like, I bunched some additions related to the order product id field in my custom module in Ubercart-Add-ons.


The easiest way IMO to do this is to use the views field template. Here is a very detailed and helpful tutorial on DO. You can find the field template's name in the views theming tab under the advanced tab.

In terms of implementation for your use-case, the field's $output in the template would be empty if there is no link, and then you can change $output to be the link to that node (which you should be able to access with $row->nid).


Easiest way would be to change the access callback to the user page (user/%user) via hook_menu_alter.
The new access callback would use the value of a user field to determine or the page is accessible or not.

Code to give you an idea of the structure, not a fully functioning example

YOUR_MODULE_menu_alter(&$items){
  $items['user/%user']['access callback'] = 'user_profile_is_private';
}

function user_profile_is_private($user){
  // Check the content of the user field here and return true/false.
}

This tells drupal to use the user_profile_is_private function to determine or people can access the user page or not. This function should return true/false.
The user object is passed to this function via the core user module already.

You'll need to add the core user access function user_view_accessin there somehow to prevent this change to override all other access settings.


Download true file name instead of from drupal version changed filename

Is all depends on how your loading the file information. As the filename field in the file_managed table will always be whatever is uploaded. e.g.
filename = mypdf.pdf
uri = mypdf_1.pdf

So you can always use the filename value for the real file name. It sounds like whatever you're using to load the file/create the file link isn't using this correct value


How translate a static block in drupal 6?

try this:

if ($user->language == 'ru') print 'Привет чувак!';
if ($user->language == 'en') print 'Hey Dude!';


How can I check a Rules condition to see if the Statuses sender and recipient are the same?

This should do what you want.

if($status->sender == $status->recipient) {
  drupal_set_message('A match');
}
else{
  drupal_set_message('Not a match');
}

Rules Code

{ "rules_status_test" : {
    "LABEL" : "Status Test",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "php", "rules", "fbss_rules" ],
    "ON" : { "statuses_save" : [] },
    "IF" : [
      { "php_eval" : { "code" : "if($status-\u003Esender == $status-\u003Erecipient) {\r\n  drupal_set_message(\u0027A match\u0027);\r\n}\r\nelse{\r\n  drupal_set_message(\u0027Not a match\u0027);\r\n}" } }
    ],
    "DO" : []
  }
}


We don't recommend the built-in Aegir SSL feature (yet), as explained in BOA docs.

Anyway, on BOA/Octopus, the directory you are looking for is located in the /data/disk/USER/config/ tree.


When creating a new user with a order, how to email the new user login details

I have achieved this using Rules

The Rule is as follows.

Events
After updating an existing commerce order

Conditions
Data value is empty - commerce-order:owner:last-login

Actions
Send account e-mail

The reason why I have used this Event rather than 'After creating a new order' is to do with how this 'Commerce Admin Order Advanced' module works. You create the order before adding line items. And since I only need this email to be sent when a certain product type is created, this should suffice, hence I add the following condition

Order contains products of particular product types - Bespoke (an arbitrary product type)

But in order to prevent these emails being sent again should an admin update the order again, I have added the following extra Condition

Data comparison - commerce-order:created == commerce-order-unchanged:changed


Get the node title conditionally in a view rewrite field

Is title a field you made or do you mean the node title? Node title can be printed with either {{ label }} or {{ node.getTitle() }}.

Fields that you created on the node, they are rendered out as:

{{ content.field_title }}

Which can be checked as:

{% if node.field_title_external is not empty  %}
  {{ content.field_title_external }}
{% else %}
  {{ node.getTitle() }}
{% endif %}

You can also use {{ label }} instead of {{ node.getTitle() }}.


Rewriting output of existing content block

You can try hook_block_list_alter() hook.

Act on blocks prior to rendering.

This hook allows you to add, remove or modify blocks in the block list. The block list contains the block definitions, not the rendered blocks. The blocks are rendered after the modules have had a chance to manipulate the block list.

You can also set $block->content here, which will override the content of the block and prevent hook_block_view() from running.


How to set a coming soon page on drupal?

You can put the site on maintaince mode and can use the message as coming soon.


For a quick non-programmatic solution, you can consider using the Menu blocks module to render 2nd level menu items in 6 separate blocks, then render the blocks in the regions you want. On top of this you can also add customer classes on menu items with Menu attributes module.
If you don't mind a javascript approach, you can manipulate dom to move the sub menus around.
If you are familiar with the theme layer, you can create your custom theme function for main menu by implementing themename_links__system_main_menu.


What is the syntax for the 'Query string value' in a view argument input?

Syntax depends on your view display path, e.g. for page displays.

For example, if your page display path is url_to_view_page/% then the syntax is:

url_to_view_page/foo.

If you do not have a path, then you'll always fall back on the contextual filter not provided behavior, this is always the case for blocks.


For anyone with the same problem, what I had to do was:

function mymodule_page_alter(&$page) {
    unset($page['content']['system_main']['comment_node']);
}

I'm not fond of having to do this, but I couldn't figure out why the content type was displaying.


How to display a custom block as a pop on home page?

There are other modules which provide you the popup functionality.

Popup message

  Display popup message for users once per browser session. Based on
  javascript code:
  http://yensdesign.com/2008/09/how-to-create-a-stunning-and-smooth-popup-...

Lightbox2

  The Lightbox2 module is a simple, unobtrusive script used to overlay
  images on the current page. It's a snap to setup and works on most
  modern browsers.

Shadowbox

  Shadowbox is a JavaScript modal media viewer application for viewing
  images, video, Flash and other content in a modal window.


Static field works, dynamically modified element gets lost

instead of over writing the form element just edit variables you want to change something like below

  $publishers = array( 'pub1' => 'Publisher 1', 'pub2' => 'Publisher 2' );

  $form['field_publisher_code']['#type'] = 'select';
  $form['field_publisher_code']['#options'] = $publishers;
  $form['field_publisher_code']['#multiple'] = FALSE;

I presume your $form already has the variable when you get the form.


Hook into other module's field formatter?

The question mentions that hook_field_formatter_view() is only called on the originating module, but you can take ownership of the field formatter via hook_field_formatter_info_alter().

You should be able to set the module key of the formatter to MYMODULE like:

function MYMODULE_field_formatter_info_alter(&$info) {
  $info['some_field_formatter']['module'] = 'MYMODULE';
}

Then you can implement MYMODULE_field_formatter_view(), optionally feeding through the existing module which handled it to get an element to alter.

function MYMODULE_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  // Your custom logic
  $element = OTHER_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display);
  // Any alterations
}


How to retrieve GET parameter in Twig template

You didn't say what template this is for, but app is not defined in any of the templates I have seen.

What you could do, is add a theme_preprocess_TEMPLATE function to include the GET params. Here is a page template example:

In your mytheme.theme file, add a hook_preprocess_page function.

/**
 * Implements hook_preprocess_page()
 */
function MYTHEME_preprocess_page(&$vars) {
  $vars['get']['name'] = $_GET['name'];
}

Then in your page.html.twig you can render it like this:

<h1>{{ get.name }}</h1>


Enable a button basing on multiple form values being equal

'array('value' => ':input[name="confirm_password"]')

This means the value equals the literal string ":input[name="confirm_password"]".
As far as I know, #states can't check if the value of two fields are the same.

  I can do this with JavaScript, potentially, but then the JavaScript
  code would managing some states and the PHP code would manage other
  states. It seems messy.

Here is a way that may seem less messy. Use a hidden compare_passwords field whose value will indicate whether the password and confirm_password fields have the same value:

$form['compare_passwords'] = array('#type' => 'hidden', '#default_value' => 'fail');

Use the value of that field in the #states array for your button.

':input[name="compare_passwords"]' => array('value' => 'match')

Write some JavaScript that changes the value of compare_passwords whenever the value of password or confirm_password changes (use .on() instead of bind() if your site uses jQuery 1.7+):

var password_selector = ':input[name="password"]';
var confirm_selector = ':input[name="confirm_password"]';
var compare_selector = ':input[name="compare_passwords"]';
$(password_selector + ',' + confirm_selector).bind("change paste keyup blur", function () {
  if ($(password_selector).val() == $(confirm_selector).val()) {
    $(compare_selector).val('match').change();
  } else {
    $(compare_selector).val('fail').change();
  }
});

By the way, you can use '!value' to put all your "does not equal empty string" conditions under "enabled", using the Boolean "AND" structure. The Boolean "OR" structure, which is wrapping each condition in its own array, is harder to understand if you aren't familiar with #states.

// Only enable the button when all fields have a value and passwords match.
// The value in "compare_passwords" is dynamically updated by my_script.js
//  whenever the user types inside the password or compare_password fields.
$form['my_button']['#states'] = array(
  'enabled' => array(
    ':input[name="field1"]' => array('!value' => ''),
    ':input[name="field2"]' => array('!value' => ''),
    ':input[name="password"]' => array('!value' => ''),
    ':input[name="confirm_password"]' => array('!value' => ''),
    ':input[name="compare_passwords"]' => array('value' => 'match'),
  ),
);


So i solved it. In hook_views_pre_render i added something like:

if($view->name=='property_list'){
// ..got the xml , processed it
// and in the folowing array I added; of course field_address is an item in a content type
$view->result[$i]->field_field_address[0]['rendered']['#markup'] = $child->address;
// if i wanted the field to be a link, then altered this array item
$view->result[$i]->field_field_address[0]['rendered']['#path']['path'] = 'property-detail?id='.$child->ID;
}

The link pointed to another view where the detailed property was shown;


How to link different contents together and display the linked content on the same page?

Images are just media assets on a site. By which I mean you're relating something specific in X to another thing in Y -- you could just as easily relate content titles.

You likely want to either relate things together using Tagging via Taxonomies. Taxonomies can also have associated images for example. Or, you want to relate content around with relationships:

Entity Reference
Relation

Without a concrete mocked-up example with wireframes and in-depth explaination of requirements .... good luck.


What's the correct way to add attributes to a Link field?

There were some close ones, but this is the correct way to set an attribute to the first link:

function mymodule_preprocess_field(&$variables) {
  if ($variables['field_type'] == 'link') {
    $variables['items']['0']['content']['#attributes']['target'] = '_blank';
  }
}


How to preprocess output of $user_picture in Drupal 7?

In the core user module you can find user-picture.tpl.php. Copy this file to your active theme, edit it and be sure to clear cache.

If you need to go deeper, put this in your theme's template.php. Original can be found in user.module.

function yourthemename_preprocess_user_picture(&$variables) {
  $variables['user_picture'] = '';
  if (variable_get('user_pictures', 0)) {
    $account = $variables['account'];
    if (!empty($account->picture)) {
      // @TODO: Ideally this function would only be passed file objects, but
      // since there's a lot of legacy code that JOINs the {users} table to
      // {node} or {comments} and passes the results into this function if we
      // a numeric value in the picture field we'll assume it's a file id
      // and load it for them. Once we've got user_load_multiple() and
      // comment_load_multiple() functions the user module will be able to load
      // the picture files in mass during the object's load process.
      if (is_numeric($account->picture)) {
        $account->picture = file_load($account->picture);
      }
      if (!empty($account->picture->uri)) {
        $filepath = $account->picture->uri;
      }
    }
    elseif (variable_get('user_picture_default', '')) {
      $filepath = variable_get('user_picture_default', '');
    }
    if (isset($filepath)) {
      $alt = t("@user's picture", array('@user' => format_username($account)));
      // If the image does not have a valid Drupal scheme (for eg. HTTP),
      // don't load image styles.
      if (module_exists('image') && file_valid_uri($filepath) && $style = variable_get('user_picture_style', '')) {
        $variables['user_picture'] = theme('image_style', array('style_name' => $style, 'path' => $filepath, 'alt' => $alt, 'title' => $alt));
      }
      else {
        $variables['user_picture'] = theme('image', array('path' => $filepath, 'alt' => $alt, 'title' => $alt));
      }
      if (!empty($account->uid) && user_access('access user profiles')) {
        $attributes = array('attributes' => array('title' => t('View user profile.')), 'html' => TRUE);
        $variables['user_picture'] = l($variables['user_picture'], "user/$account->uid", $attributes);
      }
    }
  }
}


One option:

create a content type (sentence) with only a title (sentence 1, sentence 2, etc) and body
create 20 pieces of sentence content, each with one of the sentences you want
create a new View, content type: sentence, page, show 20, no pager, table of fields
add the body field to the table, and remove the title

Now download the Editable Views module:

  Editable Views lets you create Views where the fields can be edited.
  Fields show both the current value and a form to edit it. A 'Save'
  button allows saving of all the entities shown in the View.

  Editable fields can be added on the base entity as well as on entities
  brought into the View by a relationship. Other, non-editable fields
  may be added to the View, in which case they function normally.

and set it up for that View of sentences.

create your normal View of Grid, with the body field from the sentence content type and set it up however you would normally do so

With this set up, you can easily create the grid of sentences you want, plus it will create an easy way to edit those sentences (Editable Views) so that you don't need to go to 20 different pieces of content to update the field - it can all be be done from one View page


Are there Get/Set methods for addressing commerce line_items and order object properties?

What you're doing is correct for Commerce 1.x.  Drupal 7 just uses stdClass objects for entities, no methods. Fortunately Commerce 1.x isn't seeing any significant changes - any time we make an API change it will be heavily noted in the change log of a new release. Additionally, Commerce 2.x on Drupal 8 is actually able to use robust classes for entities, so the future is brighter.


How to add a value to a field via custom button

The problem is complex. I think one way to address what you want is to code a JS behavior that is attachted to your block view that when user click each venue the venue value is added to the field and add more elements button is clciked, so Drupal reconstructs the form adding a new element.

Steps:

Add the venue nid to your View but hide it using CSS. This is a quick-and.dirty way to have the Venu nid available for your JS code. A better way is to alter the views output and add the nid in some other way.
Add a JS file for your module that will be added in that add form (use form alter and the $form['#attached'] key.
Your JS file should be a Drupal behavior JS that will attach a click listener to your venues elems in the block. When clicked, the listener will have to locate the last empty venue form field element, put clicked venue nid in that field elem and click the 'Add more' button of that multiple value field to trigger and AJAX call that will make Drupal to reconstruct the form and add a new empty value for the venue form element.

But the easy way is to use Entity Reference View Widget. The behavior is not exactly what you want but I think it can fit your needs.

This module allows to open a popup with a View where you can select the values of the field. As the popup is filled woth a View you have all the power if Views to modify what user sees in the view.


My current method is dirty:

  $build['search_form_resort'] = $build['search_form'];
  unset($build['search_form']);

Then put the $build['search_form_resort'] under the $build['suggestions'].

Read more:
http://api.drupal.org/api/drupal/modules%21search%21search.pages.inc/function/search_view/7


I just tested that exact code in Drupal 7 and it's working perfectly!  The full view displays two or more images and a view of teasers just shows one image per node.

HOWEVER, I did notice the following: if you're just in the process of building a view the Preview below the view does not display the final output correctly.  The Preview in the view of teasers shows multiple images per teaser, but if you just go ahead and hit 'save' and then test your view (by going to its link if it's a page), you'll see that it actually displays correctly.

Does that end up working for you?


Custom MigrateMap to sync by field or property, e.g. SKU

The map class doesn't (and shouldn't) know anything about either your source or your destination - its job is simply tracking the relationships between their keys.

I've done this in the migration's prepareRow(), doing an explicit lookup for a matching destination object, and if found saving that destination ID to the map and returning FALSE to prevent further processing. Look at how migrate_d2d maps user accounts based on email:

// On initial import, if this email address already exists, just map to the
// existing uid and don't allow it to be deleted. When updating, we can
// take the existing uid from the map instead of querying for it. Make sure
// when updating an imported user that we don't apply this logic.
if (empty($row->migrate_map_destid1)) {
  $new_uid = db_select('users', 'u')
             ->fields('u', array('uid'))
             ->condition('mail', $row->mail)
             ->execute()
             ->fetchField();
  // If we haven't mapped the admin account based on email address, map it
  // directly to the destination admin account.
  if (!$new_uid && $row->uid == 1) {
    $new_uid = 1;
  }
}
elseif ($row->migrate_map_needs_update == MigrateMap::STATUS_IGNORED &&
        $row->migrate_map_rollback_action == MigrateMap::ROLLBACK_PRESERVE) {
  $new_uid = $row->migrate_map_destid1;
}

if (!empty($new_uid)) {
  $hash = isset($row->migrate_map_hash) ? $row->migrate_map_hash : NULL;
  $this->map->saveIDMapping($row, array($new_uid), MigrateMap::STATUS_IGNORED,
    MigrateMap::ROLLBACK_PRESERVE, $hash);
  $this->rollbackAction = MigrateMap::ROLLBACK_PRESERVE;
  return FALSE;
}


You can use the EntityFieldManager. This is an example how to get the properties for the field uid of the entity node:

$fields = \Drupal::service('entity_field.manager')->getFieldStorageDefinitions('node');
$properties = $fields['uid']->getPropertyDefinitions();

From the command line you can use this in a drush php-eval command:

drush ev "var_dump(\Drupal::service('entity_field.manager')->getFieldStorageDefinitions('node')['uid']->getPropertyDefinitions())"


Any other ways I can stop the  page from being cached by boost?

What is the actual url of your front page?
If your frontpage is the default ( /node ) then you need to add both 'node' and '' to your exceptions list.
Boost treats them differently and keeps a copy of each page in the cache.

You can inspect the cache files that boost creates (these are actually plain html files) in the cache apache root folder.


How can I get a list of the patches I submitted for issues on drupal.org?

If you contributed patches, they will be credited to you. In that case, on your profile, you will see the ones credited to you in the past 3 months. In my case, I see the following.

Keep in mind that sometimes you participate in an issue without contributing patches, and you get credited for participating.

Unfortunately, there isn't a page with all the credited issues for all the projects, but if you have a list of the projects to which you contributed patches, you can get the list of the credited issues for that project by looking at https://www.drupal.org/u/<username>/issue-credits/<project-id>, where <username> is the username on drupal.org (in my case, kiamlaluno) and <project-id> is the ID for the project (for example, 3060 for Drupal core). So, if I would want to look to all the patched I submitted for Drupal core, I would look at https://www.drupal.org/u/kiamlaluno/issue-credits/3060.

It seems that the list of credited patches has been created on 2015, so you would not get any credited patch before that year.


How do I override the admin theme in my own theme?

You can add admin CSS from a module hook.  Replace XXX with the module name.

1 Put your CSS in css/extra.admin.css

2 Declare a library by creating XXX.libraries.yml

extra.admin:
  css:
    theme:
      css/extra.admin.css: {}

3 Create a hook to load the library.

/**
 * Implements hook_page_attachments().
 */
function XXX_page_attachments(array &$attachments) {
  $theme = \Drupal::theme()->getActiveTheme()->getName();
  if ($theme == 'seven') {
    $attachments['#attached']['library'][] = 'XXX/extra.admin';
  }
}


Make a field state change depending on the moderation state field

Drupal API: function drupal_process_states

Example A where the source fieldtype is a textfield

$form['moderation_state'] = [
  '#type'  => 'textfield',
  '#title' => ('Some title'),
];

$form['schedule_publish_date'] = [
  '#type'   => 'textfield',
  '#title'  => ('Invisible if ...'),
  '#states' => ['invisible' => [':input[name="moderation_state"]' => ['value' => "published"],],],
];

Example B where the source fieldtype is a select-field

$form['moderation_state'] = array(
  '#type'          => 'select',
  '#title'         => t('Some title'),
  '#options'       => array('unpublished'=>'unpublished', 'published'=>'published'),
  '#default_value' => 0,
);

$form['schedule_publish_date'] = [
  '#type'   => 'textfield',
  '#title'  => ('Invisible if ...'),
  '#states' => ['invisible' => [':input[name="moderation_state"]' => ['value' => "published"],],],
];


Why do form builders have a $form parameter?

Its an interesting question as there are now two ways of altering forms.

Using HOOK_form_alter ie book_form_node_form_alter with $form by ref and by inheritance returning $form as done in ie \Drupal\forum\Form\Overview::buildForm

class Overview extends OverviewTerms {
  ...
  public function buildForm(array $form, FormStateInterface $form_state) {
    ...
    $form = parent::buildForm($form, $form_state, $vocabulary);
    ...
    return $form;
  }
  ...
}

where \Drupal\taxonomy\Form\OverviewTerms::buildForm gets called using $form = parent::buildForm($form, $form_state, $vocabulary); thus in fact zapping $form.

Most code seems to return parent::buildForm($form, $form_state, ...); which we could call 'method' 3.

I guess hook_form_alter will disappear in the next version (10.x?) in favour of event listeners


I think there are 2 possible approaches, as further explained below (I'm assuming you're using Drupal version 7, not 6).

Use a boolean field to exclude from the calendar

For the content types that you want to include in your calendar, add a boolean field like "Exclude from Calendar" (Y/N). When creating your view, filter out the nodes that have a value of "Y" for this field.

Use 'Views Contextual Filters OR'

Consider module Views Contextual Filters OR (which only has a dev version today). Excerpt from its project page:

  ... provides a views plugin which modify query to support OR conditions for contextual filters.

With that, you might be able to specify the various dates to be excluded, with something like date1 OR date2 OR ... (if you only have a few dates to be excluded o course).

Does this help?


Slideshow Question - Slider for images uploaded to a node

While I haven't specifically used Views Nivo Slider, I have used Views Slideshow to display uploaded CCK images in a view. The trick here is to use Arguments (or Contextual Filters, depending on which Views UI you're using) from the current nid, with a view that is set to display image fields.


There are several issues that could be plaguing you related to various configurations. However as a starting point, let's start with the basics:

Clear all caches. This will clear most issues caused by upgrades.
Rebuild permissions. Sometimes new access permissions or changes to old ones occur during upgrades. Since the fields still exist, but are not seen in the content view, it's possible that a permissions error is in your way.

http://www.example.com/admin/reports/status/rebuild
Check your PHP logs. Sometimes issues can occur with PHP where upgrades adding new features break things in a subtle way. Running out of memory, or breaching the 'max_input_vars' threshold are common issues I've seen.


how can I have Infinite pager in mini_page views?

I use this reference views mini pager. In order to do this in your template.php you need to call the function for that view mini pager. In order to find out which is the best for you, use the theme developer module.

The trick is to change what happens when empty($li_previous)) and (empty($li_next)). If there is a better way to accomplish this, please let me know.

function my_theme_name_views_mini_pager__yourview($variables){

  global $pager_page_array, $pager_total;

$tags = $vars['tags'];
  $element = $vars['element'];
  $parameters = $vars['parameters'];
  $quantity = $vars['quantity'];

  // Calculate various markers within this pager piece:
  // Middle is used to "center" pages around the current page.
  $pager_middle = ceil($quantity / 2);
  // current is the page we are currently paged to
  $pager_current = $pager_page_array[$element] + 1;
  // max is the maximum page number
  // first is the first page listed by this pager piece (re quantity)
  $pager_first = $pager_current - $pager_middle + 1;

  $pager_last = $pager_current + $quantity - $pager_middle;
  // max is the maximum page number

  $pager_max = $pager_total[$element];
  // End of marker calculations.

  if ($pager_total[$element] > 1) {
  $li_previous = theme('pager_previous',
  array(
  'text' => (isset($tags[1]) ? $tags[1] : t('')),
  'element' => $element,
  'interval' => 1,
  'parameters' => $parameters,
)
);

if (empty($li_previous)) {
  $li_last = theme('pager_last',
   array('text' => (isset($tags[4]) ? $tags[4] : t('')),
  'element' => $element,
  'parameters' => $parameters));

  $li_previous =$li_last;

}

$li_next = theme('pager_next',
  array(
  'text' => (isset($tags[3]) ? $tags[3] : t('')),
  'element' => $element,
  'interval' => 1,
  'parameters' => $parameters,
)
);

if (empty($li_next)) {
  $li_first = theme('pager_first', array('text' => (isset($tags[0]) ? $tags[0] : t('')), 'element' => $element, 'parameters' => $parameters));
  $li_next = $li_first;

}

$items[] = array(
  'class' => array('pager-previous'),
  'data' => $li_previous,
);

$items[] = array(
  'class' => array('pager-current'),
  'data' => t('@current of @max', array('@current' => $pager_current, '@max' => $pager_max)),
);

$items[] = array(
  'class' => array('pager-next'),
  'data' => $li_next,
);

return theme('item_list',
  array(
  'items' => $items,
  'title' => NULL,
  'type' => 'ul',
  'attributes' => array('class' => array('pager')),
)
);

}

}


As mentioned above, the Node Access User Reference module does exactly that. You specify a list of user and grant them actions upon the node. Awesome.


How can I use the Private Message module for anonymous users?

The Privatemsg module CANNOT be used for anonymous users ... Unless you are ready for some "tweaks" ... as detailed below.

I'm assuming your question is about D7, if it is for D6, you might consider using what's described in Issue # 490264. But it's worth reviewing that issue to get "an idea" about a possible work around ...

So how about D7? Issue # 554238 is about D7, and Comment #7 in it refers to the issue I mentioned above (which is for D6). However Comment #8 in that issue might be the solution. It contains this code sample:

<?php
$msg = "Hello there";
$source_tag = "from {$_SERVER['REMOTE_ADDR']}";
$result = privatemsg_new_thread( array(user_load(1)), "Browser visit {$source_tag}", $msg, array('author' => user_load(1)) );
// If you wanted to show an error, uncomment the following:
if (!isset( $result['success'] ) || !$result['success'])
{
  printf( "
Failed to send: %s
\n", $result['error'] );
}
?>

Apart from what is above, there is also the (way more) recent issue # 2231795. Comment #1 in it contains a code sample also. So if the above code doesn't fit (or work), consider this as an alternative.

So by using the Privatemsg module, and some tweaks (see above) you should be able to make it work somehow for anonymous users also


Exclude from list view some articles based on their content type?

You can add this rule to Filter criteria section as on screen


CTools modal with webform unable to close

We figured it out - this was being caused by the ThemeKey module. The base page was one theme, and the ajax call was requesting default theme, trigging a reload of all the javascript.

The solution is to enable  'Bypass a request forgery protection in theme selection for Ajax responses.' and select the safe themes.


Can anyone recommend a good Drupal module for managing/displaying videos

Drupal 6: Embedded Media Field. Now has a D7 version too.

  This extensible module will create fields for content types that can be used to display video, image, and audio files from various third party providers. When entering the content, the user will simply paste the URL or embed code from the third party, and the module will automatically determine which content provider is being used. When displaying the content, the proper embedding format will be used.

Drupal 7: Media

  The Media module provides an extensible framework for managing files and multimedia assets, regardless of whether they are hosted on your own site or a 3rd party site - it is commonly referred to as a 'file browser to the internet'.


Hooking into an update of the db system table

You should be able to use hook_themes_disabled().

The following code in a module will put themes being disabled into the Drupal logs:

function MYMODULE_themes_disabled($theme_list) {
  foreach ($theme_list as $key => $themename) {
    watchdog('MYMODULE', '%themename was disabled.', array('%themename' => $themename), WATCHDOG_NOTICE);
  }
}

EDIT:  Forgot to mention this, but hook_themes_enabled() is used in exactly the same way, so you could easily just modify the hook above to check when a theme is enabled.


It is possible to clone a View Display (in this case an attachment). For example:

Go to admin/structure/views/view/frontpage on your Drupal site
Select the 'Feed' Display under Displays
Under 'Feed details', notice the 'Display name' field, look all the way to the right of here and you'll notice a 'view Feed' drop down menu, click the 'down' icon
Then click 'clone Feed'

That will cone that particular display, click 'Save' when you're ready to save the changes. For your attachment, follow the steps above and replace the steps with your view, and the name of your attachment.


How can I get Slick Slider to display the images?

I accomplished what you're trying to do using Slick Carousel together with Slick Views.
You can create a content-type that you intend to be aggregated into the slideshow.  In my case a testimonial type consisting of a background image and overlying text.
You can create a views block and set its format to Slick Carousel.  You will be provided with setting options to configure the slideshow as you wish.
Filter your view by the content-type you want to comprise your slideshow, in my case testimonial.
lastly, pull your views block slideshow into another piece of content via entity reference.


Views - Clicked element + corresponding content

Step 1: Create the View, the block and the required fields (order matters).

Block's instructions (page can be different):

Format:

Grid
Number of columns: 2

Fields:

Nid: Exclude from display
Title:

Link this field to the original piece of content: Unchecked
REWRITE RESULTS -> Rewrite the output of field -> Output this field as a link -> Link path: ajax-link/nojs/[nid]
Link class: use-ajax

Image:

Link image to: Nothing
REWRITE RESULTS -> ... Same as "Title"
Link class: use-ajax

So, the title's or image's url should have this structure: hook-menu-registered-path/nojs/argument

Step 2: Create a custom module and implement the following code.

/**
 * Implements hook_menu.
 */
function custom_module_menu() {
  // A menu callback is required when using ajax outside of the Form API.
  $items['ajax-link'] = array(
    'page callback' => '_custom_module_response',
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 *  Callback function.
 *
 * @param int $nid
 *   Either a valid node id or 0 (zero) if not available.
 *
 *  @param string $type
 *   Either 'ajax' or 'nojs. Type is simply the normal URL argument to this URL.
 *
 *  @return string|array
 *    If $type == 'ajax', returns an array of AJAX Commands,
 *   otherwise, just returns the content, which will end up being a page.
 */
function _custom_module_response($type, $nid = 0) {
  $output = _custom_module_node_load($nid);
  if ($type == 'ajax') {
    $commands = array();
    // Selector: A jQuery selector string, either a .class or #id.
    $commands[] = ajax_command_replace('.selector', '
' . $output . '
');
    $page = array('#type' => 'ajax', '#commands' => $commands);
    ajax_deliver($page);
  }
  else {
    $output = isset($output) ? '
' . $output . '
' : t('Node does not exist!');
    return $output;
  }
}

/**
 *  Node loader function.
 *
 *  @return string
 *   The themed node in its define view mode.
 */
function _custom_module_node_load($nid = 0) {
  $node = node_load($nid);
  if ($node) {
    $pre_rendered_node = node_view($node, $view_mode = 'full');
    return theme('node', $pre_rendered_node);
  }
}

Step 3: Load the necessary library. I chose the template.php file to do it.

/**
 * Implements template_preprocess_views_view.
 */
function custom_theme_preprocess_views_view(&$vars) {
  $view = $vars['view'];
  if ($view->name == 'my_view_name') {
    // drupal_add_library is invoked automatically when a form element has the
    // '#ajax' property, but since we are not rendering a form here, we have to
    // do it ourselves.
    drupal_add_library('system', 'drupal.ajax');
    $output = '
' . $vars['rows'];
    $output .= '
';
    $vars['rows'] = $output;
  }
}

Now, should only the body field must be displayed (or a certain set of fields) I suggest the definition of a view mode per case, then define that view mode to the node_view function.

Note:

Ajax framework's "magic" class: use-ajax

  By adding the 'use-ajax' class to a link, the link will be loaded via an Ajax call. When using this method, the href of the link can contain '/nojs/' as part of the path. When the Ajax framework makes the request, it will convert this to '/ajax/'. The server is then able to easily tell if this request was made through an actual Ajax request or in a degraded state, and respond appropriately.

Ref.: Drupal examples modules, How to use Drupal 7's built-in Ajax Framework


Rule for sending email when order exceeds a defined weight

After some fiddling I've found the solution myself:

    { "rules_notice_overweight" : {
    "LABEL" : "Overweight",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "commerce_physical", "rules", "commerce_shipping" ],
    "ON" : { "commerce_shipping_calculate_rate" : [] },
    "IF" : [
      { "commerce_physical_rules_order_weight_comparison" : {
          "commerce_order" : [ "commerce-line-item:order" ],
          "operator" : "\u003E",
          "value" : "10",
          "unit" : "kg"
        }
      }
    ],
    "DO" : [ { "drupal_message" : { "message" : "Total weight is over 10kg" } } ]
  }
}

The problem in my first code example was the trigger "commerce_shipping_collect_rates". It has to be "commerce_shipping_calculate_rate" instead. I hope someone can benefit from that.


The solution I used is below for anybody else who might have similar questions.

You can use the autocomplete_route_name property to get the options for autocompletion.

$element += array(
    '#type' => 'textfield',
    '#default_value' => $items[$delta]->value ?: NULL,
    '#autocomplete_route_name' => 'example.myroute',    //your route name
    '#placeholder' => $this->getSetting('placeholder'),
);

The route should be defined in your module_name.routing.yml file

example.myroute:
    path: <url>
    defaults:
      _controller: <controller>::<method>
    requirements:
      _permission: <permission>

Hope this helps :)


Since the blog URL is hard coded, make an alias using the (core) path module.


Skip words/vary word order in search for autocomplete suggestions

Doing this would require a different selection handler. Look at class Drupal\Core\Entity\Plugin\EntityReferenceSelection to see how the default selection handler works. In particular you need to create a different buildEntityQuery method. I don't know of any module that provides a handler to do this, and I'm not sure how I would go about accomplishing it myself. Sorry I can't give a more satisfactory answer.


Hide a particular radio box item in a set

To remove the entire field on the form, you can definitely do something like this

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

  if ($form_id == "form_id_for_form_you_want_to_modify") {
    if (isset($form["field_you_want_to_remove"])) {
      unset($form["field_you_want_to_remove"]);
    }

  }

  return $form;
}

To change or remove a specific option on the field you can access and alter it with $form['field_your_field']['und']['#options']

(note: If your site is multilingual, you'll need to alter more than just ['und']. In this case ['und'] means undefined language code).

You can also alter the field type with:

$form['field_your_field']['#type'] = 'checkboxes';

It all depends on what you're trying to accomplish.


Displaying a block on a content profile page passing the content profile nid into the block

Add an argument of type Node[nid] to your views

Configure Action to take if argument is not present for Provide default argument as PHP Code

Add following code in the text area

  $node = node_load((int)arg(1));
  return $node->uid;


How do i run the equivalent of single configuration import from a hook?

if (\Drupal::moduleHandler()->moduleExists('views') && !View::load('view_name')) {
    $config_path = DRUPAL_ROOT.'/configurationpathto/views_view_view_name.yml';
    $data = Yaml::parse($config_path);
    \Drupal::configFactory()->getEditable('views.view.view_name')->setData($data)->save(TRUE);
  }


How to auto-yes "drush features-revert-all" ... via terminus

You need to add a -- separator to your command. The options for Terminus come before this marker, and the options for Drush come after.

In other words:

terminus -y drush site.dev -- features-revert-all -y

Explanation:

In programs that support it, -- means "all of the options that come after should be treated as arguements". The command terminus drush passes all of its arguments through to Drush.


node-NAME.tpl.php doesn't override the node template. I've cleared theme registry

You mispelled the filename. Drupal 7 now uses double dashes (--); your file needs to be node--NAMEOFTHENODETYPE.tpl.php.


Displaying content type in translated languages

Since you wrote a custom template for your content type. I think the problem would be rendering fields without any specific language

For Example:

In your Template to print a field:

$field_language = field_language('node', $node, 'body');

<?php print($node->body[$field_language][0]['value']); ?>

Since drupal 7 uses Entity translation . You need to select language for specific fields instead of node.


Can I use drupal_get_form and drupal_render within a custom Drupal 7 input filter?

I believe you can do this, but not by default. You'll need to disable caching. This is because the filtered data is cached, so your form will only work the first time. To disable caching, you need to set cache to FALSE in your hook_filter_info() definition.

If it's timing out, then it may be a problem in your form definition itself - does the for work in non-filter context (ie embedded directly into a page)?