Taxonomy terms as numbers? Creating real estate website, i have a lot of exposed filters.
For year when the object is built i have number field which in views is as exposed filter.
When user makes input he puts year 1961 for example.

User searching in exposed filter writes 1961 and filter is set up like "equal or higher" so he gets all objects made 1961 and higher. Works fine.

But i have a problem with floors.
For floors i have vocabulary:
ground floor
1
2
3
4
etc..
attic

I cant use number field because of ground floor and attic so i had to use taxonomy.
But now i cant use equal or higer as exposed filter so if user picks number 3 he only gets appartments with 3 floors.

You could still use floors as numeric field, having numbers as keys and display output as needed.

Example of "List (integer)" values:

-1|Basement
0|Ground floor
1|1
2|2
3|3
100|Attic

This would allow you the same logic for floors.

EDIT:
When selecting the field as a filter in Views you need to choose the delta value. It looks something like Content: Floors (field_floors:delta). This will give you the integer filter options such as Is greater than or equal to.


Is the latest Drupal 7 core, 7.59, fully PHP 7 ready? I just transferred a Drupal 7 installation to Debian 9 and when I try to connect to the site I get the error PHP Fatal error:  Cannot use "self" when no class scope is active in vars.module on line 39.

There is a Drupal issue on it Upgrade to PHP7: Cannot use "self" when no class scope is active [#2668622] , but it doesn't seem to be fully resolved and I am not sure which PHP7 version it works on.

The version of PHP currently on Debian 9 is PHP Version 7.0.27-0+deb9u1

The point is I am running the latest version (Drupal 7.59) on Ubuntu 16.04 whose PHP version is PHP Version 7.0.30-0ubuntu0.16.04.1 and it runs without that error.

Are there versions of PHP 7 running on Debian 9 which work with latest unpatched Drupal 7.59, perhaps later ones like PHP 7.1 or PHP 7.2?

Maybe the bug only manifests in  early versions of PHP 7.

UPDATE: It turns out that vars.module is from the contrib module Variable API and not part of core, and was only enabled to support the Textile module. Disabling it solved the problem.

For the most part, Drupal 7 core is compatible with PHP 7, however in some cases you might run into issues, depending on your specific website's configuration.

There is a meta issue on drupal.org that you can follow at https://www.drupal.org/project/drupal/issues/2656548

In addition, although most of the widely used modules are, not all contributed modules are compatible yet.
The issue you linked is for a contributed module, not Drupal core.

Your best bet is to test your site and its particular modules on a development PHP 7 environment and then resolve any issues you find. Once you're happy that the site is functioning as it should, update your PHP version on your production server.

In my personal experience, with at least a dozen Drupal 7 sites of varying sizes, I have had no issues with Drupal 7 on PHP 7.0 or 7.1 but I have had a few issues with 7.2 when it was new (which may have been resolved by now).

In some cases I have had to apply patches that were already available in issue queues, but generally I've only had to update modules to the latest versions.


How to make the name of an organic group unique can someone explain how to make groupnames unique? If i create 2 groups with the same name, i want to become a validation error. Actually i tested og in the commons distribution an there i can create groups with same names, but in the list of all groups are only one of the same groups listed.

Thanks for your help.

Greats Daniel

Assuming your og groups are based on node entities.

  You can have unique group titles with help of unique_field module.
  With help of this module you can set the title field as unique fields the content type generating groups on your site.


How to rewrite image url in nodes? I need to rewrite all image urls inside certain node types into custom-defined urls. For example, this image:

need to be rewritten to:

And I need to do that for all of the user-generated images. Obviously, the goal is to be able to off-load all images to a secondary file server.
How can I do that?

Thanks

ok if you're looking at drupal 6 look into custom_url_rewrite_outbound(). For D7, you can use hook_url_outbound_alter().

Some example code I have sitting around in a module that takes media resources of a Drupal site and points the generated urls to another server to serve media content, we used Nginx. Keep in mind that if you're just sending back to same server on another port .... you're just feeding yourself more traffic -- which isn't as helpful as a true CDN.

 /*
 *
 * A mechanism in Drupal to rewrite outbound urls to point to another domain.
 * This can be used to serve static content from a dedicated server, aka a CDN.
 *
 * Taken 100% from the following url. I am not smart enough to pull off this
 * magic :).
 *
 * http://drupal4hu.com/node/260
 *
 * In the below code $conf['dew_cdn_domain'] is a custom value in
 * settings.php that points to like "http://yourotherserver.com" to serve
 * media files.
 */

/**
 * Implementation of hook_file_url_alter()
 *
 * This inspects and transforms file urls to our remote CDN host.
 */
function dew_cdn_file_url_alter(&$uri) {
  global $conf;
  static $drupal_static_fast;
  // A drupal_static_reset() would clear this and then we need to rerun variable_get.
  if (!isset($drupal_static_fast['dew_cdn_domain'])) {
    $drupal_static_fast['dew_cdn_domain'] = &drupal_static(__FUNCTION__);
    $drupal_static_fast['dew_cdn_domain'] = $conf['dew_cdn_domain'];
  }
  $cdn_domain = &$drupal_static_fast['dew_cdn_domain'];
  if ($cdn_domain && strpos($uri, ':') === FALSE) {
    $uri = $cdn_domain . $uri;
  }
}

/**
 * Implementation of hook_stream_wrappers_alter()
 */
function dew_cdn_stream_wrappers_alter(&$wrappers) {
  $wrappers['public']['class'] = 'DrupalCDNPublicStreamWrapper';
}

/**
 * Any files that would go the public stream public:// get rewritten to another
 * base domain.
 */
class DrupalCDNPublicStreamWrapper extends DrupalPublicStreamWrapper {
  function getExternalUrl() {
    global $conf;
    $path = str_replace('\\', '/', $this->getTarget());
    return $conf['dew_cdn_domain'] . self::getDirectoryPath() . '/' . drupal_encode_path($path);
  }
}


IMCE module is not showing icons on the editor I installed the IMCE module, but it didn't add any icon to the editor menu toolbar. It manually loads with domain.com/imce.

You need IMCE WYSIWYG bridge module to connect it with WYSIWYG editor.

For CKEditor, configure the editor for your input filter and choose "IMCE" button.

For TinyMCE it is enough to select "Image" button.


Unable to send e-mail i want to create a new user, for this , i have done the following things.
1.Installed SMTP module through drush
2.Installed sendmail through apt-get
3.and created the new user, when i trying to create a user it shows the error as mentioned in image.
Please someone help me to get out of it.

You dont necessary need the SSMTP module.

I think this is a bad configuration with your local environment. For testing purpose you should consider using Gmail.

  Debian/Ubuntu users can Install with this command or click here to
  open up apt:

  sudo apt-get install ssmtp

  We need to then need to edit, ‘/etc/ssmtp/ssmtp.conf’:

root=username@gmail.com mailhub=smtp.gmail.com:587 rewriteDomain= hostname=username@gmail.com UseSTARTTLS=YES AuthUser=username AuthPass=password FromLineOverride=YES

  Then add each account that you want to be able to send mail from by
  editing, ‘/etc/ssmtp/revaliases‘:

root:username@gmail.com:smtp.gmail.com:587
localusername:username@gmail.com:smtp.gmail.com:587

If you do not want to used Gmail here is another tutorial with an alternative Sendgrid.


How to create views of nodes and all revisions in? As it is obvious form the title I am want to create a views which has all contents of a given type and all its revisions under it.

I tried these ways but none of theme gave all I need:

Create a views from contents with relation to revision NID.
It just give the last revision.
Create a views from contents with relation to revision ID.
It has no difference with the previous one.
Create a views from content revision.
Again just the latest version appeared.

So what will be solution to do that?

Simple step by step instruction:

Try to create view by content revisions.
Remove relation to actual revision (added by default).
Also be sure that filter by published node isn't enabled.
It should work.


Access submitted form data in custom callback before hook_mail_alter() I wan't to alter contact form recipient according to what user chose in one of the dropdown fields of my Contact form.

I implemented hook_form_FORM_ID_alter() in order to add custom submit callback like this

 $form['actions']['submit']['#submit'][] = 'my_custom_callback';

to get submitted data.

I thought I could use State API in my_custom_callback() to store received data temporally and use it's value in hook_mail_alter() but it looks like hook_mail_alter() is called before my custom callback.

This is what the order of callbacks looks like:

Default Submit callback of Contact form;
hook_mail_alter();
my_custom_callback.

I wander if there is any way to change this order to this:

my_custom_callback;
Default Submit callback of Contact form;
hook_mail_alter().

Why do you need a submit callback at all? The built contact message is available in hook_mail_alter(), you can just access the submitted data there?

This is from a custom project where we did something similar:

/**
 * Implements hook_mail_alter().
 */
function yourmodule_mail_alter(&$message) {
  if ($message['id'] == 'contact_page_mail') {
    /** @var \Drupal\contact\Entity\Message $contact_message */
    $contact_message = $message['params']['contact_message'];

    if ($contact_message->bundle() != 'feedback') {
      return;
    }

    $recipient_address = $contact_message->get('yourfield')->value;
    if (\Drupal::service('email.validator')->isValid($recipient_address)) {
      $message['to'] = $recipient_address;
    }
  }
}


How do I add JavaScript to a page? I made a module, and I want to add a JavaScript file to that module; I enable the module and obvious it works, but I didn't see the JavaScript file that module should take with.

I just put code similar to the following in hook_menu():

function my2form_menu() {
      drupal_add_js(drupal_get_path('module', 'my2form') . '/abc.js');
}

Is it OK?

Adding a call to drupal_add_js() directly in hook_menu() doesn't work; the call to drupal_add_js() should be added on the code that is executed when Drupal is outputting a page. This means:

in the implementation of hook_init()
in an implementation of hook_form_alter(), hook_form_FORM_ID_alter(), or hook_form_BASE_FORM_ID_alter()
in the menu callback for the menu defined from the module

Within a form, Drupal 7 modules can use something similar to the following code, to add a JavaScript file to the currently output page.

$form['#attached']['js'] = array(
  drupal_get_path('module', 'my2form') . '/abc.js',
);

As alternative, if you write the following line in the .info file of a module, the JavaScript file will be added to any page.

scripts[] = abc.js

The path needs to be relative to the directory containing the module; if the file is contained in a sub-directory of that directory, e.g. javascript, the line should be the following one.

scripts[] = javascript/abc.js


D7 - Print node taxonomy terms including custom term field as CSS Class I have a list of possible taxonomy terms (vocab is called Categories) that can be referenced on a given node. For this particular vocabulary, I have a custom field called field_icon_class. The intention here is to make use of CSS Sprites, so when the terms for the page are rendered, they hopefully get printed out with the field as the CSS Class for the individual taxonomy term.

I've tried numerous ways to get these to render the way I would like to no avail. I've tried:

taxonomy_term_load_multiple($node->field_categories);

along with a combination of other iterative statements which weren't successful. Ideally, I would like for each taxonomy term for that node to render along the following lines:

[taxonomy term name]

Any ideas how this can be accomplished, or any module exists to do so? Much thanks!

Are you cool with using views?   I do this type of thing all the time on my site.  If you are then reply back and I'll post an example.


Tax rate on shipping price Drupal commerce shipping module.
I want to set a tax rate on a shipping price so that the shipping price with its tax component is integrated in the subtotal of the line items.
Guess it has to be done with rules but I don't know where to start.
Any help is very welcome!

I guess that, as the creator and maintainer of the Drupal commerce shipping, I should bid in.

The short answer is that right now, this is actually possible without creating the functionality yourself from scratch. The issue was raised in the Drupal commerce shipping queue (by yourself?). Anyways as stated there, this is something that should be handled by commerce core, which right now is lacking a way to apply taxes to line items which aren't the product line items.

I have a chat with Ryan about the problem, where we agreed that the product line item is a special case, since a lot of price handling is tied to the product, where all other line items, shouldn't have a relationship like that. The issue has been raised on the Drupal commerce issue queue, which I believe you are aware of.

If you don't have the ability to create the code for this yourself, your best bet is to wait for some one to fix it, or buy it.

Update:
This is now built in the Commerce shipping module, by exposing an event in rules that can be used to add taxes on shipping line items.


How do I get the index number of currently displayed slide of a Views Slideshow into the jQuery Cycle's "Before" advanced option? According to this StackExchange Answer, you can access jQuery Cycle options like so:

//on before function
before: function (curr, next, opts) {
    alert(opts.nextSlide + " of " + opts.slideCount);
}

However, the instructions in the views plugin say, "If one of the options you add uses a function, example fxFn, then you need to only enter what goes inside the function call" so in the Advanced Options before box I only put:

alert(opts.nextSlide + " of " + opts.slideCount);

This code yields the error Uncaught ReferenceError: opts is not defined in the console.

How do I access these jQuery Cycle variables (mainly the index of the current slide) from within my "Before" advanced option code?

Looking at the JS code for views_slideshow_cycle:

case "before":
  var beforeValue = advancedOptions[option];

  beforeValue = Drupal.viewsSlideshowCycle.advancedOptionCleanup(beforeValue);
// transition callback (scope set to element to be shown):
function(currSlideElement, nextSlideElement, options, forwardFlag)
  settings.opts[option] = function(currSlideElement, nextSlideElement, options, forwardFlag) {
    pager_before_fn(currSlideElement, nextSlideElement, options);
      eval(beforeValue);
  }
  break;

Your code isn't actually executed within the scope of the before callback, it's executed afterwards. The variable that the module provides is named options rather than opts, hopefully that will resolve to what you need and the change should be as simple as:

alert(options.nextSlide + " of " + options.slideCount);


Receiving an error when uninstall I am getting a WSOD after attempting to uninstall the Drupal Commerce module on Drupal 8.1.1 Has anyone seen this error before, and possibly point me a direction? Lost trying to fix this.

  Drupal\Component\Plugin\Exception\PluginNotFoundException: The "commerce_product" entity type does not exist. in Drupal\Core\Entity\EntityTypeManager->getDefinition() (line 125 of core/lib/Drupal/Core/Entity/EntityTypeManager.php).

Commerce for Drupal 8 must be considered unusable at this stage and very unstable as it is still in alpha version.

No stable version has been released yet, therefore it is advised not to try to build anything yet with it, and installation shall be considered for development purpose only.


Allowing third-party modules to alter the query executed by a module I am developing a module that exposes a public API, which includes functions to save data in his own database table, which is supposed to be used from any module that uses my module.

The module checks the content of the database to verify if a user is not allowed to access the site, or if users should be notified with an error message when they change something in their user profiles.
Considering that in most of the cases, the database table is the only table to check, should I change the code to allow third-party modules to alter the query being executed from my module through hook_query_TAG_alter() (or the more generic hook_query_alter()), or use a custom hook that other modules need to implement?

Not really sure what your question exactly is now.

I'm not sure why hook_query_alter() even exists, it did not in the beginning. I don't think that hook makes much sense, I can't think of a use case where you want to alter every query.
If you expect that other modules want to extend your query, then use "->addTag('yourmodule_tag')" so that it is possible to alter it. As you already said, this only covers cases where the same existing query should be changed. It might be possible to do other checks and then add a condition that can never be true (like 1 = 0) on the query, but that sounds hacky to me.
You can also define your own hook if you think that there could be more complex checks that other modules want to do. You probably want to re-use the hook_node_access pattern with three possible return values (ignore, allow, deny), see node_access().

You can do either or both of these two things, hook calls are rather fast in D7 because the hook implementations are cached and don't need to re-checked every time the hook is invoked.


How can I lock a user profile field after registration? I have a custom field on my user's profiles; I would like it is filled out at registration, but then not changed on post-registration.

How can I achieve this?

Could you use the Field Permissions module?  You could set permissions on the field so that authenticated users (or any other user role if you're using any) cannot edit this specific field, but anonymous (registering) users can.


show images for taxonomy terms in referenced node D7 question. I need to have a "clients" taxonomy with an image extra field on each term (the client's logo). Then I have a "project" content type. Projects belong to specific clients, ie the project content type has a term reference field to the client taxonomy.

When I click on a "project", I want to see the clients logo and not (only) the term name. This seems possible by following these instructions http://drupal.org/node/1224916, but this article is misleading: it suggests having an entity-reference field on the project content type instead of a term-reference. The problem with that approach is that when you connect a term and content by an entitity field, these two are not connected as far as taxonomy is concerned. So you lose all taxonomy functionality.

I beleive you can achieve this with the normal "Term reference" field, and a custom template file: field--field_my_custom_field.tpl.php in your theme folder which renders the image. You can access the value of your custom field through $items[$key]['#options']['entity']->field_my_custom_field where $key is the array index (if you have more than 1 value for this field, first item is index 0, second is 1 etc, usually you should just loop through the $items like foreach($items as $item) and then you can do $item['#options']['entity']->field_my_custom_field)

You may need to have a field.tpl.php (copy from root/modules/field/theme then duplicate it and rename the duplicate into field--field_my_custom_field.tpl.php) in your theme folder in order for it to work (or templates folder inside your theme folder, basically same folder as your custom field--field_my_custom_field.tpl.php) (Not 100% sure, but this was the case in Drupal 6)

API documentation for field.tpl.php

This may also come in handy: taxonomy-term.tpl.php

Sorry for unsure answer with a lot of unknowns, just trying to help :)


Run a check on every page load programmatically Drupal 7.

I have a site with Single Sign On (SSO) implemented. The implementation of the features is complete and the site is running perfectly.

Now, I have a requirement where I am supposed to check whether the session of the central server (on root of the domain and not using Drupal) is alive. I can do this by checking the availability of the session cookie on the root domain. And if the session is not active the user is logged out of Drupal.

I tried implementing it inside hook_init() but it only works for non-cached pages, whereas I want my code to be triggered on every page.

I also had a look at hook_boot() which runs even on cached pages. But, it is called while Drupal is still in bootstrap mode; even before themes and modules are loaded into memory. Which would mean that I would not be able to check the status of the user (whether the user is logged in?), because the user module and the included file session.inc would not be present in the memory while the execution of this hook.

So my question is which function (or hook) should I use which would execute on all pages(cached and non-cached) and which would give me access to common user properties (e.g. global $user object, user_is_logged_in() function etc)?

(I'm assuming Drupal 6)

Looking at bootstrap.inc, hook_boot is called on all pages, as long as agressive caching hasn't been turned on.

At this point the global $user variable should already exist (page_get_cache, which is called before hook_boot, makes use of it for example). module.inc has also been included, so you can use the functions included in that file to check for module existance and load them if necessary.

So, hook_boot looks like a good choice.


Views contextual filters programmatically alter add to or I have 2 fields in my contextual filters. Obviously, the default join is AND but I'd like to filter on one or the other field depending on which one of two arguments is provided.

I tried the following approach:

function mymodule_views_query_alter(&$view, &$query){

    if($view->name == 'my_links'){
        switch ($view->current_display) {
            case 'page_2':
                // dsm($query, 'Query');
                $query->where[0]['type'] = 'OR';
            break;

            default:
                # code...
            break;
        }
    }
}

However, using the devel module to inspect the Views data, the type field in the where section of my View still outputs AND instead of OR.

Which means my attempts to alter my View is not working.

Can anyone help me get this working?

If you have a way of knowing both filter values (like NULL and 12), then I would use hook_views_pre_build and unset the NULL field.

function test_views_pre_build(&$view) {
  // Do some checks for view name and current_display
  unset($view->display_handler->handlers['argument']['null_field']);
}


Create validation to input alphanumeric and with specified symbols for field type password in user module In the user module for field type password input I want to avoid hazardous characters input so i added #required and '#element_validate. But as i am new to drupal i dont know how to processed and also i am not sure if i am in right direction or not . Please help me

if (!$register) {
  $form['account']['pass'] = array(
  '#type' => 'password_confirm',
  '#size' => 25,
  '#description' => t('To change the current user password, enter the new password in both fields.'),
   //The below two lines are added by naveena.
  '#required' => TRUE,
  '#element_validate' => array('user_pass_element_validate'),

);

function user_pass_element_validate($element, &$form_state, $form) {
  if (!empty($element['#value'])) {
    form_error($element, t(''));
  }
}

You should use user_validate_current_pass().


Why is config for my view going to config/local? We use config_split to slice off parts of the site config to other config folders (local, dev, stage, etc). This more or less works as expected.
I have one view which always exports to config/local even though there is nothing I can see in the config_split configuration which is suggesting it do this.
Any ideas why it fails to export to the correct folder (config/sync)?

As is usually the case, 30 min after posting I figure it out.
My issue was caused by the "Include dependent configuration" option being enabled for the split configuration.


IP Restricting admin pages with whitelist in custom module This needs to be done within Drupal as my architecture does not allow for htaccess restriction.

I'm coming over from wordpress here so I've sort've Frankensteined this together from my wordpress code. Any thoughts or help on why this wouldn't be working?

Or maybe there is a much better way of doing this in code somewhere else? Or with some other function?

I'm on drupal 7.

function hook_init() {
if (path_is_admin(current_path()))
{
    // Whitelist
    $whitelist = array(
        'SOME IP ADDRESS',
    );

    // Check if current user IP is out of the whitelist, then redirect to home
    if(!in_array($_SERVER['REMOTE_ADDR'], $whitelist))
    {
        drupal_goto('frontpage', 302);
        drupal_exit();
    }
}
}

This does not.need to be done in code. I.would use https://www.drupal.org/project/restrict_by_ip  and set a role for specific IP that would have the specific  permissions that you need.


Delete Long Text Box I have a Node Content Type that has an "unlimited" number of Long text boxes allowed.  I have created one-too-many text ![enter image description here][1]boxes and cant seem to find a way to delete them.

Here is a link to what I am talking about

http://my.jetscreenshot.com/demo/20120730-gpz3-42kb.jpg

You don't actually "Delete" the extra values, you can simply leave the extra boxes empty and they will be ignored when you save the content.


Form alter overriding submitted values I have a form_form_id_alter function that sets some default values and a checkbox checked.

If I submit the form, with the checkbox unset and it fails validation, the re-rendered form re-sets the checkbox to a checked state (as per the form_alter), not the submitted state.

Is this expected behaviour? I would expect the submitted values to remain persistant.

Do I need to re-assign the submitted values in the form_validate function or am I doing something wrong?

I'm using this function to alter form:

// Form ID alter
function events_form_registration_event_node_form_alter(&$form, &$form_state, $form_id){
  global $user;

  $form['#validate'][] = 'events_form_registration_event_node_form_validate';

  // If node add.
  if(arg(1) == 'add'){

    // Check if the user is an event editor and perform the form_alter
    if(events_does_user_have_role($user)){

      // Show end date, checkbox value checked
      $form['field_show_end_date'][LANGUAGE_NONE]['#attributes']['checked'] = 'checked';

      // Event status, list value Open
      $form['field_event_status'][LANGUAGE_NONE]['#default_value'] = 'Open';

    }
  }
}

// Validate form.
function events_form_registration_event_node_form_validate(&$form, &$form_state){

  // Get the current end date value from submitted form.
  $current_end_date_value = ($form_state['values']['field_show_end_date'][LANGUAGE_NONE][0]['value']);

  // Set the show_end_date element to have the submitted value.
  $form['field_show_end_date'][LANGUAGE_NONE]['#attributes']['checked'] = $current_end_date_value ;

}

You need to check values of checkbox field in $form_state while setting it "checked" in line

$form['field_show_end_date'][LANGUAGE_NONE]['#attributes']['checked'] = 'checked';

This would be something like

$form['field_show_end_date'][LANGUAGE_NONE]['#attributes']['checked'] = isset($form_state['values']['field_show_end_date'][LANGUAGE_NONE][0]['value']) ? $form_state['values']['field_show_end_date'][LANGUAGE_NONE][0]['value'] : 'checked';

I haven't tested this code, but it should work just fine or it will give you idea about how to fix your problem. Hope it helps...cheers!


How to change name of result of rest export? I have a custom entity (ContractSubscription) created in a custom module (amap).
One of its fields (contract_id) is a link to another custom entity (Contract) of the same module.

I created a View to export content of ContractSubscription as a csv file using REST Export.
Among the settings of the view, I have:

Path: /amap/contract/export
Contextual filters: 'Contract subscription : Contract' (this allows me to view only the subscriptions related to a specific contract)

When I go to mysite/amap/contract/export/2, I have the expected result that I can save locally:

As far as I understand, the name of the result is defined by the actual path when the view is executed, i.e. '2' which is the end of the path (in fact the value of the contextual filter).

I'd like to have something like 'Contract2.csv' instead of '2'.
How can I do that?

The HTTP header Content-Disposition will suggest the filename the browser will save as. What's needed here is to make the REST export to add the HTTP header.

It turns out there's an existing issue for the CSV Serialization module. The current patch in the issue will take the last part of the URL after the slash and appends .csv to it (e.g. 2.csv in your example). You could modify the patch to use whatever filename you want to use for your CSV export.


Can we add different fields to instances of the same entity? I have a City entity with two fields (Title and Population), and I have created two instances of that entity.

Can I add different fields to these two instances?

Thank for you responses but I want different approach
Let me put my question in this way

1) I have entity:  City (with fields Population and Title)

2) of which I created two content (what should i call Chicago an New York ? contens of type City or anything else??):

Chicago and New York

3) now i know the entity City is fieldable i.e i can add custome fields to it, but those will be accesible to both ‘Chicago’ and ‘New York

4) What I want is ‘Chicago’ and ‘New York’ also be fieldable and have distinct field as well as common field

5) so, it should look like as
  Chicago : (Title - ‘Chicago’, Population - 1000, CField1 - ‘Hello’)
  New York: (Title - ‘Chicago’, Population - 1000, NField1 - ‘Hello’, NField2 - ‘Hello’)

Please tell me if above requirement is possible to implement

This single entity will use all of the fields you attach to it – it's still 1 instance (what we call a 'bundle') of an entity.

If you want to conditionally allow fields to be displayed on the entity edit form (or the display of the entity) use the Conditional Fields module: http://drupal.org/project/conditional_fields

If you really want to use different sets of fields, you need 2 different bundles, i.e. a "city" entity of bundle "foo" and a "city" entity of bundle "bar".


Search result to show link to the page not to the pdf file I am using the Search file attachments module (which searches for text from pdf files after they are indexed), and everything works fine.

But I would like in Search result to display link to the content (where I uploaded the file) not link to the PDF itself, so that the user goes to that page and from there he can choose to see the PDF.

I am still new to Drupal, but from what I have read that I have to alter $search_results in search-results.tpl.php and use template_preprocess_search_results() to display what I want (not sure if this is the right way) or is there another way to this?

EDIT:

I found that I could edit search_file_attacments.module and there is the link attribute in $results[] I just have to figure out how to get nid (so I can get the url) from fid

First, I can't install the Search File Attachments module at this moment, but you can read at the module's page:

  The module is based on the core search and no other module is
  required.

And I don't see any template page inside the module.

As in the search-result.tpl.php you will only have access to the $snippet variable, this is not a solution for you, because $snippet is a string, see the code inside search-result.tpl.php:

<?php if ($snippet): ?>
  <p class="search-snippet"<?php print $content_attributes; ?>><?php print $snippet; ?>

<?php endif; ?>

So your best bet should be implement the template_preprocess_search_results() in the template.php file of your theme.

See this example:

function THEME_preprocess_search_result(&$variables) {
    dpm($variables); //you need devel module to use dpm
}

Inside $variables['result'] you will have the values that you need to make your modification. See the dpm() output:

If you want modify the $snippet variable then change the value inside the function like this:

function THEME_preprocess_search_result(&$variables) {
  //searching the info that you need
  $variables['snippet'] = 'The new value';
}


How to hide breadcumbs on the front page? I would like to disable breadcrumbs on my home page and I don't know of any easy way to do this so I was going to just display:none the breadcrumbs class.

Suggestions welcome, thank you!

Assuming you are using D7.  There are a number ways to achieve it. I am providing three methods here.

Contributed module.
The easiest one is to use "Disable Breadcrumbs" module.

Theme Overide.
If you think it is overkill, don't want to use that module, you can also implement the preprocess html hook to remove breadcrumb like this:

/**
 * Implements template_preprocess_html()
 */
function THEMENAME_preprocess_html(&$variables) {
  if ($variables['is_front']) {
    // kill breadcrumb, set to empty array
    drupal_set_breadcrumb(array());
  }
}

Custom Module. You can also done this in your custom module by implementing hook_page_alter

/**
 * Implements hook_page_alter().
 */
function MODULENAME_page_alter(&$page) {
  if (in_array('front', $page['#theme_wrappers'])) {
    // kill breadcrumb, set to empty array
    drupal_set_breadcrumb(array());
  }
}


Archiving options in drupal 7 Apart from unpublishing a node for example, what are the other archiving options for outdated, no longer used pages in the site?

Is there a way to somehow archive the deleted pages?

I am running drupal 7.

try to use node archive module or auto archive module, they give a lot of stuffs to do. you can also type archive in search section in drupal.org nd choose modules to display all kind of modules about archiving.


How to use HTML entities in links in Drupal 8? I have a client who prefers some links to have the » symbol at the end. This is typically produced with the » HTML character entity.

In Drupal 7, you would do something like this:

l('Go there &raquo;', 'node/1', array('html' => TRUE));

But how do you do it in Drupal 8? The following won't work because of new sanitization rules:

$node->toLink('Go there &raquo;', 'canonical', ['html' => TRUE]);

They want the raquo in the link, not as a suffix.

The cleanst solution for this is doing it in CSS:

.my_link_css_class::after {
  content: '\00a0\00bb';
}

(\00a0 is for a space, \00bb is for the »)


How to alter the fields available for commerce backoffice Quick Edit? I have added a "waiting time" field to the orders in Drupal Commerce, so that each order has a waiting time.

I would like for the field to be available using the Quick Edit options of Commerce Backoffice. How to do it?

i am not sure if this might help, but recently i've written a custom hook to enable stock quantity field on commerce product quick edit form.

It should theoretically be possible yes to write a similar hook on commerce order.
Here's my custom module copy pasted :

<?php
/**
 * Implements hook_form_FORM_ID_alter().
 */
function commerce_stock_quickedit_form_commerce_backoffice_product_quick_edit_form_alter(&$form, &$form_state, &$product){
  $product = $form_state['product'];
  $product_wrapper = entity_metadata_wrapper('commerce_product', $product);
  $form['stock'] = array(
    '#type' => 'textfield',
    '#title' => t('Stock'),
    '#title_display' => 'before',
    '#default_value' => !empty($product->commerce_stock) ? $product_wrapper->commerce_stock->value() : 0,
    '#size' => 5,
  );
  $form['price']['#title_display'] = 'before';
  $form['#validate'][] = 'commerce_stock_quickedit_commerce_backoffice_product_quick_edit_form_validate';
  $form['#submit'][] = 'commerce_stock_quickedit_commerce_backoffice_product_quick_edit_form_submit';
}
/**
 * Validation callback to make sure stock is numeric.
 */
function commerce_stock_quickedit_commerce_backoffice_product_quick_edit_form_validate($form, &$form_state) {
  if (!empty($form_state['values']['stock'])) {
    if (!is_numeric($form_state['values']['stock'])) {
      form_set_error('stock', t('Please enter a numeric stock value'));
    }
  }
}
/**
 * Submit callback to update the product stock.
 */
function commerce_stock_quickedit_commerce_backoffice_product_quick_edit_form_submit($form, $form_state) {
  $product = $form_state['product'];
  if (!empty($product) && !empty($form_state['values']['stock'])) {
    $product_wrapper = entity_metadata_wrapper('commerce_product', $product);
    $product_wrapper->commerce_stock->set($form_state['values']['stock']);
    commerce_product_save($product);
  }
}


limit_validation_errors resetting form values in submit handler I have a custom button in my form_alter and a submit handler for that . I don't need validation for this button submit . I tried by giving limit_validation_errors to exclude all validation for the custom submission . When giving like this am not receiving any form values in submit handler . Any idea on how to resolve this issue ?

TRY

function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id){
 //Additional button for the Save as Draft feature
  $form['actions']['draftsubmit'] = array(
      '#type' => 'submit',
      '#value' => t('Save as Draft'),
      '#weight' => 1000,
      '#submit' => array('draft_form_submit'),
      '#limit_validation_errors' => array(),
     );
}

/**
 * Handles the save as draft button submit
 */
function draft_form_submit($form, &$form_state) {
    echo '<pre>';print_r($form_state->getValues());exit;echo '</pre>'; //Not getting values here
    $name = $form_state->getValue('field_p_name')[0]['value'];
    $dc = $form_state->getValue('field_p_dc')[0]['value'];
    $sec_type = $form_state->getValue('field_p_sec_type')[0]['value'];
}

UPDATE

I have other validations in other modules form_alter like

 function othermodule_form_alter(&$form, FormStateInterface $form_state, $form_id){
    $form['field_fwd_acl']['#element_validate'] = array('validate_IpAndNetworks');
    $form['field_fwd_dest_acl']['#element_validate'] = array('field_fqdn_validate');
    $form['field_amount_of_proxies']['#element_validate'] = array('field_instance_validate');
}

I mean these validations should not be worked when clicked on Save as Draft button is clicked

#limit_validation_errors prevents values from being passed to the submit handler, since they have not been validated. You can whitelist values by passing the form element key to #limit_validation_errors:

'#limit_validation_errors' => [
  // format follows the same as in the form state values. Elements
  // that are not #tree will be a string. Nested elements will be
  // an array.
  'element1',
  ['wrapper','element2'],
];

If you want to limit validation, but need all the values in the submit handler, then it's better to not use #limit_validation_errors. Instead, you can wrap any validation in a conditional to check if the 'next' button was clicked:

if ($form_state->getTriggeringElement() == $form['actions']['next']) {
  // Do form validation here. If the 'back' button was clicked, this
  // validation code will not be clicked. It will only be validated if
  // next has been clicked.
}

Note that if you use #required, validation will still happen even with the above code, since #required is handled separately. In this case, I don't use #required, instead I'll add custom validation to the above code:

if ($form_state->getTriggeringElement() == $form['actions']['next']) {
  // Do form validation here. If the 'back' button was clicked, this
  // validation code will not be clicked. It will only be validated if
  // next has been clicked.
  if (!strlen($form_state->getValue('some_element')) {
    $form_state->setError('some_element', $this->t('Please fill in a value for some field'));
  }
}


Importing Webform Submissions to create content Is it possible to use data a user submits via a webform via a simple import into a site.  It would not be the same site.  The webform is being used to collect specific data.

e.g.  webform data = user name, address, photo file, csv file submitted via webform in site A

webform submission data imported in to site B

You can make a view of your results (built-in webform) and with the https://www.drupal.org/project/views_data_export module turn in it into a CSV. Plenty of ways to import that.


Entityforms validation What is the best way to add some validation to the fields in an Entityforms form? I did some googling can't find any good answers.

Thanks,
Jonathan

Just in case someone else finds this.

You can use Entity Rules This was made for Entityform 1.x but could be used with 2.x

You could probably also use Field Validation if you didn't want to use Rules.


How to create a multilingual node programmatically? In the last days I tried to migrate a multilingual CSV file to Drupal 8 without success, so finally I decided to use a Batch Process to accomplish the task.

At this moment I have the batch process working, but at this point I need to create my nodes and create the translation. So, how to create a multilingual node programmatically?

Fortunately I found a post named Create and translate a multilingual nodes programmatically.

And here is the code with some comments:

use Drupal\node\Entity\Node;

$node = Node::create([
  // The node entity bundle in this case article.
  'type' => 'article',
  //The base language
  'langcode' => 'en',
  'created' => \Drupal::time()->getRequestTime(),
  'changed' => \Drupal::time()->getRequestTime(),
  // The user ID.
  'uid' => 1,
  'title' => 'My test!',
  //If you have another field lets says field_day you can do this:
  //'field_day' => 'value',
  'body' => [
    'summary' => '',
    'value' => '
The body of my node.
',
    'format' => 'full_html',
  ],
]);
//Saving the node
$node->save();
//This line is not necessary
\Drupal::service('path.alias_storage')->save("/node/" . $node->id(), "/my/path", "en");

//Creating the translation Spanish in this case
$node_es = $node->addTranslation('es');
$node_es->title = 'Mi prueba!';
$node_es->body->value = '
El cuerpo de mi nodo.
';
$node_es->body->format = 'full_html';
//Saving the node
$node_es->save();
//This line is not necessary
\Drupal::service('path.alias_storage')->save("/node/" . $node->id(), "/mi/ruta", "es");


How to redirect to another URL if visitor is anonymous when clicking a menu? I used the following code to redirect anonymous visitor to a login page:

<?php
  global $user;
  if ($user->uid) {
    print "Submit now...";
  }
  else {
    print "Submit now...";
  }
?>

But I can do this only in a block. What I want is put a Submit menu in the main menu and if anonymous visitor click the link he/she will be redirect to:

http://www.sourcecodester.com/user?destination=submit

after he/she login, he/she will be redirect again to the submit page as defined in the URL as "destination=submit".

Is this possible in main menu?

you can use Menu per Role module:

  This module allows you to restrict access to menu items1 based on user
  roles. It depends on the Drupal core menu.module—just activate both
  modules and edit a menu item as usual. There will be a new fieldset
  that allows you to restrict access by role. The fieldset also appears
  in the node edit form.


How do I add body class on specific content_type who have specific field? I need to add class in body when content type article and have image on it.
How do I achieve this?

I checked in theme_preprocess_html only found content_type as string. Don't know how to check image on it.

You will need to do a little work in the html preprocess:

/**
 * Implements template_preprocess_html().
 */
function mytheme_preprocess_html(&$variables) {
  $variables['has_image'] = FALSE;
  if ($variables['node_type'] == 'article' && ($node = \Drupal::routeMatch()->getParameter('node')) && $node instanceof \Drupal\node\NodeInterface) {
    $variables['has_image'] = empty($node->field_image->value) ? FALSE : TRUE;
  }
}

and the html template:

{#
/**
 * @file html.html.twig
 */
#}
<!DOCTYPE html>
<html{{ html_attributes }}>
  <head>
...
  </head>
  <body{{ attributes.addClass(has_image ? ['has-image']) }}>

This will add the class has-image to the body tag of every Article type content node.


Would be Drupal a good choice for my web app? I have a 'webapp' that consists basically of making Linux command line calls; let's admit it runs the 'uptime' command and returns the output.

My app is currently built using CodeIgniter; it works fine, but i'd like to use the powerful features of Drupal that are built-in like users handling, views, imagecache etc.

My main concept is having a 'button' on which user clicks and then it runs the selected task (asynchronously, AJAX) and then shows the result (with jQuery).

I know of 'triggers' but I can't really think of having them 'do' some action once a 'button' (a link) is pressed, not a 'on node creation do ...'.

I just wonder if anyone has done something similar, and how.

Both codeigniter and drupal are php frameworks. Can you elaborate more on what exactly you are looking for? Drupal is capable of doing everything a php can do. Also Drupal 7 has built in ajax support for forms. With additional modules like ctools, you can extend ajax functionality to any DOM elements.

There is Rules module that is more powerful and extended version of triggers. Its the GUI version of if-else-then php statements.


how to overwrite omega 960 grid margin? What is the correct way to overwrite the Omega theme stylesheet, so that the margin of .grid-1 is 0 instead of 10px?

I tried to specify this style:

.grid-1 {
  margin-left: 0;
  margin-right: 0;
}

in two stylesheets:
/sites/all/themes/mytheme/css/mytheme-alpha-default-normal.css -> this one is not loaded at all

/sites/all/themes/mytheme/css/global.css -> this one is overwritten by alpha-default-normal-12.css

The alpha-default-normal-12.css is always at the top of all loaded stylesheets, so it looks like it can't be overwritten. And it contains the styles for all .grid-x margins.

So, how to specify my own margin for a grid?

The best explanation of how to do a custom grid in Omega I have found is in the Omega documentation wiki: Creating and Setting up a Custom Grid for Omega 3.x. As the Omega documentation matures, I hope this will move into the main documentation.

The basic idea is below (but see the link above for more details):

Copy the appropriate grids entries from alpha.info into mytheme.info. There will be no grids entries initially in your mytheme.info if you have created a subtheme in the normal way. You will be copying various grids[alpha_default] entries. Then edit those entries to be grids[mytheme_default].
Generate a new CSS grid file at http://grids.heroku.com/ or http://www.spry-soft.com/grids/. Just use this as a model for the next step, as it does not correspond exactly to the way Omega CSS grid files are written.  The class naming conventions are a little different ("_" vs "-", for instance.
Copy the css and png files you need from sites/all/themes/omega/alpha/css/grid/alpha_default/{normal,wide,narrow,..}/alpha-default-*-*.{css,png}. to sites/all/themes/mythemes/css/grid/mytheme_default/{normal,wide,narrow,..}/mytheme-default-*-*.{css,png}. You will not need all the files unless you are planning to provide a complete set of narrow, normal, and wide 12 and 16-column grids. Just put in the ones you need.
If you are changing the default number of columns from 12, don't forget to edit the number-of-column defaults for all the different regions given further down in mytheme.info. Otherwise your pages will look wrong because they are using the original default settings.
Note you must also rename the mytheme/css/mytheme-alpha-default.css and mytheme/css/mytheme-alpha-default-{narrow,normal,wide}.css files to mytheme/css/mytheme-mytheme-default*.css. This is because you have changed the alpha-default grids name to mytheme-default.

I did all this recently for a design I was given that was 960px wide with no left and right margins. I set up a 60px by 16-column 960px grid.

The Omega Tools module has an incomplete wizard for setting up your own custom grid. Unfortunately, it does very little of the above as of this writing.


Can't move blocks in Drupal 7 I currently have a site that has quite a lot of blocks (about 120 in 1 region and many others in other regions).

Recently the Block admin page stopped working for me. I can't add any blocks through that screen, however when I go to the block detail page, I can.

All new blocks are handed the weight 0, and I cant change that (not by drag and drop, neither by manually entering the weight).

Anyone who know how I can fix this? Is it because there are too many blocks?

120 blocks in one regions seems to be excessive, you may want to attempt to consolidate them into a custom block and use context to set those.  Also may want to look at creating multiple regions that reside in the same area


Missing argument 1 for hook_menu() I'm getting this error in my custom module.

  [warning] Missing argument 1 for signin_menu(), called in
  /public_html/includes/menu.inc on line 2813 and defined
  signin.module:2

here is my code to create hook menu call back.

function signin_menu(&$items) {
  $items = array();

  $items['signin'] = array(
    'title' => 'Sign In',
    'description' => 'Sign In Form',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('user_login'),
    'access callback' => TRUE
  );

  return $items;
}

In Drupal 6 and Drupal 7, hook_menu() implementations don't get any argument. That is the reason of the error message.
They got an argument in previous Drupal versions, but it was not passed by reference. It's probable you are getting confused between hook_menu() and hook_menu_alter(). The latter gets a $&items parameter, but the purpose of the hook is slightly different. (It's altering routes defined from other modules, rather than defining new routes.)

As side note, I would rather use the following code.

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

  $items['signin'] = array(
    'title' => 'Sign in',
    'description' => 'Sign in form',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('user_login'),
    'access callback' => 'user_is_anonymous',
  );

  return $items;
}

The login form should be visible only to anonymous users. Logged in users should not see it, since they already logged in, but the 'access callback' => TRUE line is making it accessible to every user, contrary to what Drupal (correctly) does.


Getting the token tree to appear contextually I'm writing my own file formatter which is supposed to be Token-compatible. As it will be also used on taxonomy term pages, it should accept taxonomy term token. What am I doing wrong in hook_field_formatter_settings_form by saying:

'#token_types' => array('node', 'taxonomy_term')

so that I don't get term-related tokens at all? Cleared cache many a time.
Preferably, I would like the tokens to appear contextually: taxonomy term - when managing display of taxonomy term page, node - when managing display of a node page. Can this be done?

The surpising answer was:
'#token_types' => array('node', 'term')
Thanks to davereid!


Drupal 7 views contextual filter (taxonomy: summary display), displaying a readable term-name instead of term-id Within my view, I'm using a contextual filter—with a default "summary output"—to filter my results by taxonomy term.

The problem is that the summary-result is grouped by a listing of taxonomy term-id's (including a node count) and not human readable term-id names.

1 (21)
2 (16)
etc.

Is it possible to change (or hook) the view output of the summary, by not listing its term-id's, but the term-id-name?

Term name A (21)
Term name B (16)

(It doesn't bother for me if the actual request URL stays the same.)

My goal is to create a more readable output-format of my taxonomy-term summary, which an end user can understand.

Set your view to fields and expose the field that contains the associated taxonomy term.
Set your contextual filter to filter for a taxonomy term and select to include a validator.
Set the validator to taxonomy term and check the box for your vocabulary.
Select the option for filter value type as ' Term name converted to Term ID.
Save the filter and go to the preview box.  If you enter the text name of your term, you should see the desired content.

If you are passing the information from the URl you may have to select the 'Transform dashes in URL to spaces in term name filter values' checkbox as well since the machine name uses dashes


remove description in views exposed filter Is it possible to remove the description of views exposed filter widgets in other way as css display:none?

I tried to unset $widget->description, but without any success.

it can be done either via theme or custom module:

function MODULE_OR_THEME_form_alter(&$form, &$form_state, $form_id)
{
    if($form['#id'] == 'FORM_NAME')
    {
        $form['#info']['filter-FIELD_MACHINE_NAME']['label'] = '';
    }
}

use dpm($form); from the Devel Module to get the complete form name, and field names for non-content type filter criteria:

A suite of modules containing fun for module developers and themers ...

  Devel Helper functions for Drupal developers and inquisitive admins.
  This module can print a summary of all database queries for each page
  request at the bottom of each page. The summary includes how many
  times each query was executed on a page (shouldn't run same query
  multiple times), and how long each query took (short is good - use
  cache for complex queries). Also a dprint_r($array) function is
  provided, which pretty prints arrays. Useful during development.
  Similarly, a ddebug_backtrace() is offerred.

Be aware that removing the label (description) will change the layout of the filter itself, so some css might be required to fix things.


My local site directs to install.php after update from production site af drush sync Just set up drush for a site, database and site root set up in MAMP. I've updated the local directory using these drush commands:

drush rsync @alias.production @alias.local
drush sql-sync @alias.production @alias.local

The terminal doesn't display any errors and I can see in my local phpmyadmin + in the site folder that both files and database entries are synced. Still the local URL directs me to /install.php (also after running drush cc all)

I've done this several times before without difficulties. Any ideas how I should debug this behaviour to find my error?

Is settings.php there? It is not synced by default with drush rsync.

The redirect to the install page also indicates that you are missing settings.php.


JSON URL access restriction within Drupal I am using Drupanium in Drupal which generates JSON that can be assessed through a URL. The URL in turn is parsed by the app to show data.

Now the problem is that this URL can be publicly assessed by anyone too and anyone can see all the details. The app, on the other hand, shows the same data to the restrictive users.

My question is that how can I restrict anyone who opens the URL through a browser whilst also allowing the app to assess the data through the same URL?

The URL looks like this:-

http://site.com/section/allowed-users-in-the-list.json

Many Thanks.

Simple answer is - you need to move credentials check and permission check to your Drupal. If app on a person's computer can see all the data, no matter what you do that person can see all the data just as well. So, in Drupal only allow certain role access to that path, and then only populate results with the data user should see.


How do I post a node that has its created field set to the past in a test class? I am creating a test class using the framework of the core Testing module for a module that is supposed to autoexpire nodes some time after they've been created.

Nodes have two timestamp fields: changed and created.  I've tried to use the following code inside my test class (subclass of DrupalWebTestCase) to post an article that is supposed to have been created some time ago:

  // Post an article.
  $edit = array();
  $edit["title"] = $this->randomName(8);
  $edit["body[und][0][value]"] = $this->randomName(16);
  $edit['changed'] = 1397700000; // This is accepted.
  $edit['created'] = 1397700000; // This fails.
  $this->drupalPost('node/add/article', $edit, t('Save'));

The above code snippet produces the following error message when the test is run:

  Failed to set field created to 1397700000

Do anyone know how to explicitly set the created field to some specified Unix timestamp date for a node created inside a test class?

When you access node create form using admin role created value is exposed using Authored Information...

So, You can able to set created date by creating user with administrator role for testing...

Please see implementation below..

<?php

/**
 * Tests the functionality of the Simpletest example content type.
 */
class SimpletestExampleTestCase extends DrupalWebTestCase {
  protected $privileged_user;

  public static function getInfo() {
    // Note: getInfo() strings are not translated with t().
    return array(
        'name' => 'Simpletest Example',
        'description' => 'Ensure that the simpletest_example content type provided functions properly.',
        'group' => 'Examples',
    );
  }
  public function setUp() {
    // Enable any modules required for the test. This should be an array of
    // module names.
    parent::setUp(array('simpletest_example'));
    // Create and log in our privileged user.
    $user = $this->drupalCreateAdminUser();
    $this->drupalLogin($user);
  }

  public function drupalCreateAdminUser(array $permissions = array()) {
    $roles = user_roles();
    $index = array_search('administrator', $roles);
    $user = $this->drupalCreateUser($permissions);
    $user->roles[$index] = 'administrator';
    return user_save($user);
  }

  /**
   * Tests creation of a Simpletest example node.
   */
  public function testSimpleTestExampleCreate() {
    // Create node to edit.
    $edit = array();
    $edit['title'] = $this->randomName(8);
    $edit["body[und][0][value]"] = $this->randomName(16);
    $edit["date"] = "2012-04-19 22:54:38 +0530";
    $this->drupalPost('node/add/article', $edit, t('Save'));
    $this->assertText(t('Simpletest Example Node Type @title has been created.', array('@title' => $edit['title'])));
  }
}

Here is the output


add facebook,twitter links to node page My requirement is that in my custom content type page, I need to add fields that link to facebook and twitter. This is easily do-able as two textboxes which contain the hyperlinks to the two site urls. However the way I want it is that, if there is a facebook URL added, in the display it should show a facebook icon clicking on which will take the user to the facebook URL, same with twitter. (It is not for sharing my page content in facebook, but for redirecting the user to facebook link provided - same with twitter)

I would like these two to be two standard fields in the content type so that added links to these two will trigger this behaviour. If the textboxes are empty, the icons will not show up.

Any pointers on how this can be achieved? I looked at the various social share modules in drupal, but most of them are for sharing/tweeting the page inside which they are added.

I appreciate any help...

You can use Link module to create facebook or twitter url field for your content type.

  The link module can be count to the top 50 modules in Drupal
  installations and provides a standard custom content field for links.
  With this module links can be added easily to any content types and
  profiles and include advanced validating and different ways of storing
  internal or external links and URLs. It also supports additional link
  text title, site wide tokens for titles and title attributes, target
  attributes, css class attribution, static repeating values, input
  conversion, and many more.

For facebook or twitter icon, you need to manage this through css or need to add extra field for icon and display node.tpl.php if there is value for the link field.


How to check if field exists in an entity? In entity node, I want to check if 'abc' field exists or not. If exists, I will get its value by $value->get('abc').

But the content type where this field doesn't exists, gives error:

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

How to check if field exists in an entity?

You can use the method hasField():

$entity->hasField('abc')


Sorting a new column on task list on open atrium Hey I have added two new column's to a task list. One is a Due Date (Date chosen by calendar) and the second is number of days out (integers). The other column's that are added by default are able to be sorted, however the two new columns only have a black title.

Is there a way to add the ability to sort these new columns?

I figured it out.

Go to adminstration/structure/views/
Click Edit for Open Atrium Worktracker
In Filter Criteria click add, then select column of choice
Click the "Expose this filter to visitors, to allow them to change it"


AJAXifying content and pagination problems I am using the Ajax links API module that allows to load a node inside a
 tag by using Add page.

However, I have a problem: If I use a pager, and I click on the link to see another page, I will be redirected to that page, instead of loading it inside the
 tag.

I solved partially by using the Views Infinite Scroll module, but if I have several
 tags, the module doesn't load the correct view in the correct
.

It seems I cannot use the pagination because the URL is not re-written to accommodate to the container, and it is not scrolling because this limitation.

Is there some way of creating simple AJAX calls loading content in different
 tags on the same page, and with pagination (or load more button, infinite scrolling, etc.)?

Try this below solution with views pager ajax enable.

jQuery 1.7+ Version

function runthiscode() {
  $(".pager a").each(function(){
    $(".pager a").addClass("ajax-link");
    $(".pager a").attr('rel', '#content')
  });
}

$(document ).ready(function() {
  runthiscode();
});

$(document ).ajaxComplete(function() {
  runthiscode();
});


How to embed a Rules Link in a View in order to trigger a Rules link to run? What is the general process to embed a Rules Link in a View in order to trigger a Rules link to run?

I have used the Rules Link module to create a Rules Link embedded in a View (it's a View that combines all the details of a User).

I want the Rules Link to trigger a Rule which (when the reading user clicks " More Content From Author") will trigger the Rule to show a list of their latest postings in a HTML format.The paths work alright, it just doesn't seem to trigger the Rules Link to run the View.

If I add say a generic link in the Rewrite Result link path (say http://www.google.com), it works fine and finds the target. But my Rules Link URL "More-Content-by-Author" throws a 404 even though the link is set correctly.

I've got most things working, checked all the Permissions and set the "Execute Rules Link" permission in the said View, but still get a 404 error.

I have not added any variables (do I need to?).

After 6 hours, and I'm stumped now. Any suggestions?

Note: All my other Rules links work fine.

These are 2 modules that can trigger events based on the 'current URL being viewed' (quotes are from their project pages):

Rules URL Argument:

  ... provides two rules conditions based on URL arguments:

  check if a URL argument is present
  compare the value of and URL argument

  It also provides an action that makes the value of an URL argument available as new variable to Rules.

Path Rules:

  ... implements Rules conditions for checking the URL against a given string for triggering actions.

You can also use the Rules Link module to generate a custom link that can trigger a rule. But that requires the link to be clicked to access the page and there might be an issue that the user must be logged in.


Is a MySQL statement from an external script possible? I'm working with a PM on a Drupal project, and we're having little success finding a developer to answer (what we believe to be) a simple question.  I'm afraid I have no Drupal experience to speak of.

We've made well aware that Drupal itself doesn't use MySQL statements per se, but it is MySQL based, so - is it possible to write a SQL statement to find all users that have purchased a particular product/sku?  The SQL is to be used in an external script, outside of the website itself.

The developer is vague, at best, so I can't be any more specific than the fact that it's Drupal 7 using a standard ecommerce package.  I absolutely hate asking a broad question like this, but we're locked into this particular resource, and is insisting it will take 100+ hours to get this data to us, and I am unable to get to the DB to even try to construct the SQL.

Any advice is appreciated!  (and if you want some contract work, I'd be MORE than happy to talk).

Clarification

Again, I know this is vague, and the SQL itself would be a bonus in the answer.  The challenge is that the developer insists that Drupal doesn't use SQL statements, and therefore an external script isn't possible because it will take 100 hours to write a Drupal module to get that the result of the query.  I'm imagining something like this to determine if/when a customer last ordered product #1234.:

SELECT MAX(o.orderdate)
FROM users AS u
JOIN orders AS o on o.userid = u.userid
JOIN orderitems AS i on i.orderid = o.orderid
JOIN products AS p on o.productid = i.productid
WHERE u.email = 'somecustomer@example.com' AND o.productid=1234

With my limited Drupal experience, I know that this example isn't close to correct, but in principal, this is what we need to execute on a different server, with different software to simply get a date or a null.  If she'd give us credentials to look at the database, I could probably figure it out, but her "position" in the matter is that it can only be done with this exhaustive module development effort that she seems to want to do.

Drupal does use SQL statements to communicate with the database, however it does so through a built in abstraction layer. That said, you can write regular old SQL from any PHP script to query the information you need, as long as you have the database connection info. Personally I would build whatever functionality you're after into a custom Drupal module, and then use that to interface with whichever external service you're working with. We would need a bit more information on exactly what you're trying to achieve to provide more specific feedback however.


How to output data from module to a page. What are my options? I have some code in a module that returns some data. I want to output it in a particular place on the page: Would a block, ctools plugin for panels or a template file be the best option and how would I choose?.

If you already use Panels, and/or if you have an argument to send to your code, i'd advise Panels, definitively...

Great caching powers, multi-instances and rules of access.

But if you don't use it, don't make your site heavier with it and keep it with Blocks.

What about tpl.php ?


Edit user account how to check before update if the role check box is selected? I have a module that when my user changes the user details hook_user onupdate, pushes these details to an external database. However I would like this to only work when role X is selected, else my module will not do anything. The role will not be in the users profile as this processing is happening before I update the users account.

Drupal 6
Thanks

Update

 function checkrole_user($op, &$edit, &$account, $category = NULL){
 switch($op){
 case 'submit':

  if ($edit['roles'] == 'Staff'){
  do xyz
    }

  }

Use hook_user_presave() for any logic that you need to happen before user data is really updated, but also have access to new values:

Parameters
$edit: The array of form values submitted by the user. Assign values to this array to save changes in the database.
$account: The user object on which the operation is performed. Values assigned in this object will not be saved in the database.
$category: The active category of user information being edited.

You need to test against $edit argument.

For Drupal 6, you need hook_user.

Act on user account actions.

Act when $op == 'submit', as:

submit: Modify the account before it gets saved.

Just as with Drupal 7, you must examine

$edit: The array of form values submitted by the user.


Contextual filter for an indirect taxonomy term? I know how to display similarly tagged items of a different content type in a view block (here is a good explanation and settings picture).

I have a scenario where the term IDs aren't directly associated with both content types. The term reference field on the page content type is attached, not to the view content type itself, but to another taxonomy that is attached to the view content type (the view content type uses a taxonomy that has a field which is also used in the page content type).

How can I filter my view to items that are "mapped to" the term?

To rephrase (to see if I understood correctly):
You have a content type pointing to term reference #1, that is pointing to term reference #2. You want to show the content that points to term #1, with the context being term #2.

In that case, you'd need to create a relationship (see Using Views Contextual Filter and Relationship to display reference on referenced node)

(The following explanation would work best with entity reference instead of term reference - I don't use that field type so I'm not sure the relationship exists with it)

But in short, you'd create a relationship to "referencing entity from field_term_reference" (the field on term #1 pointing to term #2). From there you could create the "referencing entity" relationship from the field on the content type pointing to term #1. The contextual filter would be to the term ID #2 using that relationship.


How to style and add more fields to the bubble in a gmap field? I'm using gmap field, it displays only 1 bubble at the same time. If I click on bubble it displays title.

How can I customize it? I need to style it and add more fields to it.

I know how to do it using view (than I can do template for it), however in this case I have only gmap field that display itself.

I want to get this result:

Quote from the Comparison of mapping modules:

GMap is considered a legacy module.

So maybe you want to have a look at the IP Geolocation Views & Maps module. Partial quote from its project page:

Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (Google, OpenLayers or Leaflet) with any location storage module of your choice, e.g.:

Get Locations,
Geofield,
Geolocation Field
Location.

This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).

Head over to its (impressive) project page for even more information about it. That project page also includes various screenshots.


Why is my '#id' transformed into 'data-drupal-selector'? In a custom form I (try to) write, I have this element at the end:

$form['referent'] = array(
    '#id' => 'breferentdistrib',
    '#type' => 'hidden',
    '#default_value' => ($bReferentDistrib) ? "Y" : "N"
);

'breferentdistrib' being used in javascript this way:
var breferentdistrib = document.getElementById("breferentdistrib").value;

Unfortunately, I get this in the rendered HTML:
<input type="hidden" value="N" name="referent" data-drupal-selector="breferentdistrib">

No 'Id' and 'data-drupal-selector' instead.
Of course, my getElementById("breferentdistrib") is not working...
Any idea?

It's intentional as @clive says. You can select it using jQuery or CSS of the this way:

div[data-drupal-selector=your-selector-id]

If you want to use a id you can declare like this:

$form['referent']['#attributes']['id'] = 'foo';


Adding a field without the field_ prefix (Drupal 7) I am using the organic groups module which adds a field with machine name: group_audience to the user entity which can be seen at:

/config/people/accounts/fields

Somehow after install some other modules, this field disappeared.  I would like to add it back the field's machine name was simply group_audience instead of field_group_audience.

When I try and create a new field with the Drupal 7 interface builder it always prepends field_ to any field that is create.  How can I create a field that does not have the field_ prefix?

The Organic Groups module has a nifty API method for this. You just need to do a:

og_create_field(OG_AUDIENCE_FIELD, 'user', 'user');

This first checks if the field exists and creates it if it doesn't, then checks if an instance of the field has been attached to the user entity and creates it if it doesn't.

You can check this answer out to understand where and how you can run this snippet from.


Render a drupal form retrieved by drupal_get_form In Drupal 7, I have a preprocess function retrieving a form like so:

$contact = drupal_get_form('privatemsg_new');

$contact is then a fully populated form array with the right fields and elements. After that, I tried drupal_render and render, but neither one show a themed output in the node. What do I have to do to display the form?

The correct answer is to use drupal_render, which is used for render arrays like the form is. I tested this with a different form, and got the desired result so what you're doing should be right. Most likely you have a different error some where in your code causing this.

$html = drupal_render(drupal_get_form('form_id', $args)));


Error executing PHPUnit I was trying to write PHPUnit test in D8, but am blocked due to a weird issue which I am not able to track.

The module for which I am writing the test is at https://github.com/ajitdev/phpunit_d8

I have created a basic class Math with some functions https://github.com/ajitdev/phpunit_d8/blob/master/src/Math.php

<?php
namespace Drupal\phpunit_d8;
class Math {
  public function addNum($a, $b, $c) {
    return $a + $b + $c;
  }
  public function substract($a, $b) {
    return $a - $b;
  }
  public function divide($a, $b) {
    return $a / $b;
  }
}

And the test in tests/src/Unit directory https://github.com/ajitdev/phpunit_d8/blob/master/tests/src/Unit/MathTest.php

<?php
/**
 * @file
 * Contains Drupal\Tests\phpunit_d8\Unit\MathTest
 */
namespace Drupal\Tests\phpunit_d8\Unit;
use Drupal\Tests\UnitTestCase;
use Drupal\phpunit_d8\Math;
/**
 * Class MathTest
 * @package Drupal\Tests\phpunit_d8\Unit
 *
 * @group math
 */
class MathTest extends UnitTestCase {
  public function addNumTest() {
    $math = new Math();
    $this->assertEquals($math->addNum(1,2,3), 6);
  }
}

The test shows up on /admin/config/development/testing, but throws the following exception:

Uncaught PHP Exception Drupal\Core\Database\IntegrityConstraintViolationException: "SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'file' cannot be null: INSERT INTO {simpletest} (test_id, test_class, status, message, message_group, function, line, file) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7); Array
(
    [:db_insert_placeholder_0] => 14
    [:db_insert_placeholder_1] => Drupal\Tests\phpunit_d8\Unit\MathTest
    [:db_insert_placeholder_2] => fail
    [:db_insert_placeholder_3] =>
    [:db_insert_placeholder_4] => Other
    [:db_insert_placeholder_5] => Drupal\Tests\phpunit_d8\Unit\MathTest->Warning()
    [:db_insert_placeholder_6] => 0
    [:db_insert_placeholder_7] =>
)
" at /Applications/MAMP/htdocs/d8/core/lib/Drupal/Core/Database/Connection.php line 673

The issue is empty value for the file value. I am not able to trace down the issue. Any pointers would be really helpful.

I was able to resolve the issue. You just have to prefix your test with test_. Seriously! No kidding!

My test looks like the following:

<?php
/**
 * @file
 * Contains Drupal\Tests\phpunit_d8\Unit\MathTest
 */

namespace Drupal\Tests\phpunit_d8\Unit;

use Drupal\Tests\UnitTestCase;
use Drupal\phpunit_d8\Math;

/**
 * Class MathTest
 * @package Drupal\Tests\phpunit_d8\Unit
 *
 * @group math
 */
class MathTest extends UnitTestCase {
  /**
   * Very simple test to MathTest::addNum().
   */
  public function testAddNum() {
    $math = new Math();
    $this->assertEquals($math->addNum(1,2,3), 6);
  }
}

Also, pushed at https://github.com/ajitdev/phpunit_d8


View: taxonomy_term, additional display of type page I have two main content types with different vocabularies for tagging them.

I have enabled default Drupal view, "taxonomy_term".

I need two different displays: unformatted for content type A and table for content type B.

Content type A works ok, because it is using the default page display of this view.

I created another page display in this view with a filter to the proper vocabulary and node type.

Path is the same: taxonomy/term/%

But I am getting "Page not found" for taxonomy terms for content type B.

Could somebody help?

You can only have one page display on a particular path.

If you want to display two views on one url there are a number of ways you can do it.

Have one display page as you have, then have the second view as an attached view.

Or

Display the second view as a block and use context to display it on the same url


Conference registration form/site with limited places available I have to build a little conference-site with a registration-form.

The conference is 1 day and has different sessions in the morning and different sessions in the afternoon. Those sessions have limited spaces available.

Users should be able to register for the conference by the registration-form and if there are no more spaces available for a specific session, they should get a message that this is no longer available, so that they have to choose another session.

What is the best solution for this, knowing that my client wants 1 registration form for the entire day. Otherwise I was considering entity_registration. With the "1 registration form" in mind, I was considering to use webform and webform_validation or webform_rules, but there is no standard solution for the limited spaces available.

Is there a good solution for this problem?

Can someone help me?

Session = content_type.

One session = one node of type session

Every session has a field "available spaces"

Create a custom form programatically which you pass the session id in a field of type "value".
https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#val

In the validate function of the form check if the field "available spaces" for the session with that id is greater than 0, otherwise decrease it and in the submit function store the user id with this session id.

Regards.


Change base URL of multi-site install I've searched a bit for the answer to this, but all the answers seem to refer to single sites, or they just don't work (or I'm doing them wrong).

I have an out-of-the-box Bitnami image setup on Amazon EC2, and when I point my domain to the server, then visit the domain, I need to put a /drupal on the end to get to the drupal sites.

I need to figure out how to make example.com and example2.com point to the drupal installation instead of example.com/drupal and example2.com/drupal.

Is this a drupal configuration that I need to change, or an Apache configuration, or what?

This is more than likely an apache configuration.  Changing it to the RewriteBase /drupal like above will simply allow drupal to know that /drupal is where the site is installed.  You need to either look into moving the files into the original directory that the domain is pointed to, or look into finding the apache virtual host file and point it to the /drupal folder.


Possible to require custom module dependancy on a specific dev version? Is it possible for my custom module to enforce it's dependability on a specific dev version of a particular module?

E.g. my custom module, foo is dependant on variable module 7.x-1.1+26-dev.

Here is the info.
Writing .info files (Drupal 7.x)

dependencies[] = exampleapi (1.x)

The above module requires any minor version of the module in the 1.x branch (1.0, 1.1, 1.2-beta4, etc.)

The dependencies[] property in the .info file can also optionally specify operators:

= or == equals (optional: equals is the default)
> greater than
< lesser than
>= greater than or equal to
<= lesser than or equal to
!= not equal to


How should i get corresponding field value for taxonomy filed attached? I use drupal 7. I created a content type with these fields:

one field to upload a file to private folder
a taxonomy field (for that file)

my problem: i can save one file with one taxonomy! but how should i get these data again!(is there any API here) I want to know which taxonomy was saved for a certain file(i need to check it inside my custom module).  i raised similar question here: so by following code i can get corresponding field:

$nids = db_query("SELECT nid FROM node WHERE title LIKE :title", array(':title' => '%'.$title.'%'))->fetchCol();

$nodes = node_load_multiple($nids);

foreach($nodes as $node) {

// using field_get_items here automatically loads the field in the correct language
$field_items = field_get_items('node', $node, 'field_subtitle');
$subtitle = $field_items[0]['safe_value'];
}

but it seems it dose not work taxonomy attached field.

why do i have this question: i sell some digital files and now i am developing a module for selling my files. i want to sell them this way: each file has a certain taxonomy. when my user buys that file he or she gets that taxonomy(and i will keep it in one table). once he clicks on download link i have to check whether that user has that taxonomy already or not! if he has i will let him to download it.

You can see the relationship by viewing or editing the node.

If you mean where is this data stored in the DB then if you created a field called file_type then the tid of the associated taxonomy term would be found in the field_data_field_file_type table.

The names of the taxonomy terms are stored in the taxonomy_term_data table.


How to enable a payment method as soon as an order is saved in Drupal commerce programmatically? I am trying to create a membership site using Drupal commerce. I have created a custom form that collects all the billing details of the user and the membership type and then on submit creates and saves a Drupal commerce order (products have already been created).

Now I want to activate the payment system for the order as soon the order is saved but I have not been able to do so. All of this should be happening in the backend and I do not want to redirect the user to a payment page. How do we do that?

To get it to go onto the review page you can do.

$order = commerce_order_new($uid, 'checkout_review');

When creating your order that sets the status to checkout_review.

Then you can use the following to driect yourself to the page

drupal_goto('checkout/' . $order->order_id. '/review');

As the status has been set you go to the review page. I did something similar recently and it is working well.


Remove  around form items I want to use as much as I can from http://twitter.github.com/bootstrap/base-css.html#forms for my theme, and as part of this I really want to get rid of the <div class="form-item"> that is being wrapped around each <input> element.

As far as I can tell the only way to do this is by copying the entire http://api.drupal.org/api/drupal/includes!form.inc/function/theme_form_element/7 theme_form_element() function and remove the code that produces the <div> wrapper.

Is this really the only way?

Yes. These classes are hardcoded into Drupal and are not only used for visible styling but also for the jQuery code that "animates" the forms (validation, autofill, auto focus, etc.)

HTML elements can have multiple classes. You could just add the classes to the Drupal form and then create your own theme. By creating your own theme you could not theme the default Drupal classes and instead just theme the classes from Base CSS.


Why do my breadcrumbs see double? and How can I control them? A double question? I have a taxonomy menu that invokes a Panel variant linked to a view that uses the taxonomy term.  The display works fine, but I get a breadcrumb trail that repeats the menu path twice.  I cannot find a setting in the menu, panel or view that offers control of the breadcrumbs, in fact, since this is my first time dealing with breadcrumbs, I discovered I cannot find what controls them at all.  How do I configure breadcrumbs?

I had similar problem and find out that theme I was using had breadcrumb override function in template.php which was messing with results.


view results not show for unadministrator users There is a views that it access set to permission:view published contents ,every thing seems ok but I meet strange things, The views result not show for non-administrator user,
first I think the views result node are unpublished but they are not ,another idea was check the permission view published contents but It check for all roles.
any idea about where is the problem and how can I solve it ?
    thank you

What is your view path or URL? Is this URL protected for any specific user role?

1) Is there any field permission is given?

2) Can you please select role instead of permission from access? And set specific role you want to give permission.

3) Is there any contextual filter is applied?

4) Check your views filter criteria. Remove some of the filters which you have doubt on that filter and try it.


set up social login for multiple drupal sites? I intend to set up multiple independent drupal installations, each of which could benefit from social logins. I like HybridAuth, but it requires me to set up multiple "applications" (one for Google, one for Github, one for Facebook etc) for each site.

Any thoughts on how to automate creating these "applications"? Or maybe a different solution? I've tried OneAll but the Drupal module seems quite buggy.

I don't think you're going to find a way to automate the creation of application accounts. Facebook, Google, et. al have to deal with enough spam as is, without them opening up a pandora's box of spam application accounts that would come from exposing an API that could create application accounts on their respective platforms.

HybridAuth works well if you're looking to have flexible access to each social login platform (e.g. a FB app that can request multiple user permissions to the Graph API). If you're looking for just login delegation you might find more success with one the 3rd-party social login services like the LoginRadius or the Janrain modules (there might be more, those are the only ones I've heard of).


Drush and user permissions I see that my user is a member of the apache group. I added and confirmed via the following

$ sudo usermod -a -G apache `whoami`  # add my user to apache group
$ sudo chmod -R g+w .                 # permit group members to write
$ groups `whoami`                     # confirm I'm in the apache group

However, when I attempt to run a drush update core or even drush cron

$ drush cc all

unlink(sites/default/files/css/css_71ba7c25a8d3c47c68a8e05608ae525c.css):[warning]
Permission denied file.inc:482

And the CSS cache in this situation looks like

$ ll
total 1536
drwxrwxr-x.  2 apache apache  12288 Nov 26 10:12 .
drwxrwxr-x. 11 apache apache   4096 Nov 24 20:35 ..
-rw-rw-r--   1 apache apache 162269 Nov 26 10:06 css_00d5f4d7c5c92cd4f.css
-rw-rw-r--   1 apache apache 158090 Nov 26 10:02 css_0605989692a2119d305.css
-rw-rw-r--   1 apache apache 162269 Nov 26 10:02 css_0779dcac71ee9aa8e02d9e.css

I would assume that my user account, which has sudo access, should be a group member of apache (or www-data) and that the file tree should permit group write access. Any help or points in the right direction would be much appreciated.

Arguably, a much more straightforward approach is to not muck with your user's group assignments at all and instead run drush as the web server user (ie: apache, www-data).

Use sudo:

sudo -u apache drush

or on debian/ubuntu:

sudo -u www-data drush

Create a command alias:

Then, to ensure that you always run drush like that, add an alias:

echo "alias drush='sudo -u apache drush'" >> ~/.bash_aliases

or on debian/ubuntu:

echo "alias drush='sudo -u www-data drush'" >> ~/.bash_aliases

Now when running any drush command, you'll be prompted for your password by sudo, and the command will run as the web server user. No more permissions problem reading and writing files.


If NID doesn't exist, save node? I'm using menu_get_object() to get the NID for a computed field. The problem is that on a node save, NID doesn't exist yet so the computed field produces an error. If I resave the node, everything works since now the NID exists for the computed field to refer to. How can I go about adding an IF statement that if NID doesn't exist, save the node?

$node = menu_get_object();
$assigned_uid = $node->field_agent[LANGUAGE_NONE][0]['target_id'];
$assigned_user = user_load($assigned_uid);
$percentage_split = $assigned_user->field_percentage_split[LANGUAGE_NONE][0]['value'];

$other_ins = (isset(field_get_items($entity_type, $entity, 'field_other_ins_')[0]) ? field_get_items($entity_type, $entity, 'field_other_ins_')[0]['value'] : 0);
$vb = (isset(field_get_items($entity_type, $entity, 'field_vb')[0]) ? field_get_items($entity_type, $entity, 'field_vb')[0]['value'] : 0);
$finder_s_fee = (isset(field_get_items($entity_type, $entity, 'field_finder_s_fee')[0]) ? field_get_items($entity_type, $entity, 'field_finder_s_fee')[0]['value'] : 0);
$broker_fee = (isset(field_get_items($entity_type, $entity, 'field_broker_fee')[0]) ? field_get_items($entity_type, $entity, 'field_broker_fee')[0]['value'] : 0);
$dlc_franchise_fee_hst = (isset(field_get_items($entity_type, $entity, 'field_franchise_fee_hst')[0]) ? field_get_items($entity_type, $entity, 'field_franchise_fee_hst')[0]['value'] : 0);

$value = (($other_ins + $vb + $finder_s_fee + $broker_fee) - $dlc_franchise_fee_hst ) * ($percentage_split/100);
$entity_field[0]['value'] = $value;

Try this at the top of your code:

global $node;
if (empty($node->nid)) {
  node_save($node);
}

Worked for me in D5 and D6.


Add flag counter in views Module(Search API index) I want to add flag counter of content in views field. Authenticated users can flag(bookmark) contents. I want to know how many users flaged a content, And I want to add this in views field(display the number of times a node is flagged by a certain flag by Users).

Notice; I'm using "Search API Index" in content part of views

How can I do it?

UPDATE Question after using Vicky8888 method;

I added below code in global php field of views

   <?php
   $flag = flag_get_flag('bookmarks');
   if ($flag) {
  print "Number of Flags:";
  print $flag->get_count($node->nid);
      }
    ?>

this code work in tpl.php file of content type, But It's showing "0" in views.
I got several errors in picture too.

after that I using JS code of Vicky8888.

Drupal.behaviors.your-theme = {

 attach: function (context, settings) {

 //add your available class below
    jQuery('.view-id-top_users.view-display-id-page .views-field-php .flag-link-toggle').click(function(){

        jQuery(document).ajaxComplete(function() {
         location.reload();
        });
       });
      }
       };

I cleared "your-theme" and added "adaptivetheme", and cleared classes and added
".view-content .views-field.views-field-php .field-content .flag-link-toggle".

after that I using this code in separate file and added

scripts[]=scripts/extracode.js

in adaptivetheme.info file.

I cleared cache and run cron too.
but It didn't work too.

Use these two modules drupal like and flag simultaneously

Go to /admin/structure/flags create flag ,and  configure it properly.

Go to your view add  Global: PHP field

 <?php
print flag_create_link('bookmarks',$node->nid);

 $counts = flag_get_counts('node', $node->nid);
if(isset($counts['bookmarks'])){
 echo $counts['bookmarks'] .' Likes';
 }else{
      echo"no user flaged a content";
     }

 ?>

And at last put this code in your themes js file

Drupal.behaviors.your-theme = {

 attach: function (context, settings) {

 //add your available class below
    jQuery('.view-id-top_users.view-display-id-page .views-field-php .flag-link-toggle').click(function(){

        jQuery(document).ajaxComplete(function() {
         location.reload();
        });
       });
      }
       };

To add the flag link in your content type use code:

   <?php
    global $user ,$base_url;
    if(!$user->uid) {
   $flag_link = flag_flag_link($flag, $action, $content_id);

   $flag_url = $flag_link['href'];
    if(isset($flag_link['query']['token'])) {

    $flag_url .= '?'.$flag_link['query']['token'];
}

?>

  <a href="<?php echo $base_url;?>/user/login?destination=<?php echo      current_path();?>">MY-LINK


Any solution to use two different $base_url's for drupal 7 Any solution to use two different $base_url's for drupal 7. What i need to do is when i log to my site using IP/VPN, $base_url should be xxxx.xxxx.xxxx.xxxx and without any vpn connections $base_url should be aaaa.aaaa.aaaa.aaa. Any solutions? I'm Using Drupal 7.54

Rather than trying to change the base_url manually you might be better using something like https://www.drupal.org/project/domain or Drupal's language translation system and having 2 domains setup and the content shared for both domains.

So they effectively will look and act the same but the base url for drupal will be whatever the user is currently on. Then you could use these modules inbuilt hooks if you wanted to force a user ontop a specific domain based on their IP or whatever


How to create a button on module configuration page that calls a custom php function? I am creating a custom module that has a button on the module's configuration page. When the button is clicked, a custom php function (located in the custom_module.module file) needs to run to perform some task.

How can I create a button on the custom module's configuration page that allows me to click the button to manually run the custom php function?

You should use the Drupal Form API for it.

Please, check it: https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#submit (it is about adding button).

And it: https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#submit_property (it is about run custom function).