How to get bundle machine name when viewing the creation form? From the creation form (any bundle), I need to get the content type label/name to use it in a link (in a block, for example) and pre-filter the View opened by this link.

Example :

The user wants to add a new Article and opens the Article creation form.

In a special block (let's say in Highlighted region), a link is displayed : "Clone existing".

This link leads to a View listing the existing Articles with a clone button for each.

This View can be filtered by content type.

So the link would be something like :

<a href"/existing-nodes?type=[node:content-type]">Clone existing</a>

How to get the [node:content-type] (just here to clarify, good old token) from the form?

Any tip would be nice.

Writing your own question is always useful.

I may have a solution, even if you may have something different, so please share.

I have built a Views block with a custom text (my link) as unique field (only show one result, you do not need to repeat the link, of course).

I have added a contextual filter based on content type with a default value provided by url, raw value, third component (node/add/mybundle_name), with case transform in lower case.

My link looks like :

Clone existing

And it works.


How to pass Javascript variable with form on submit? I want to pass a variable created with Javascript to $form_state so that I can use this variable in the form_submit function.

In an ajaxified form I can use:

Drupal.ajax[ajax_el].options.data._my_vars = JSON.stringify(js_object);

But how can I accomplish it in a non ajax form? Is there another possibility than using a hidden field? It might be possible to pass it to a field with #access => FALSE?

I would welcome every advice. Many thanks!

Daniel

Create a field for that variable, like this:

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

Whenever you are changing variable, update field's value.

Do not use

'#access' => FALSE

The Form API Reference clarifies it:

  when FALSE, the element is not rendered and the user submitted value is not taken into consideration.


If points equal value: reset to zero I use the User Points module. I've set a rule that add 10 points per content viewed. This was easy. THEN I want to check if user points is greater than 100 and, if it is, send an email to admin, AND set points to that user back to zero.

Download the Rules module and import the following rule:

{ "rules_reset_points" : {
    "LABEL" : "Reset points",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "Points" ],
    "REQUIRES" : [ "php", "rules", "userpoints_rules" ],
    "ON" : { "userpoints_event_points_awarded_after" : [] },
    "IF" : [
      { "php_eval" : { "code" : "global $user;\r\n$num_pts = userpoints_get_current_points($user-\u003Euid, \u0027all\u0027);\r\nif ($num_pts \u003E 100) {return TRUE;}" } }
    ],
    "DO" : [
      { "userpoints_rules_get_current_points" : {
          "USING" : { "user" : [ "userpoints-transaction:user" ], "tid" : "all" },
          "PROVIDE" : { "loaded_points" : { "loaded_points" : "Number of points in the specified category." } }
        }
      },
      { "data_calc" : {
          "USING" : { "input_1" : [ "loaded-points" ], "op" : "*", "input_2" : "-1" },
          "PROVIDE" : { "result" : { "result" : "Calculation result" } }
        }
      },
      { "userpoints_action_grant_points" : {
          "user" : [ "userpoints-transaction:user" ],
          "points" : [ "result" ],
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Prevent more than 100 points.",
          "operation" : "Add",
          "display" : 0,
          "moderate" : "approved"
        }
      }
    ]
  }
}

Adapt the actions to your needs, add another action "Send mail" after installing the Mime mail module (this article may help you in doing that) and you're done!


field_info_field API to get human readable name We want get human readable name from field info API.
For e.g. in below API call
field_info_field('field_image')

From UI for Drupal to add Article as below:

Can we get this human readable names i.e. Title, Alternate Text etc from API.

You can't, no - the labels are set statically in code (in image.field.inc), they don't come from the API:

// Add the additional alt and title fields.
$element['alt'] = array(
  '#title' => t('Alternate text'),
  '#type' => 'textfield',
  '#default_value' => isset($item['alt']) ? $item['alt'] : '',
  '#description' => t('This text will be used by screen readers, search engines, or when the image cannot be loaded.'),
  // @see http://www.gawds.org/show.php?contentid=28
  '#maxlength' => 512,
  '#weight' => -2,
  '#access' => (bool) $item['fid'] && $settings['alt_field'],
);
$element['title'] = array(
  '#type' => 'textfield',
  '#title' => t('Title'),
  '#default_value' => isset($item['title']) ? $item['title'] : '',
  '#description' => t('The title is used as a tool tip when the user hovers the mouse over the image.'),
  '#maxlength' => 1024,
  '#weight' => -1,
  '#access' => (bool) $item['fid'] && $settings['title_field'],
);


Facebook images timeline block Is there a module and/or jQuery solution how to show multiple images in a block like the Facebook gallery on people's timeline? The images are always well aligned regardless of their size and landscape/portrait position.

I'd like to use a similar approach for my blog articles - Upload like 3 or 4 images and some text. I included a screenshot of a Facebook post to give you an example of what I mean.

You can do this on a lot different ways regardless where you are using this, but it is mostly Front End question.

There is a Grid Field Formatter module that can help you with this, but it is not the best solution.

  Grid Field Formatter module provides a simple way to overridde the
  display of multi-value fields to show as a grid/table with a certain
  number of columns.


Node Create/Edit Form - Multistep with dynamic fields Our site has different type of articles. Based on the type selected, the fields displayed to the user are varied. The ask is to create a multi-step form and include type field on step 1. Based on the type, subsequent steps and fields included in those steps need to vary.

An important ask is that they need the ability to change the type of the article after it has been created. So on day 1 they might create an article with type "single page" but later change it to "multi page" (Multi-page article has all fields in single page plus additional fields).

I looked at Multistep, msnf, webform and webform_conditional modules etc, but they didn't seem to provide the functionality I need. Is creating this using Form API the best approach? Any suggestion?

UPDATE1

Another important requirement: An article could have multiple (0 or many) sections and each section could have multiple subsections. What is the best way to model the content type? Create content type Section and Subsection and then use node references (article will have a nod reference to section; section will have a node reference to subsection)? Using node references, can one to many relationship be implemented?

There are three module(may be two in your case), which can together to achieve what you want in D7. I have done this & client use it on daily basis..

Field Group

Multi Step

Then I have used Conditional Field module to have fields dependent on one another & it works great.

If you find any error in setup, please try the issue queue for patch.


Drupal 7 Link CCK text field to Node ID I am creating a view and the Filter Criteria cck text field needs to equal the Node Id. Any ideas on how to accomplish this?

Thanks

Include cck text field and node id in your view's field list and then you can make your text field as link to node id.

Also for the filtration you can use contextual filters if required one is not available you can use relations.


What is the purpose of the "Views: views_view" component? Using the Features module, I notice there is a "Views: views_view" component, when creating a feature, but I don't see any setting for that component.

I thought it would be list the views enabled in the site, but that doesn't happen, even if I have two views enabled.

What is the purpose of that component? Why isn't showing any settings?

I have tried with both the latest release candidate, and the lastest development snapshot, but the result doesn't change.

What is the purpose of [the "Views: views_view"] component?

As you suspected, to allow views to be exported into a features module.

  Why isn't showing any settings?

I do not know. One possible explanation is, that all the enabled views are provided by other modules via an implementation of hook_views_default_views(). The Features module itself exports views by writing an implementation of hook_views_default_views(), so the Views module cannot distinguish between the two versions of the view. That's why the Features module does not allow views to be exported, that are provided by other modules.


OO way of adding base field definitions Is there any object oriented Drupal way to add a base field definition to an existing entity?
Of course I am familiar with hook_entity_base_field_info(), but I am trying to keep my .module file size to a minimum and I was wondering if there is a way to achieve that with a different approach.
I thought of decorating or extending the entity, but after some research, I stumbled upon these issues that suggest those two options aren't yet possible or elegant, as far as I understand.

Allow entities to be subclassed using "bundle classes"
Create a generic way to decorate Entity classes

Am I wrong in that?
Is there anyone that has had the same case and found a different approach?
Edit:
TL;DR answer is that trying to replace this specific hook, will cause more confusion, rather than improve code clarity.

Without using any hook, it's not possible, since to change the class used for an entity, it's necessary to implement hook_entity_type_alter(), which is problematic to implement when more modules need to alter the entity definition, for example changing the same entity handler, or the entity class, for the same entity type.
Imagine two different modules that try to add two different fields to the User entity by replacing the entity class used for it. For example, the first module could use the following code.
/**
 * Implements hook_entity_type_alter().
 */
function login_id_entity_type_alter(array &$entity_types) {
  $entity_types['user']->setClass(LoginIdUser::class);
}

namespace Drupal\login_id\Entity;

use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\user\Entity\User;

class LoginIdUser extends User {

  /**
   * {@inheritdoc}
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    /** @var \Drupal\Core\Field\BaseFieldDefinition[] $fields */
    $fields = parent::baseFieldDefinitions();

    $fields['login_id'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Login ID'))
      ->setDescription(t('The ID used for the login credentials.'))
      ->setRequired(TRUE)
      ->setConstraints([
        'LoginId' => [],
        'LoginIdUnique' => [],
    ]);

    $fields['name']->getItemDefinition()
      ->setClass('\\Drupal\\login_id\\LoginIdItem');

    return $fields;
  }

}

The second module could use the following code.
/**
 * Implements hook_entity_type_alter().
 */
function admin_email_entity_type_alter(array &$entity_types) {
  $entity_types['user']->setClass(AdminEmailUser::class);
}

namespace Drupal\admin_email\Entity;

use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\user\Entity\User;

class AdminEmailUser extends User {

  /**
   * {@inheritdoc}
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    /** @var \Drupal\Core\Field\BaseFieldDefinition[] $fields */
    $fields = parent::baseFieldDefinitions();

    $fields['admin_mail'] = BaseFieldDefinition::create('email')
      ->setLabel(t('Admin email'))
      ->setDescription(t('The email used from administrator users to contact the user.'))
      ->setDefaultValue('')
      ->addConstraint('UserMailUnique')
      ->addConstraint('UserMailRequired')
      ->addConstraint('ProtectedUserField');

    return $fields;
  }

}

With two modules implementing that code, only a field would be added to the entity. To get both the entity fields, LoginIdUser should extend AdminEmailUser, which would mean that a module should have the other one as dependency.
This assumes that admin_email_entity_type_alter() is executed before login_id_entity_type_alter(). This is what normally happens when the hook execution order isn't altered by a hook_module_implements_alter() implementation, or when the weight associated to module isn't altered by a call to module_set_weight(). In the case login_id_entity_type_alter() is invoked before admin_email_entity_type_alter(), for example because a module implements hook_module_implements_alter() and changes the order of those hook implementations, AdminEmailUser should extend LoginIdUser.
Implementing hook_entity_base_field_info() allows to modules to add different fields without interfering with each other.
As side note, hooks can be placed in a file different from a .module file, which is automatically loaded from Drupal. Which files are loaded from Drupal when looking for hooks is influenced by hook_hook_info(). With the implementations of that hook done from Drupal core modules, the files Drupal core looks for are the following.

<module_name>.tokens.inc
<module_name>.views.inc

If you are interested in reducing the size of the .module file, implementing hook_hook_info() to tell Drupal where your module hooks are could be a way to achieve it.


How to display devel dpm messages on a panels generated page? I am testing a custom module for a site using Panels Everywhere & Panels. I need to put the results of a Devel module dpm() message into a pane so that I can see it on page displays. Does anyone know what content type it might be? I assumed it would be System Help, but no luck.

Put the code inside panels-pane.tpl.php file which is responsible for printing panel pane.
You can find this on Panels directory but you should better copy this into your theme folder and do there any modifications.


How to filter content in Views based on multiple term custom fields? I'm trying to find a way to filter Views through contextual filters based on custom taxonomy term fields. Here is an example:

Content type: Article
Taxonomy vocabulary: Tags
Tags custom field: UniqueString

When I create an article, I assign tags to it. To every tag (taxonomy term) I assign an unique string. Example:

Article title: John Smith's best songs
Tags: John | Guitar
UniqueString for tag John: uid1
UniqueString for tag Guitar: uid2

Now I want to display articles that are tagged with both John and Guitar. This works:

Contextual filters:

Content: Has taxonomy term ID
Content: Has taxonomy term ID

View page path: views/taggedby/%/%

Path views/taggedby/john/guitar will display:

John Smith's best songs

However, I want to filter based on UniqueString value and not on tag names:

Relationships:

Content: Taxonomy terms on node

Contextual filters:

(term) Taxonomy term: UniqueString
(term) Taxonomy term: UniqueString

View page path: views/taggedby2/%/%

Path views/taggedby2/john/guitar will display an empty view. What's confusing is that everything works when there is only one filter and the path is views/taggedby2/%, so there has to be a way to make it work with multiple filters as well. E. g. if I change View page path to views/taggedby2/% and use guitar as an argument, it will display:

John Smith's best songs

How to make it work with two (or more) arguments?

I have finally found a solution - it's necessary to add another relationship for the same field :

Content: Taxonomy terms on node, Identifier: term
Content: Taxonomy terms on node, Identifier: term2

The second contextual filter should use the second relationship (term2) and then everything works as expected.


Why do certain fields not behave like fields? Why do certain fields not behave like fields? For example 'Product title' and 'Product price' fields from Drupal Commerce:

You can tell that these two fields are composed very differently. I have noticed that most fields have the same composition as 'Product price' above; whereas 'Product title' doesn't even look like a field.

Matter of fact, the question could be rephrased as: why isn't 'Product title' a field, what is it? And how can I make it behave more like a field? Specifically, how to attach RDF mappings to 'Product title' using the RDF module, like you can with regular fields?

Product title is an entity property instead of a field. See blog post by Wolfgang Ziegler for an explanation.

You should be able to add RDF definitions by using hook_rdf_mapping(). I looked into the Commerce module and it didn't use the hook. You might want to file an issue on the Commerce project page.

Luckily you can define the RDF mappings by yourself. Below is an example code which might work.

function your_module_rdf_mapping() {
  return array(
    array(
      'type' => 'commerce_product',
      'bundle' => RDF_DEFAULT_BUNDLE, // might be something else
      'mapping' => array(
        'rdftype' => array('sioc:Item', 'foaf:Document'),
        'title' => array(
          'predicates' => array('dc:title'),
        ),
      ),
    ),
  );
}

If you want to expose entity properties to the UI, you can use hook_field_extra_fields(). Node module is using that to expose the title property to the UI. Below is an example code of that.

/**
 * Implements hook_field_extra_fields().
 */
function node_field_extra_fields() {
  $extra = array();

  foreach (node_type_get_types() as $type) {
    if ($type->has_title) {
      $extra['node'][$type->type] = array(
        'form' => array(
          'title' => array(
            'label' => $type->title_label,
            'description' => t('Node module element'),
            'weight' => -5,
          ),
        ),
      );
    }
  }

  return $extra;
}


How to move an article to another place. I just add 10 articles in my drupalwebsite, but now I want to change the place of my articles.

The article that I have added first is now at the bottom. This should be at the top. Everything is in reverse order. How can I change this?

Thx for helping.

Promoted to home page content is ordered by created data.. So, Change authored date accordingly..
Make them sticky by editing content and checking sticky at top of lists checkbox to place them on top of list in home page..
If you are using views module you can set sort criteria..


Display alias instead of node I am trying to create a link in page.html.twig that points to an alias. The code {{ url('node/1') }} shows an unexpected error, whereas {{ 'node/1' }} works fine but goes to url website/node/1.

In D7, one can use <?php echo url('node/1'); ?> and be directed to the page with proper alias.

What code can be used in D8 to display correct alias url?

You can use getAliasByPath function to get the url alias for a path.

Put the below code in THEME_NAME.theme file.

function THEME_NAME_preprocess_page(&$variables) {
  $variables['url_alias'] = \Drupal::service('path.alias_manager')->getAliasByPath('/node/1');
}

Finally print the url_alias in your page.html.twig file.

{{ url_alias }}


Change Views Ajax speed I've got a view with a few exposed filters. Is there a way to change the submit speed of the ajax request? So that rather than submitting the request after every key press, it waits until no keypress has been registered for say 500ms before submitting the request? I'm having problems, especially on mobile, where you might type "ar" in the exposed filter, but end up seeing the results for "a", with the filter set back to "a".

function do_search(e) {
  clearTimeout(search_timer);
  search_timer = setTimeout(function() {
    var v = $("#YOUR_INPUT_VAR_ID").val();
    p(v);
    CALL THE AJAX HERE
  }, 500);
}


Save button missing from content type edit form Here is what the bottom of my "leaflet" content type edit form (i.e. admin > structure > content types > leaflet > edit) looks like:

Here is what the bottom of my "testimony" content type edit form looks like:

Note that there are no save/delete buttons! Another of my content types has also now picked up this bug. This just happened. I have no idea why. I can't save changes! I tried flushing all caches and it didn't help. I'm an administrator and I have permissions for everything.

Why would this have happened and what can I do? Drupal 7.19.

The problem was the i18n synchronize translations module. Disabling it fixed the problem. Of I have to immediately re-enable it afterwards since I actually use this module. So I filed an issue: http://drupal.org/node/2004260. Thanks to Ayesh K who gave me the idea in his comment on my question. Since it's not an answer I can't mark it correct, so I'm just answering here and will mark this correct.


403 - node creation via api I have an issue with creating a node via the API. I have the correct permissions setup but it seems like a glitch somewhere in the permissions. An admin can create a content but no other role can. [content type]: Can create new content permission is checked.

Error; access denied - /node?_format=hal_json

Config:

Client:

return api({
    method: 'post',
    url: 'node?_format=hal_json',
    data: JSON.stringify(_node),
    headers: {
        'Content-Type': 'application/hal+json',
        'X-CSRF-Token': _xscrf_token,
    },
});

Make sure you check the correct permissions for the roles you want in the "RESTful Web Services" section on the /admin/people/permissions page.


get error field is required when #access is false with field permission  in image field With fieldpermission module I set some permission on some fields(fields are in profile type (I used profile2 module)) ,some of them are required , showing of field is ok ,(they are not showend and #access property of them is false ). but when I save node  get field is required error to me.
any idea?

update: after some debugging find out this problem not issued from profile2 module, problem is a bug(maybe) with image cck field and field permission. when you have image cck field and restrict it with field permission even it not showed(by #access=false ) but in submit (if it reqired) , return  the image field name is required.
any idea?

This fieldpermission bug with image and file cck field.

You can get all element in form_alter and if #access set false remove #require of it

    if ($profile_type == 'profile_main') {
    foreach($form[$profile_type] as $index=>$value) {
          if (preg_match('/^field_/', $index)){
                if ($form[$profile_type][$index]['#access'] == FALSE)
                  $form[$profile_type][$index]['und'][0]['#required']=FALSE;
          }
        }
    }


Changing a field title in a panel I've got a field in a panel. I want the field title to be replaced by something that is dependent on another node. In a view this is really straightforward:

View -> Configure Field -> Rewrite Results -> Rewrite the output of this field: ([field_A] is the name of this thing)

The Panel, however, doesn't recognize the [bracket] functionality in Node -> Settings -> Override title.

Apologies if this is obvious, but I can't find the solution anywhere. Any help would be hugely appreciated.

You can use keywords from contexts when you override a title of a pane in Panels. Go to Contexts in the Page Manager UI. The summary of contexts displays the available keywords.

In your situation you may want to add a new context, the node that you want your pane title to be pre-populated from. You can select the node ID, and the same node will always be loaded.

If it's not always the same node that you want to use, but e.g. a reference field in your already loaded node defines it, you can use a relationship to create the appropriate node context.


Applying Updates to Multiple Drupal Sites I have over 100 drupal 7 websites on my single server. Applying updates to each site individually is a lengthy task.

Is there any simple way through which we can update all the websites at once, or can we use a single module folder for multiple Drupal websites?

Please remember that testing is a very important part of every site upgrade.  It would not be difficult to write a script to copy code & db from live to stage for all sites, and then run drush -y pm-update on each site in turn; however, you should include a manual testing phase after the pm-update, and then push each tested site back to the live site as they are found to be working.

For the deploy step, you will want to copy the code from stage to live, and then run updatedb on the live site.  The live site should be offline during this operation.  See also drush_deploy for scripting stage-to-live deployment.


What Continuous Integration System is most geared? I am looking for a Continuous Integration System to use with Drupal 7. Preferably it should be widely used and easy to support.

Do you have any thought?

Among open-source PHP projects, the two most widely-used CI implementations are easily Jenkins (jenkins-ci.org) and Travis (travis-ci.org). Both have significant communities, and you can find examples of using them with Drupal (eg wiki.jenkins-ci.org/display/JENKINS/Drupal+Development and www.vmdoh.com/blog/how-we-test-drupal-7-modules-travis-ci).

Between the two:

Jenkins' positioning is more like Drupal's -- it's an open-source product with a lot of add-ons/options/features, but you have to think a lot about deployment and picking options. It's useful for testing and many other things (e.g. deployment, nightly tarballs, cron-jobs).
Travis is a proprietary SaaS offered on a freemium basis -- free for public/FOSS code; paid otherwise. It's generally easier to setup because Travis provides servers and bundles more features in the default. It has a more focused/limited range of use-cases.

For some specific features that differentiate them (at time of writing):

Jenkins provides reports -- e.g. when a test fails, it lists out specific failures on a nice web-page. You can see an example of a full report at https://test.civicrm.org/job/CiviCRM-Core-Matrix/CIVIVER=4.5,label=test-debian6-1/lastCompletedBuild/testReport/ . In Travis, this is a long-standing feature-request: https://github.com/travis-ci/travis-ci/issues/239
Travis makes it relatively easy to test with different combinations of key dependencies (e.g. PHP 5.2+5.3+5.4+5.5 and MySQL 5.1+5.5+5.6). In Jenkins, this is possible but requires much more sysadmin skill.

As a rule of thumb:

If you have a large project (with lots of code, lots of tests, peculiar integrations, some budget), then Jenkins' deeper feature-set and configurability make it the better choice.
If you have a small project published on Github (e.g. an individual Drupal module or PHP library with no budget), then Travis's simplicity and bundling make it the better choice.
If your project is in between, then there is no clear rule of thumb; it's a judgment call.

Aside: You may find buildkit.civicrm.org interesting. The summaries and explanations are written for an audience that works with Drupal/Joomla/WordPress, although a lot of technical details would need tuning for a Drupal-only audience (e.g. replace "civibuild" with "drush"; replace "Build Types" with "makefiles").

(NOTE: I left several links as plain-text because stackexchange limits the #links from new users.)


One of two field is required in drupal 7 view? I have one view in which i want to upload picture(image) or embed video(text). I want to add condition either picture or video field required. and also user can not fill both value user can fill only one value.

I also tried to use https://drupal.org/project/conditional_fields but it can not work for me.

I reffered https://drupal.org/node/355264 . I hope this will help me but I am new in Drupal so how can I used this.

Any help will be appreciate.

Thanks in advance.

An approach could be adding a previous radio button field where the user must select which field is going to fill, and the show this field with conditional field. (Both fields should be required)


How to play the video using media module? I am using drupal 7 and i am in need of upload a video from our local system as well as from the video. I found the media module and media_youtube module. After installing the module, the url from the youtube is working, but for local machine system video upload in getting downloadable option in the front end and not played.

How to play the video without downloadable option in the same page. Please suggest me some ideas.

Thanks.

You can see see here the list of player modules that extend media module.
There is also basic version information about each module.

Start with jPlayer and see if it fits your needs.


Expose a view's filters both in a block, and in the actual view I made a View, and I exposed the filters in a block; then, in the block's administrative screen, I set this block not to appear in the view that belong. In the actual view I don't want to show this block. Instead, I want the filters to appear in the content as they normally would if I didn't expose them in a block.

If that makes any difference, I am using Drupal 7.

The accepted answer did not work with Drupal 7 for me.
I followed http://www.drup-all.com/blog/exposed-filters-form-your-custom-block-drupal-7 with success. Code below:

/** implements hook_block_info() **/
function test_block_info(){
  $blocks = array();
  $blocks['custom_exposed_filter_form'] = array(
    'info' => t('Exposed filter form'),
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

/** implements hook_block_view() **/
function test_block_view($delta = ''){
  $block = array();
  switch($delta){
    case 'custom_exposed_filter_form':
      $block['subject'] = t('Exposed filter form');
      $block['content'] = _test_get_exposed_filter_form();
    break;
  }
  return $block;
}

/** Function to get the Exposed filter form **/
function _test_get_exposed_filter_form(){
  // Get a view from the database or from default views . "test" is the view name.
  $view = views_get_view('test');
  // Set the display as current.
  $view->set_display('page');
  // Acquire and attach all of the handlers to the view.
  $view->init_handlers();
  $exposed_form = $view->display_handler->get_plugin('exposed_form');
  return $exposed_form->render_exposed_form();
}


Unity launcher / OSX Spotlight like functionality for administration? I'm fairly certain I've seen a module that provides a quick way of typing in, for example, the title, of an administrative page, and it would wisk you away to that page.

Much like the way Unity's launcher, OSX's spotlight or KDE's runner behaves, just inside your site instead of the desktop.

However, I can't seem to recall what it was called and google only came up with this abandoned sandbox.

While coffee is probably the module you are looking for, i think switching on search in admin_menu is way more productive - no roundtrip for the searches and you stay focused on the admin stuff. I bet you are using the admin_menu anyway ? Just visit admin/config/administration/admin_menu and hit save - the search field should appear on the right hand side of the admin menu :)


Uploading files to two separate locations I'm uploading a clients website early next week and they've just informed me that they use load balancing software to distribute over two servers.

Normally this wouldn't be an issue because content is stored in the database and as long as both files areas can access it then it should be fine.

However, the issue comes in when uploading files. I've been informed that files should be uploaded to both servers.

I wouldn't even know where to begin to make this modification. Can anybody shed some light on it for me?

Is there a global method that's invoked when files are uploaded?

Note: This needs to work with the file field on several content types and even when files are added through modules/cck

I very much suggest a solution which actually shares the files/ directory.
My primary recommendation here is some dedicated hardware. To avoid marketing for anyone in particular, I just recommen you read, on Wikipedia, SAN and FAN.

If hardware is out of the question, then we have good experience with NFS for direct sharing. Samba on the other hand has proven to be to slow.

There is also a "native" Drupal solution called Storage API which can do a lot of neat things with your files, but I don't think your particular needs can be solved out of the box, but would require some extra coding.

I would only use some type of syncing as a last resort, but here's a really basic bash-script you could cron run. The major part of this script is a safeguard so it will refuse to start if it's already running.

#!/bin/bash
LOCK_FILE=~/.lockfile

if [ -f "${LOCK_FILE}" ]; then
  PID=$(head -n1 "${LOCK_FILE}")

  TEST_RUNNING=$(ps -p ${PID} | grep ${PID})

  if [ -z "${TEST_RUNNING}" ]; then
    echo $$ > "${LOCK_FILE}"
  else
    exit 0
  fi
else
  echo $$ > "${LOCK_FILE}"
fi

rsync -az local_files/ username@host:/remote/path/to/files
rm -f "${LOCK_FILE}"

exit 0


Unable to send email using "SMTP Authentication Support" module I was working on a project where i  used "SMTP Authentication Support" module to send emails. The authentications i provided were my personal gmail account details, It was working fine. Now when i am entering the site admins account details its displaying "Unable to send e-mail. Contact the site administrator if the problem persists." error. It also says that "SMTP Error: Could not authenticate." Can anyone let me where i am going wrong.

I would suggest you to use the module Mandrill

First you can go to mandrillapp.com and create an account.

After account creation go to Api and generate an Api key.

Then after installing the module on drupal instance. Go to Configuration->Mandrill->Add the Api key and your site is ready to send mails.

Hope this helps.


Call to undefined function node_mass_update() In hook_form_alter(), I am using the following code.

if ($form_id == 'album_node_form') {
  $form['actions']['unpublish'] = array(
    '#type' => 'submit',
    '#value' => t('Unpublish'),
    '#submit' => array('az_alter_unpublish')
  );

  // …
}

In az_alter_unpublish(), I am using the following code.

function az_alter_unpublish($form, $form_state) {
  $nodes = array();
  // $nodes is an array of node IDs for the nodes I want to unpublish.
  node_mass_update($nodes, array(array('status' => 0)));

  // …
}

This returns a fatal error.

I read the function documentation, but I can't find out the problem.

The solution for this problem is to include the node.admin.inc file.

 module_load_include('inc', 'node', 'node.admin');
 node_mass_update($nodes,array(array('status' => 0)));


How to get view by tag sorting the same as main view sort criteria I am new to Drupal 7. I have a view set up at /people with the sort criteria set to a field called surname. This is working fine, listing people out alphabetically by surname.

I have tags associated with people and /people/tag/x does list out just the people with tag x (I can't remember whether I had to do anything special to get that working).

However, when viewing people/tag/x, the entries are no longer sorted by surname. I'm not sure what order they are in.

How can I get the main view sort criteria (surname here) to persist when viewing a certain tag at people/tag/x?

Here is an export of the view: http://pastebin.com/8eBSkvn7

Screenshots of view config below, after I tried to add the contextual filters suggested by awm. I have also tried changing the first tag filter to 'Content: has taxonomy term ID'. I had no contextual filters originally.

Many thanks for your time.

You can add another argument/contextual filter (surename). And in the contextual filter settings you could specify the sort criteria when the filter is not in URL. You can choose the sort criteria numeric or alphabetical as in the screen shots

Then

Edit: If you have a content type called directory, and the content type has taxonomy term reference and a field called surname you can replicate the config in the screen shot below and it should work. Note contextual filter and sort criteria settings:
 1. Page View config note:

 2. Contextual filter taxonomy tag settings
 3. How the it will display the summary:
 4. How it will display the content, note how it is sorted by surname


Cron error message. table or view not found: 1146 In watchdog I am seeing an error when cron is run.

  Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'tdtvnksvps.field_deleted_data_38d3088921' doesn't exist: SELECT DISTINCT t.entity_id AS entity_id FROM {field_deleted_data_38d3088921} t WHERE bundle = :db_condition_placeholder_0 LIMIT 50 OFFSET 0; Array ( [:db_condition_placeholder_0] => ) in Drupal\Core\Entity\Sql\SqlContentEntityStorage->readFieldItemsToPurge() (line 1686 of /home/300465.cloudwaysapps.com/tdtvnksvps/public_html/web/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).

Pretty sure I mistakenly deleted a table from the database a while back and this is the result.

The issue appears to be similar to Error when deleting some node, but I think the advice given to find a record of the deleted field was written for D7.

Is this the same problem and how resolve it for D8?

I Had this issue sometimes ago, I deleted a field table from DB manually and this error started to showing up, A way to get rid of it is to create a table for a field, so you can use a mysql code like that :

CREATE TABLE `field_deleted_data_38d3088921` (
    `bundle` varchar(128) CHARACTER SET ascii NOT NULL DEFAULT '' COMMENT 'test',
    `deleted` tinyint(4) NOT NULL DEFAULT '0' COMMENT 'A boolean indicating whether this data item has been deleted',
    `entity_id` int(10) unsigned NOT NULL COMMENT 'The entity id this data is attached to',
    `revision_id` int(10) unsigned NOT NULL COMMENT 'The entity revision id this data is attached to',
    `langcode` varchar(32) CHARACTER SET ascii NOT NULL DEFAULT '' COMMENT 'The language code for this data item.',
    `delta` int(10) unsigned NOT NULL COMMENT 'The sequence number for this data item, used for multi-value fields',
    `test` varchar(2048) DEFAULT NULL COMMENT 'test',
    PRIMARY KEY(`entity_id`,`deleted`,`delta`,`langcode`),
    KEY `bundle` (`bundle`),
    KEY `revision_id` (`revision_id`)
)


Programmatically hide comment and view tabs Can you please help me to hide the tabs from the Find/Add/Edit content page?

Is there a way to programmatically hide them?

A more generic solution could be Tab Tamer.

  Tab Tamer is an administration utility that provides easy re-ordering, hiding, and deactivation of tabs and subtabs. You can also rename tab labels.


Possible to alter user account status options on user_register_form? I'm looking to alter user_registration behavior to allow certain users to reopen their closed or blocked accounts but not users who have been explicitly banned. As such, I'm looking to modify the current form element for ['account']['status'] from just allowing 'Blocked' and 'Active' to something like this

  $form['account']['status']['#options'] = array(t('Blocked'),
  t('Active'), t('Banned/Dead to Me'));

This is an easy form_alter hook to execute and Drupal will add the new value ('2') in the users table but it doesn't know what to do with it in other functions, ex. on the admin/people page, it doesn't recognize the new value:

  Notice: Undefined index: 2 in user_admin_account() (line 226 of
  /public/modules/user/user.admin.inc).

Is there another way to customize the user status options or is this a protected core value? Are there already modules that add new user status options that I could look at as a model?

Finished working through the implications of this and have confirmed it is not possible to alter the user_status fields through Drupal without causing other complications through other modules -- the 0/1 logic for users is too ingrained in core to overcome.

I've addressed the requirement through a number of other Drupal hooks that work alongside the user module, will be releasing user_reopen module shortly to community.


Site name with html tag How can I have the site name with a span html tag without hard-coding it in a template? [ex. Good4You]

Its not at all difficult. I tried it in Drupal 7.22

Goto Configuration => Site Information => Site Name =>

My Site This is my new website

Add whatever tags you like to have. But remember site title itself is already inside  tag, which means you have some restriction (Span tag is not container).

This is what it looks when I inspect it using firebug in mozilla.

In your case, its Good4You. Just by using css you can do the magic.


Override title with field label instead of key inside a views contextual filter I have a soccer team Drupal 7 site where I keep track of the players using a user role.  I have a view of the players which grids their profile pics and I'm very happy with it.  It's URL is /players

Now I want to divide the players into separate groups.  My first stab at this was to add a user_program field onto the User content type.  I added this field of type List(text), and gave it keys/values like:
youth_competitive_program|Youth Competitive Program
primary_competitive_programe|Primary Competitive Program

I then added a Contextual Filter so that I have /players/youth_competitive_program and such.  Works very well.  Except:  when I tell those views to override the title using %1 I get the key instead of the value.  What I really want is my human readable value up there, not the key.

edit your Contextual Filter check Specify validation criteria in Validator check PHP code and enter following:

if ($argument == 'youth_competitive_program') {
  $handler->options['title'] = 'Youth Competitive Program';
  return true;
} else if ($argument == 'primary_competitive_programe') {
  $handler->options['title'] = 'Primary Competitive Program';
  return true;
}
return false;

there is another similar way:

if (!empty($argument)) {
  $handler->options['title'] = t($argument);
  return true;
}

return false;

and translate them, so if you add more option to your user_program fields, this code will work better.

but there is another option yet:

$field = field_info_field('field_user_program');
if (array_key_exists($argument, $field['settings']['allowed_values'])) {
  $handler->options['title'] = $field['settings']['allowed_values'][$argument];
  return true;
}
return false;

I will select the last way


Use views to display not voted polls I'm using polls (from core) to make some enquetes.
Is there a way to use views to display only the polls that a user has not voted yet?

I didn't find anything on google. The only solutions where for Drupal 6. And I'm using drupal 7.

Thanks in advance =)

First I tried to use the hook_views_pre_execute.

<?php
function hook_views_pre_execute(&$view) {
    $uid = $GLOBALS['user']->uid;

    //gets one the poll and return it
        $query = db_select('node', 'n');
        $query->fields('n');

        $subquery = db_select('poll_vote', '');
        $subquery->fields('poll_vote', array('nid'));
        $subquery->condition('poll_vote.uid', $uid);

        $query->condition('n.nid', $subquery, 'NOT IN');
        $query->condition('type', 'poll');
        $query->condition('status', 1);
        $query->range(0, 1);

    $view->build_info['query'] = $query;
    $view->build_info['count_query'] = $query;
}

But when I tried to use the pager, it had too many bugs. It felt like a hack. So in the end I used:

<?php
/**
 * Returns a page with one not voted poll
 * @return [array] [drupal page array]
 */
function one_poll_page(){

    $page[] = "";
    $uid = $GLOBALS['user']->uid;

    //gets one the poll and return it
        $query = db_select('node', 'n');
        $query->fields('n');

        $subquery = db_select('poll_vote', '');
        $subquery->fields('poll_vote', array('nid'));
        $subquery->condition('poll_vote.uid', $uid);

        $query->condition('n.nid', $subquery, 'NOT IN');
        $query->condition('type', 'poll');
        $query->condition('status', 1);
        $query->range(0, 1);

        $result = $query->execute();

    foreach ($result as $record) {
      //saves the rendered poll node to the array
      $node = node_load($record->nid);
      $view = node_view($node, 'full');
      $rendered = drupal_render($view);
      $page['#markup'] .= $rendered;
    }

    return $page;
}

Because I can then control exactly what the page does.


Limited Node References I am building a site for a client where each page has 3 other pages associated with it.
I know how to create node references but I would like to find a way to limit the user to creating just 3 node references per page.

So each page only allows the creation of 3 references and whrn all of them are created the "add reference" link is removed ( until perhaps one or more of the references is deleted ).

Can anyone suggest a potential solution?

Thanks

In node reference field settings page (content type -> manage fields -> name of field) in "global settings area" set "number of values" to 3.

Thats it.
Hope this helps.


Keeping $attributes but adding a rel (D7) I have the following piece of code:

l('

' . $image, $link_path, array('html' => TRUE, 'attributes' => $attributes))

Which creates a nice link, as it should be. Now I want to add a rel-attribute without getting rid off $attributes (because I need that one). I have Googled and tried a lot, but nothing seems to work. So if anyone can help me with just adding a rel-attribute without deleting the other attributes, I would be grateful!

Thanks

If I understand you right you just want to add the rel attribute to the $attributes array before you call l(). Something like this:

$attributes['rel'] = 'the_rel';
print l('

' . $image, $link_path, array('html' => TRUE, 'attributes' => $attributes));

That will add the an item to the $attributes array with a key of rel and a value of the_rel, and won't affect any of the other attributes already in the array.


Site won't display messages I'm desperate.
I have a site with 2 databases, staging and production, and in staging messages set with drupal_set_messages() appear, but in production they don't.
The codebase is the same. I tried switching database settings on the same codebase and the behavior will change depending on the database.
I have inherited the site so I'm not 100% familiar with its configuration.

My question is: is there anything on a database level that can block messages from showing? They appear in the admin area, but not in the rest of the website...

Configuration > Development > Logging and errors has some settings on whether to display drupal messages or not. You might check to make sure that it is properly configured for your use case.

Path to config page: /admin/config/development/logging


drupal_mail_system is returning empty object I have installed mime module for sending html mails. Im receiving Drupal security update on my site but not sending/receiving any mails through my code.

$settings = array(
  'id' => $my_module . '_' . $my_mail_token,
  'to' => $email_to,
  'subject' => $email_subject,
  'body' => $email_message,
  'headers' => array(
    'From' => $conf['FROM_email'],
    'Sender' => $FROM,
    'Return-Path' => $FROM,
    'Content-Type' => 'text/html; charset=UTF-8; format=flowed',
  ),
);

$system = drupal_mail_system($my_module, $my_mail_token);
if ($system->mail($settings)) {
  print 'success';
}
else {
  print 'failed';
}

I tried to print_r($system) which is supposed to return object of mail system interface but all I received was HTMLMailSystem Object ( ). What am I missing?

You forgot to call format method.

Try the following snippet:

$from = variable_get('system_mail', $my_email);
$message = array(
  'id' => $my_module . '_' . $my_mail_token,
  'to' => $my_email,
  'subject' => $message_subject,
  'body' => array($message_body),
  'headers' => array(
    'From' => $from,
    'Sender' => $from,
    'Return-Path' => $from,
  ),
);
$system = drupal_mail_system($my_module, $my_mail_token);

// The format function must be called before calling the mail function.
$message = $system->format($message);

if ($system->mail($message)) {
  drupal_set_message('SUCCESS');
}
else {
  drupal_set_message('FAILURE');
}


AJAXX AutoComplete joins and unions causing error I am a bit out of my depth here.

I have successfully implemented my own autocomplete field of an entityform, the following link was my roadmap Textfield that uses AutoComplete.

But I am trying to do something much more fancier. I need to search for a users name, and autocomplete it for the user. The issue I am having is that I must check multiple tables for the user to select from, tables like: field_data_field_first_name, field_data_field_othername, field_data_field_nickname, field_data_field_fullname.

Because some people's names have changed, or have a nickname.

So I have begun checking multiple tables and think I got a good start, but I keep getting the following error: "SQLSTATE[21000]: Cardinality violation: 1222 The used SELECT statements have a different number of columns"

I want to be able to incorporate this:

 SELECT fn.*, ln.* FROM field_data_field_first_name as fn
    left join field_data_field_last_name as ln ON fn.entity_id = ln.entity_id
    WHERE fn.field_first_name_value LIKE '%bun%'
UNION
SELECT fn.*, fo.* FROM field_data_field_first_name as fn
    left join field_data_field_other_name as fo ON fn.entity_id = fo.entity_id
    WHERE fn.field_first_name_value LIKE '%bun%'
UNION
SELECT ni.*, ln.* FROM field_data_field_nickname as ni
    left join field_data_field_last_name as ln on ni.entity_id = ln.entity_id
    WHERE ni.field_nickname_value LIKE '%bun%'
UNION
SELECT ni.*, fo.* FROM field_data_field_nickname as ni
    LEFT JOIN field_data_field_other_name as fo ON ni.entity_id = fo.entity_id
    WHERE ni.field_nickname_value LIKE '%bun%'

into Drupal 7 db_select. I have some of this query in my Drupal query (not all of it, for the moment) but I am getting the column discrepency error (1222), my column counts aren't matching. Can't I just grab every field, like I do in my MySQL string and call it a day? I thought fields('alias') would of solved this, since that is grabbing every column, but it doesn't seem to be doing the trick!
This is what I got now:

$secondQuery = db_select('field_data_field_first_name', 'f') ->fields('f')
      // check the first_name_value, but we want to do a leftJoin to show the left_name_value as well! like Larry, Adams, not just Larry
      ->condition('field_first_name_value', '%'. db_like($string) .'%', 'LIKE');
    $secondQuery->leftJoin('field_data_field_last_name', 'l', 'f.entity_id = l.entity_id');
    $secondQuery->fields('l');

  // Make the query
  $result = db_select('field_data_field_user_name', 'u')
      ->fields('u')
      ->condition('field_user_name_value', '%' . db_like($string) . '%', 'LIKE')
      ->union($secondQuery)
      ->execute();

So, I figured out how to convert MySQL to Drupal SQL, of a join and union sql transaction, I am not done - but this is the start and the rest is just copy / paste and massage.

$matches = array();
  $debug_stop = "";

  // Firstname and Lastname - Larry Adams
  $firstname_lastname_query = db_select('field_data_field_first_name', 'f')
     ->fields('f')
    ->condition('field_first_name_value', '%'. db_like($string) .'%', 'LIKE');
  $firstname_lastname_query->leftJoin('field_data_field_last_name', 'l', 'f.entity_id = l.entity_id');
  $firstname_lastname_query->fields('l');

  // Username checks - lAdams
  $username_query = db_select('field_data_field_user_name', 'u')
      ->fields('u')
      ->condition('field_user_name_value', '%' . db_like($string) . '%', 'LIKE');
  $username_query->leftJoin('field_data_field_last_name', 'l', 'u.entity_id = l.entity_id');
  $username_query->fields('l');

  // Unionize the query to previous query
  $firstname_lastname_query->union($username_query);

  // Nickname checks - lar-bear Adams
  $nickname_lastname_query = db_select('field_data_field_nickname', 'ni')
      ->fields('ni')
      ->condition('field_nickname_value', '%' . db_like($string) . '%', 'LIKE');
  $nickname_lastname_query->leftJoin('field_data_field_last_name', 'l', 'ni.entity_id = l.entity_id');
  $nickname_lastname_query->fields('l');

  // Unionize the query to previous query
  $firstname_lastname_query->union($nickname_lastname_query);

  // Execute the query
  $result = $firstname_lastname_query->execute();

  $debug_stop = "";
  // save the query to matches
  foreach ($result as $row) {
    // If we returned back a user_name accessible field
    if (isset($row->field_user_name_value)) {
      $matches[$row->field_user_name_value] = check_plain($row->field_user_name_value);
    }
    // If we returned back a first_name_value accessible field
    if (isset($row->field_first_name_value)) {
      // with a last name
      if ($row->field_last_name_value) {
       $first_last_name = $row->field_first_name_value ." ". $row->field_last_name_value;
       $matches[$first_last_name] = check_plain($first_last_name);
      }
    }

  }

  // Return the result to the form in json
  drupal_json_output($matches);


Can't save custom field data: form submit function doesn't fire I've added custom "markup" field to the commerce_product table, next I've implemented hook_form_FORM-ID_alter, but submit function doesn't executed.

If you add the custom field through hook_form_alter. You need to store the data manually in your custom table by using your custom submit handler..    Otherwise you could use the below code in your *.install file

function MYMODULE_enable() {
  // Check if our field is not already created.
  if (!field_info_field('field_myField')) {

    // Create the field base.
    $field = array(
      'field_name' => 'field_myField',
      'type' => 'text',
    );
    field_create_field($field);

    // Create the field instance on the bundle.
    $instance = array(
      'field_name' => 'field_myField',
      'entity_type' => 'user',
      'label' => 'My Field Name',
      'bundle' => 'user',
      // If you don't set the "required" property then the field wont be required by default.
      'required' => TRUE,
      'settings' => array(
        // Here you inform either or not you want this field showing up on the registration form.
        'user_register_form' => 1,
      ),
      'widget' => array(
        'type' => 'textfield',
      ),
    );
    field_create_instance($instance);
  }
}


Storing User preferences in Drupal I recently developed a module where I used the function hook_form_user_profile_form_alter(&$form, &$form_state) to capture user preferences and saved them using function hook_user_presave(&$edit, $account, $category) .
Then I accessed the data using $user->data['field']  in a module . That worked fine .

But now  I want to store the same preferences using another form (not the user profile form).
So is there any other hook to store them ?

I want to give a link to each user to the page(form other than the user profile ) where he can store his preferences .

Thanks in advance.

You don't need to use a hook you need to use the API function user_save(). Which is a very weird function because unlike all other save functions, it has a separate argument for the things that you want to change.

Something like this should work, in your submit callback:

<?php
// Make sure you are working with the fully loaded user object.
$account = user_load($GLOBALS['user']->uid);
$edit['data']['your_stuff'] = $whatever;
user_save($account, $edit);
?>

FYI: user_save() is no more in Drupal 8 and instead behaves like all other entity save functions/methods in 8.x, by calling $account->save() after changing $account. See the following change record for details: http://drupal.org/node/1554986


Can we get full count of results from a query that is extended by PagerDefault I have a query that is extended by PagerDefault.  I need to get the total count of results to show something like: "There are a total of 100 results, now showing 21-40".  I can't figure out where to get that number without building a separate query to run that doesn't use PagerDefault.

First place I looked was theme_pager(), which I'm already overriding in template.php.  The total result count is not passed there, only the current page (as $variables['element']).

I see that within includes/pager.inc in pager_default_initialize() only the current page number is sent to theme_pager, although the total items are passed to that function. (So close!)

Then I thought I could clone the query, but the query must be extended prior to adding conditions, so that wouldn't work.  I'll note that this isn't ideal either, because ideally, I would be able to get this total count without two db hits (as it would hit it for the count every time a user navigates the pagination).

So, does anyone know the best way to get the total count?

Thanks!

With the existing pager class I don't think you can get that data without running the count query again. The total count is queried directly and saved to a local var before being passed off to pager_default_initialize()...it's not saved anywhere.

One option would be to extend the default class and use that for your pager queries. This is un-tested but I think it'll do the trick

class MyPager extends PagerDefault {

  /**
   * Overrides PagerDefault::execute().
   */
  public function execute() {
    // Add convenience tag to mark that this is an extended query. We have to
    // do this in the constructor to ensure that it is set before preExecute()
    // gets called.
    if (!$this->preExecute($this)) {
      return NULL;
    }

    // A NULL limit is the "kill switch" for pager queries.
    if (empty($this->limit)) {
      return;
    }
    $this->ensureElement();

    // Get the total items from our new statically cached function.
    $total_items = $this->getTotalItemCount();

    $current_page = pager_default_initialize($total_items, $this->limit, $this->element);
    $this->range($current_page * $this->limit, $this->limit);

    // Now that we've added our pager-based range instructions, run the query normally.
    return $this->query->execute();
  }

  /**
   * Cache the results of PagerDefault::getCountQuery().
   */
  public function getTotalItemCount() {
    static $total_items = NULL;

    if ($total_items === NULL) {
      $total_items = $this->getCountQuery()->execute()->fetchField();
    }

    return $total_items;
  }

}

You could then construct a query like the following

$query = db_select('table', 't')
  ->fields('t')
  ->condition('foo', 'bar')
  ->extend('MyPager');

$current_items = $query->execute();
$total_items = $query->getTotalItemCount();

There might be an easier way, but I just can't see it.


Drupal Commerce SKU generator I am building a Drupal Commerce site and I had the weirdest request:

Upon creating a new product, the client want's to select the product's category from a select list or something similar. This should result in the first part of the product's SKU, say

"CAT007"

Then he want's to select another attribute for that specific product which produces the second part of the SKU, say

048

So the complete SKU of the product would be CAT007.048 thus resulting in a unique identifier. The reason for this is that he doesn't want to look within huge arrays in order to produce the correct SKU.

My problem is that I can't seem to find a decent solution with which I can give the client access and management over the arrays.

Can anyone come up with something?

EDIT something that came to mind was taxonomy terms that contain a field with their SKU prefix/suffix. The problem that arises from that is how can I pass the tid from the user's selection (javascript) to the php side in order to do a term_load() and get the field's value.

By using taxonomy_vocabulary_machine_name_load() and taxonomy_get_tree() I was able to extract the 2 taxonomies I needed for creating the prefix and suffix of the SKU.

I created tables of key, value pairs that contained the tids and the SKU codes.

By using json_encode() I was able to pass those tables into an inline js script I attached to commerce's product form using $form['#attached']['js'].

Now by having a JavaScript array mapping tids to SKU parts, it's easy using jQuery to fill in the SKU textfield accordingly. :)


Is there a module to show a quick message to a user or role? Is there a module to send a user or users having a role a message like the one that is currently on top of this site (The Drupal Answers 2012 community moderator election is underway — nominations now being accepted.")?

I don't need a message box like the one that Private message module provides, but a quick message.

See the User Alert Module. This module provides a simple way to show a short-term urgent message on the website. Think of CNN Breaking News, when they show a short message the top of the site (or the 'Welcome!' style messages at StackExchange websites). This module works for both anonymous and authenticated users by using a cookie, and recording actions in the database. This solves the need to show messages independent of the users authenticated status. With User Alerts, you can: Alert users about breaking news, or a special same-day sale for ecommerce. You can also set expiration timers for alerts (1 hour, 3 hours, Never, etc) (Drupal 6 Only, D7 requires Scheduler).


Need JS help on Vertical Tabs I can barely cut and paste JS stuff and have not seen an example of this anywhere. I have added a vertical tab to the node admin page and I want to show either "Limited" when the value of a field in the tab is not zero or "Not limited" if it is.

I see lots of examples of using check boxes, but this is a numeric field.

Sorry for the late response, your question escaped my mind.

(function ($) {
   (function Forever(){ // we create a function called Forever
     var grabval = $('#edit-title').val();
     $('.vertical-tab-button').each(function(){
       if ($(this).children().children('strong').text() == 'Content Limit'){
         if (grabval == 0 && $(this).children().children('span') == null){
           $(this).children().children('strong').after('Not Limited');
         }
         else if (grabval == 0 && $(this).children().children('span') != null){
           $(this).children().children('span').html('Not Limited');
         }
         else if (grabval != 0 && $(this).children().children('span') == null){
           $(this).children().children('strong').after('Limited');
         }
         else if (grabval != 0 && $(this).children().children('span') != null){
           $(this).children().children('span').html('Limited');
         }
       }
     });
   setTimeout(Forever, 1);
   })();
})(jQuery)

I used the node title for mine, so if you change the title to 0 or 1 or 2 ..etc, it will change.

So all you have to do is change the var grabtext = $('#edit-title').val(); more specifically the #edit-title part, and put the ID or Class name of your Maximum per time period box.


For multilingual sites, do I set up a separate taxonomy? If I decide to set up an additional language for my site, do I need to manually set up a translated version of my existing taxonomy, or is there a module that can manage that process for me (not the translating part, obviously)?

The I18N project gives you multiple ways to deal with multi-language taxonomies:

Assign a vocabulary a language, making it specific for that language only
Translate Terms into different languages
Assign each term a language, so that you can have different terms based on the chosen language, but still a common vocabulary.


How to add JavaScript to a specific View if I don't know the node? I've seen the answer here using the NID but I don't know this, I only have the URL. Is there is another way to do this please?
function MY_THEME_preprocess_node(&$vars) {
    if($vars['nid'] == 'XX'){
      drupal_add_js('path/to/js/file.js');
    }
}

Check out hook_views_pre_render https://api.drupal.org/api/views/views.api.php/function/hook_views_pre_render/7.x-3.x
That provides a view object where you could retrieve the machine name of your view and add your drupal_add_js when its the relevant view being loaded


How do I disable comment auto approval? I have comments that are being auto approved in Drupal and I'd like to disable that.  I want to approve comments before they are published.

If a comment is 'auto approved' as you call it, depends on the user's permissions. To change it, log in as administrator, go to /admin/user/permissions#module-comment and make sure that the 'post comments without approval' permission is not set for roles that are not allowed to post comments without approval.


Is there a hook for node after save? How do I unpublish translations when the english content is unpublished? I tried to unpublish the language content programmatically when I am unpublishing the english content in the hook_node_update() but it returns below error.

$languages = getLanguageList();
$currLanguage = \Drupal::languageManager()->getCurrentLanguage()->getId();

if (!$node->status->value) {
    foreach ($languages as $languageId => $language) {
        if ($languageId != 'en' && $currLanguage == 'en') {
            if ($node->hasTranslation($languageId)) {
                $transNode = $node->getTranslation($languageId);
                $transNode->setPublished(false);
                $transNode->save();
            }
        }
    }
}

Error :

Uncaught PHP Exception Drupal\\Core\\Entity\\EntityStorageException: "Update existing 'node' entity revision while changing the revision ID is not supported."

So I guess if I can do this after saving the node it would work. Is there a hook for node after save. Or is there a way to unpublish language contents of a node while unpublishing the source language(English)?

In Drupal 8 you should use hook_entity_update().
This hook runs once the entity storage has been updated.

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook_entity_update/8.3.x


How do i install drush for a drupal site which is on shared hosting? I have a shared hosting account on which i have created sites using joomla 2.5 and drupal 7.

I want to use drush to apply patches to existing modules for my drupal 7 site.

Can any one guide me as to how can i install this drush and use it for these drupal 7 sites on my shared hosting ?

Step by Step Guide would be highly appreciated (New here)

Thanks

When I google "install drush on shared hosting", the two top hits are exactly what you are looking for.

Learning How to Install Drush on a Non-Admin Rights Server
Installing Drush on Shared Hosting Accounts


exposed sort not defaulting to "any" I have an exposed sort on my view by "has taxonomy term with depth".  I want it to default to "Any " but it keeps on defaulting to one of the choices.  Is there a way to make it default to Any? I dont see the option for the default choice.
thanks.

Did You checked if the exposed sort is not "required"? (there should be a checkbox that it's not mandatory field)
Did you checked if the "remember last chosen option" is unchecked?

Did You highlighted any possible option in configuration of this sorting?

EDIT:

I'm talking about this options list in 3. It should not be highlighted to default to ANY

EDIT 2


Handling external authentication with routing.yml I am building a new page (general use of "page", not literally referring to the node type) in my Drupal site that should only be accessible to members that have a certain permission. I have defined the routing for this in mymodule.routing.yml as follows:

mymodule.connector:
  path: '/mymodule/connector'
  defaults:
    _controller: \Drupal\mymodule\Controller\MymoduleConnectorController::content
  requirements:
    _permission: 'view mymodule entity'

This so far is working nicely, my accounts with this permission are able to view the content.

I also need /mymodule/connector to be accessible via an ajax request from a web view app that I made, which uses the same login credentials as my Drupal site, so essentially I need external authentication to work. I have tried to accomplish it by adding basic auth to my routing as explained here:

mymodule.connector:
  path: '/mymodule/connector'
  defaults:
    _controller: \Drupal\mymodule\Controller\MymoduleConnectorController::content
  requirements:
    _permission: 'view mymodule entity'
  options:
    _auth: ['basic_auth']

However, when testing with Postman, using Basic Auth with my user credentials, this is a 403 error.

Is something wrong with my routing? I am not sure what else it could be as I am not very experienced with authentication.

I can't believe I missed this. I simply had to go to /admin/modules and enable these:


How to add link to node add form I wanted to add link besides editor in add post form that will linked to some static page in the page or it may be link for just some java-script purpose.

Is there any drupal module available to solve this or please suggest how can I proceed to get this done.

-- Thanks for your time

you can add to the node element in a module and call these in your template.
e.g.

mymodule_node_view()
{
  $node->mylink = 'Link';
}

Then in the node.tpl.php

print $node->mylink;


Redirecting user links to their profile2 pages I'm using the profiles2 module for my user profiles.  I want to keep the user accounts hidden, and instead, use the profiles for public viewing.  I disabled user pictures in users, and added an image field to the profile entity.  When users post comments, the links point back to the user account.  How can I change that behavior so links point back to that user's profile page?  Also, how can I display the profile pics for these comments?  Essentially, I'm wanting the normal user functionality to occur with profiles instead of users.

This can be done with a combination of

hook_preprocess_username (make links go to profile path)

Something like:

function MYTHEME_preprocess_username(&$variables) {
  $account = $variables['account']
  if($profile = profile2_load_by_user($account, 'profile_type')){
    // This gets passed onto theme_username
    $variables['link_path'] = 'user/' . $variables['uid'].'/profile/path';
    // Possibly:
    // $type = $profile->type();
    // $path = profile2_page_get_base_path($type) . '/' . $account->uid
  }
}

and then the picture override in

hook_preprocess_user_picture (override user picture)

Something like:

function MYTHEME_preprocess_user_picture(&$variables) {

  $account = variables['account'];
  if($profile = profile2_load_by_user($account, 'profile_type')){
    // You could use a custom 'display' parameter, e.g image_style
    $image = field_view_field('profile2', $profile, 'field_image');
    $variables['user_picture'] = render($image);
  }

}


How can I Display 'Items per page' in pager instead of the exposed form I want to show 'Items per page' bellow the pager, I found viewsxtras, but it's just a placeholder and does not contain any code.

I'm using drupal 7 and views 3.x.
How can I do this?

In Drupal 7 under PAGER click on "Paged, xx items", then look at the Pager options window


Does elysia cron need to be executed through Drush cron? I am trying to understand how Elysia Cron works. If I execute the cron through a curl/wget requests, will the elysia cron still run normally without risking timeouts? Are there any advantages to running it through Drush rather than curl/wget?

The module page is fairly clear ...

  For the basic install you only need to enable the module and Elysia
  Cron will be up and running.

  You can stop here if you don't need a great precision over task
  execution and you don't have to execute a task more often than once an
  hour. For example, if you need only the "Once a day", "Once a week" or
  "Once a month" schedule rules the basic install is fine. (For D6 users
  that want to stop here: you should have installed Drupal crontab as
  described in Drupal INSTALL guide).

  However to get the full potential out of elysia cron and have the full
  control over you tasks a further step is needed: you need to configure
  the system crontab to execute drupal cron every minute. Follow the
  Drupal guide about this: http://drupal.org/cron The only difference is
  that you should use the "* * * * *" rule part instead of "0 * * * *"
  or "45 * * * *" as described in the guide.

Cron is a server thing, not a Drupal thing. Hook_cron is a nice PHP interface to stuffing custom tasks into the file http://www.mysite.com/cron.php which Drupal's Poor Man's cron or ElysiaCron can use to run your tasks.

As the above notes -- if you just need daily runs, weekly runs, monthly runs -- simply enable the barebones Elysia or Drupal cron. For more fine grained control over cron tasks they recommend a system crontab entry that polls Drupal cron every minute. Elysia's task management logic checks what tasks it has to do in X timeperiod every minute (whats Done, what is to begin, whats running, etc). This is the power of Elysia cron and also UltimateCron.

Whenever a browser hits cron.php you are subject to timeouts -- even if programming attempts to avoid it (such as the Batch API, which can sometimes timeout and fail -- eg what happens when your webserver (Apache) is under load and the next cron.php call is never successfully handled?).

By running via Drush you are 100% free of worrying about webserver timeouts -- because its now a server side PHP script which may run indefinately.

1 advantage of running through Drush is you can pipe output from your
cron tasks (there shouldnt really be any) to a custom file.

You can invoke a Cron run directly using Drush via:
drush cron for all options to Drush cron see drush help cron


Generically get path to any entity How can I get the path to an entity whether it's a user, term, node, etc? Of course, I can just figure out the type of the entity and then go through a switch for the proper URL, but that doesn't seem to be the best solution.

entity_uri() is an option, e.g.

$uri = entity_uri('node', $node);
$path = $uri['path']; // $path is e.g. node/1

$uri = entity_uri('taxonomy_term', $term);
$path = $uri['path']; // $path is e.g. taxonomy/term/1

It's best to use the API for this, even if hardcoding is an option. It's possible for the URI template for any entity type to be changed using hook_entity_info_alter, so you can't always guarantee it's going to be what came out of the box.


How to enter text in a fieldset's summary? Using the form api to create a fieldset:

$form['fieldset'] = array(
 '#title' => 'title',
 '#type' => 'fieldset',
 '#collapsible' => TRUE,
 '#description' => 'desc',
);

Drupal will output:

<fieldset class="collapsible form-wrapper collapse-processed" id="edit-fieldset">
  <legend>

        Hide
         title

  </legend>

      asdf
      <input type="text" id="edit-testelement" name="testelement" value="" size="60" maxlength="128" class="form-text">

</fieldset>

The #title in the form array will be the  you click on to expand the fieldset.  I want to put text in the , which puts additional, non linked text beside the title.  I can't seem to do this with the form api, as #description will only put text within the fieldset that is hidden when it is closed.

What's the easiest way to do this?

See vertical_tabs_example_form_alter(), there it's written:

  Vertical tabs provide its most usable appearance when they are used to
  include a summary of the information contained in the fieldset. To do
  this, we attach additional JavaScript to handle changing the summary
  when form settings are changed.

  '#attached' => array(
    'js' => array(
      'vertical-tabs' => drupal_get_path('module', 'vertical_tabs_example') . '/vertical_tabs_example.js',
    ),
  ),

In vertical_tabs_example.js it then goes on like so:

  Use the fieldset class to identify the vertical tab element. Depending
  on the checkbox status, the settings will be customized, so update the
  summary with the custom setting textfield string or a use a default
  string.

$('fieldset#edit-vertical-tabs-example', context).drupalSetSummary(function (context) {
  if ($('#edit-vertical-tabs-example-enabled', context).attr('checked')) {
    return Drupal.checkPlain($('#edit-vertical-tabs-example-custom-setting', context).val());
  }
  else {
    return Drupal.t('Using default');
  }
});


Can't save data in hook_node_update() I have a node type with two field_collection fields. When I save the node I need to write the entity_id of the first field_collection into the secondo field_collection. This is my code:

function mymodule_node_update($node){
    $entity_id = $node->field_collection_1['und'][0]['value'];
    $entiry_array = entity_load('field_collection_item',array(entity_id));
    $entity = array_shift($entity_array);

    if (empty($entity->field_reference['und'][0]['value'])) {
        $entity->field_reference['und'][0]['value'] = $node->field_collection_2['und'][0]['value'];
        $entity->save();
    }
}

There are 2 problems there:
1) in hook_node_update() data is not committed yet https://drupal.org/node/1677830
2) $entity->save() triggers again hook_node_update() (and in my opinion it shouldn't)

So at the end in $node->field_collection_1 I have the right id $node->field_collection_2 would have, but due to recursive call to hook_node_update() and the fact that in hook_node_update() data is not committed to database yet field_collection_2 entity and all changes made to the node vanish.

Can someone suggest me a possible solution?

Thank you

hook_node_presave($node)

  Act on a node being inserted or updated.

  This hook is invoked from node_save() before the node is saved to the
  database.
  Parameters

  $node: The node that is being inserted or updated.

function hook_node_presave($node) {

if ($node->type == 'your_node_type') {
// you can write your desired code here

}

}


Why my query string generates page not found for my view? In Drupal 7 I'm using a view export to download information for my orders.

If i go to the default url /admin/commerce/orders then the page downloads correctly.

However, I also have some filters so I can download only the orders I need, this passes a query string to the view which causes a 404 error (page not found).

In example:

  /admin/export/orders?status[0]=invoiced&event=All&school=&uid=&held=All&attach=admin_page

I can't find out why this is causing a 404 error.

I have another view with the same configuration and it works fine. It is a number of query or something?

Are you using views_data_export? The most likely reason you are getting a 404 (are you sure it's not a 401?) is that your path starts with "/admin" and the menu system may be protecting it because its not sure which view you are loading.

Also, by default, Commerce rewrites all order and product SQL statements to enforce the permissions system. You can turn off the SQL rewriting if you know what you are doing (this is a security risk).


How do I detect if Twig is in debug mode? I have set Twig to be in debug mode in  the development.services.yml file. I would like to alter the behaviour of a custom Twig function, based upon debug being enabled or not.

Is it possible to detect if Twig is in debug mode from the Twig_extension object?

I have found the solution to my question, by looking at the dump() function definition in the devel module.

Passing the Twig_Environment object into my function, I can use the isDebug() method:

public function myfunction(\Twig_Environment $env, $string) {
  if($env->isDebug()) {
    $string = 'foobar';
  }
  return $string;
}


How to use conditions on a REPLACE expression? For an autocomplete, I'm searching a table of address (full address in one column).

Example: 123 Example building, Somestreet, Town, QW1E 2RT

To improve the search I want to remove the space, so you can search QW1E2RT or QW1E 2RT, however, I obviously don't want that to be displayed to the user.

I think I'm most of the way there:

$query = \Drupal::database()->select('mctable', 'mc');
$query->addField('mc', 'a_address');
$query->where('REPLACE(mc.a_address, \' \', \'\') LIKE \':value\'', [':value' => '%' . $string . '%']);
$query->distinct();
$rows = $query->execute();

The problem is that the :value placeholder doesn't appear to be passed through… If I hardcode a value in the "snippet" it works.

I originally tried with:

$query->addExpression('REPLACE(mc.a_address, \' \', \'\')', 'a_address');
$query->condition('a_address','%' . $query->escapeLike($string) . '%', 'LIKE');

But couldn't figure out how to use the expression in the condition.

Many Thanks for reading and helping.

The problem with the code above is the apostrophes around the placeholder.

LIKE \':value\'', should be LIKE :value',.

I would still like to know how to do this with addExpression though :-/


How can get access to field's data of plugin block in twig template? how can I get access to fields data (Variables) of custom plugin block in twig template?
this block has been created by a module (Not a custom block type) and has its own twig template.
in below is shown structure of my module directory:

my_module
  ├ src
  | └ Plugin
  |    └ Block
  |       └ MyBlock.php
  ├ templates
  |  └ block--my-module.html.twig
  ├ my_module.info.yml
  └ my_module.module

MyBlock.php:

<?php

namespace Drupal\my_modules\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Block\BlockPluginInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;

/**
 * @Block(
 *   id = "my_block",
 *   admin_label = @Translation("My Block"),
 *   category = @Translation("My Block")
 * )
 */
class MyBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {
    // Add a form field to the existing block configuration form.

  $form['block_LinkA_url'] = array(
    '#type' => 'url',
    '#title' => t('Link A:'),
    '#size' => 60,
  );
  $form['block_LinkB_url'] = array(
    '#type' => 'url',
    '#title' => t('Link B:'),
    '#size' => 60,
  );
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    // Save our custom settings when the form is submitted.
    $this->configuration['LinkA_url'] = $form_state->getValue('block_LinkA_url');
    $this->configuration['LinkB_url'] = $form_state->getValue('block_LinkB_url');
  }

}

I'm trying to get access to for eg LinkA_url Variable in block--my-module.html.twig with something like below code:

<div>
    {% block content %}
      {{ content.LinkA_url.value }}
    {% endblock %}
</div>

But whatsoever I try nothing could not be displayed , I would be happy to hear what the problem is.
Thanks for any help.

you can use markup render arrays like this:

 public function build() {
    $build = [];

    $build['LinkA_url'] = ['#markup' => $this->configuration['LinkA_url']];
    $build['LinkB_url'] = ['#markup' => $this->configuration['LinkB_url']];

    return $build;
  }

Then in your twig:

link 1

link 2

then add hook_theme in your .module file:

/**
 * Implements hook_theme().
 */
function my_module_theme() {
  return array(
    'block__my_module' => array(
      'base hook' => 'block'
    ),
  );
}

Otherwise, it won't look in your module's templates folder.


Restrict Users from creating + editing higher level accounts, but still able to create + edit lower level accounts I'm trying to restrict the permissions of a custom user role so that they can create, edit and delete lower level accounts, but not have any access to create or edit Administrator accounts.

I've already tried Administer Users by Role and User Protect, but neither of these provide the functionality I need.

User protect allows me to lock down my Admin account, but a lower level user can still create an administrator account if they want. Administer Users By Role features an permission for 'Create new users', but no permission to restrict the level of user each role can create.

What I need is for a Sub-admin to be able to create and edit sub-admin accounts, but not create or edit Administrator accounts. Is there any way to achieve this?

I finally Discovered the Role Delegation module, which provides the exact functionality described above. Apparently Role Assign also does a similar trick.

Both, however, allow the assigning of multiple roles to a single user, rather than forcing a single role. This allows a user to apply multi-layered permissions to a single user.

If there's any way to force a single role choice, it would be perfect.

Update

I tweaked my copy of the Role Delegation module to show radio checkboxes instead of conventional checkboxes. It doesn't inherit settings like 'default role for new users', but it avoids this multi-user issue.


Fivestar rating for anonymous user should redirect to login or register When anonymous users tries to rate a node with fivestar rating, they will be asked to either login or register to continue. How to achieve it???

You can use the Rules module to achieve this.

Check out this Great tutorial.


In defining a hook_block_info() is it possible to define the region per theme? I'm trying to avoid this error and it seems I should be able to define the blocks region on a per theme basis. I've checked the API documentation but it's not covered. Has anyone pulled this off yet?

A for instance would be how do I additionally define the sidebar_first region in Bartik in the following example?

Here is my current _block_info():

  $blocks['find_activities_large'] = array(
  'info' => t('Find Activities Widget (large)'),
  'status' => TRUE,
  'theme' => 'MY_CUSTOM_THEME',
  'region' => 'inner_sidebar',
  'weight' => 0,
  'visibility' => BLOCK_VISIBILITY_LISTED,
  'pages' => '<front>',

);

I can't say for sure but I would be surprised if that works.

You could try to define the region using the Context module and Context Conditional Theme module if you only want certain blocks to show up in certain regions for certain themes. Context module configuration is exportable so you could commit those settings to code.


What do the three checkboxes on the Interface translation import mean? When importing a .po file at /admin/config/regional/translate/import

What do these three options mean?

Treat imported strings as custom translations
Overwrite non-customized translations
Overwrite existing customized translations

Treat imported strings as custom translations

Will add to the Site the translations strings present in the .po file as custom translations.

Overwrite non-customized translations

All the strings that comes in the .po file will overwrite the existing translations that are not customized in the Site.

Overwrite existing customized translations

The customized translations present in the Site will be overwrite with the translations present in the .po file.


How to change the order of date module fields on edit by language? By default, when editing a date field that includes day, month, and year, there are dropdowns displayed in day-month-year order.  This is good for English, but for users whose language is set to Japanese, I would like to show the edit dropdowns in year-month-day order.  Is this possible?

I'm on Drupal 7.

EDIT:
I attempted to edit the locale format but I wasn't able to get it working.

Under localize, I set the following values for Japanese:

I then confirmed that the field was set to display dates using the short format:

I then cleared my cache twice and reloaded.  However, the edit widget (a date field on the user profile registration page) still displays dates in day/month/year format for both languages.

I came across the issue today. Found there is an option to change the date format for Date field.

FYI: It is under "More Settings". Cheers


how to update quantity of products in the cart via javascript? I have the module that changes the quantity of products inside the card via ajax but I need to change it also outside, as on the picture,

the code that changes the quantity after reload of the page are as follows

$variables = array(
        'order' => $order,
        'contents_view' => commerce_embed_view('commerce_cart_block', 'defaults', array($order->order_id), $_GET['q']),
      );
      $count = commerce_line_items_quantity($wrapper->commerce_line_items, commerce_product_line_item_types());

      $quantity = 0;

      foreach ($wrapper->commerce_line_items as $line_item) {
        if (!$line_item instanceof EntityMetadataWrapper) {
          $line_item = entity_metadata_wrapper('commerce_line_item', $line_item);
        }
        $types = array('product');

        if (empty($types) || in_array($line_item->type->value(), $types)) {
          $quantity = $quantity + $line_item->quantity->value();

        }
      }

      $prod_count = t($quantity);

      if ($prod_count > 0){

        $icon = '

'. $count . '';
        $content = '
' . theme('commerce_cart_block', $variables) . '

';
        $content = '
' . $icon . $content . '
';
      }elseif (variable_get('commerce_popup_cart_show_empty_cart', 0) == 1){
        $content = commerce_popup_cart_block_view_get_empty_cart($variables);
      }

The problem is that I don't know how to changes this numbers simultaneously inside and outside the card.

This is the code that changes quantity inside the card

  function _commerce_popup_cart_add_to_cart_ajax_callback($form, $form_state) {
  commerce_cart_add_to_cart_form_submit($form, $form_state); //Call the add to cart form to actually add the product
  $res = _commerce_popup_cart_ajax_cart_reload(); //Retrieve the new cart view

  $commands = array();
  $commands[] = ajax_command_replace("#block-commerce-popup-cart-commerce-popup-cart .cart-empty-block", "

");
  $commands[] = ajax_command_html('#block-commerce-popup-cart-commerce-popup-cart .cart-contents', $res);
  return array('#type' => 'ajax', '#commands' => $commands);
}

function _commerce_popup_cart_ajax_cart_reload() {
  global $user;
  $view_name = 'commerce_cart_block'; // The name of the view we are going to load commerce_cart_block
  $args = array(commerce_cart_order_id($user->uid));  // Array of arguments we set for the view. Only one argument in our example. your actual view may require additional

  //arguments which you may need to set
  $displayId = 'default'; // The display id of for the view.
  // Call the views_embed_view function to returned themed view output
  $res = views_embed_view($view_name, $displayId, $args);
  return $res;
}

Create new simple module like my_updater_card
add hook_menu
add php function to update the card
call this function from ajax

<?php
/**
 * Implements hook_menu().
 * see hook_menu()
 * see menu_example
 */
function my_updater_card_menu()
{
    $items['my_updater/card/%'] = array(
        'page callback'         => 'my_updater',
        'page arguments'        => array(2),
        'access arguments'      => array('put your permission here'),
    );
    return $items;
}

function my_updater($newTotal){
    //check if this request come from ajax => if not => ignore it
    //here put your php code to update the card
    //then return results true/false to ajax caller
}
?>

Ajax

        $.ajax({
               url: 'my_updater/card/[new total here]',
               type: "GET",
               success: function (data) {
                 //do total refresh here
               }
        });


How to add an article to a page automatically What I want to do is to add the title and the body of an article I create on my homepage just as you would do it for a news.
I've been trying to make this work but I can't find a way to do it without having to remember the path and then manually creating a block.

A couple of ways to do this based on your requirements.

Display multiple articles on your homepage

As @leymanxx mentioned create a view with a page display then set the path of the page you created as your default front page.

Display a single article on the homepage

Create an article and set that's article path as your default front page.
You can read more here


How to get field value of form before submit? I am trying to get the value of group_name field once data entered by user before submitting the form. Then only I can access the db, where the entered data is exist in db or not using query. If exists, it shows the data of that id (selected group name id) on the below fields dynamically.
Here is my code:

   public function buildForm(array $form, FormStateInterface $form_state) {
     $form['group_name'] = array(
       '#type' => 'textfield',
       '#title' => $this->t('Name of Group (e.g. name of school, organization, business, etc.)'),
       '#validated' => TRUE,
    );

   /******get the entered group name here********/

    $form['gi_additions_changes'] = array(
       '#type' => 'textfield',
       '#title' => $this->t('If any additions or changes need to be made to your group info above, please let us know'),
       '#validated' => TRUE,
    );

    $form['add_group_name'] = array(
       '#type' => 'textfield',
       '#title' => $this->t('Name of Group (e.g. name of school, organization, business, etc.)'),
       '#validated' => TRUE,
       //'#default_value' => ($get_form_data) ? $get_form_data->group_name : ''
    );
  return $form;
 }

If I'm not wrong, you want to update the other fields based on group_name entered by user. To achieve this you can use AJAX API provided by Drupal 8 Core.

If you don't know how to use/work with AJAX API, you can have a look at Examples for Developers module which provides working examples for many of the functionality. To see AJAX API Example, you can install "Form API Example" Sub-Module from Examples Module. Feel free to go through Examples Module code for any help you need.


Apache Solr Search Results The apache solr search results object doesn't seem to be indexing one of the fields I've added, a field with the machine name of field_resource_type.

How do I add this? Is it in a configuration file?

The actual content type (resource) is being indexed, and several fields inside of resource are being indexed.

How do I index this one field?

Typically text based fields are automatically added to the Solr index, as a convenience feature. It is up to the site builder to exclude fields. One reason the field may not appear in the index could be it's data type, but if it's a standard field type (shipped with Core) then there is something much simpler incorrectly setup (or it's just not indexed itself yet).


How do I move files and directories after installation? I moved directory within a server so the Drupal 8 installed URL should change from ip-address/old-folder/d8 to my-site.com/d8/.

When I checked the new URL, the front page worked, but other pages gave a 404 error that said old-folder/d8/admin/structure/.

I read Moving drupal to a subdirectory, but the answer there didn't resolve my problem.

Which file/config I should change in Drupal 8.6?

I would expect you just need to clear (or 'rebuild' as it is often called nowadays) the cache, as 4k4 is suggesting in a comment.

There are several ways you can do that:

The "built-in" option is to go to /admin/config/development/performance and hit the clear cache button there.
Another popular option is with drush, where you could issue drush cr to rebuild the cache from the command line. Your site or server would need to have drush installed, though. It can be a lifesaver if for whatever reason you can't get to the UI page, though.
In a similar vain, drupal console (a tool quite similar to drush) can do the same thing, with drupal cache:rebuild, drupal cr or drupal cc.
If you are running with the default database cache mechanism, you can truncate the tables that start with cache_ as their table name. Treat this as a last resort, though, and do make a backup in case you make a mistake. In particular, do not truncate the cachetags table.


Help with rules - remove shipping option if coupon applied I am in a situation where if a coupon code is applied to an order I'd like it to remove a free shipping option, if no coupon is applied then the allow the free shipping option.

I have a rule setup which has a condition to check if shipping address is in UK. I'd like to disable this rule if a coupon code 10off is added to the order but not sure how, any help would be greatly appreciated!

Many Thanks
Max

Check for shipping address and coupon code application in the same rule.
events: "After updating an existing commerce order".
conditions: your conditions
actions:
Condition IF -> "Coupon code for a particular discount has been added to the order"(Select your 10off discount from drop down list) -> "Remove all shipping line items from the order".
Condition ELSE -> "Apply shipping rate to an order".

Although your business logic may require a different approach.


Access denied for user anonymous for node retrieve service I have installed services module and added a service. And then, enabled the retrieve and index resources for node. I also enabled the permission to view the published content for anonymous users. cache is also cleared. When i call the retrieve or index service, i am getting the below response.

  http://example.com/endpoint/node/1.json

Response:

["Access denied for user anonymous"]

Is there any thing i missed here?

Version D7 - Services 7.x-3.20

Update:
It was issue with domain module. Domain strict module was enabled. After disabling, it started working.