How do I check if the current password that the user gives in the password reset form matches with the hashed password? I'm trying to reset a user password programmatically in Drupal 8 without the email link. For this the first step would be to check if the password(which is plain) that the user enters in the password reset form is matching with the hashed password of the respective user. And then save the new password.

Each time I hash the password, its giving a different value, this is because its salted. How shall I compare the password which the user enters in the form with the hashed password from the table.

This is the code that I have in my controller for checking the current password :

<?php
/**
* @file
* contains \Drupal\customer_profile\Controller\ProfileUpdateController
*/

 namespace Drupal\customer_profile\Controller;

 use Drupal\Core\Controller\ControllerBase;

 use Symfony\Component\HttpFoundation\JsonResponse;
 use Drupal\Core\Password\PhpassHashedPassword;
 use Drupal\Core\Password\PasswordInterface;

 class ProfileUpdateController extends ControllerBase {

   $user =\Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
   $ret = \Drupal\Core\Password\PasswordInterface::check('secret', $user);
   //$user->setPassword('secret');
   //$pass = $user->save();

   $response->password = $ret;
   return new JsonResponse($response);
  }
 }

After using \Drupal\Core\Password\PasswordInterface::check() method, for comparing the plain text password with the hash password, I get this fatal error :

Fatal error: Non-static method Drupal\Core\Password\PasswordInterface::check() cannot be called statically, assuming $this from incompatible context in C:\xampp\htdocs\ijarah\modules\custom\customer_profile\src\Controller\ProfileUpdateController.php on line 725

In Drupal 7 we have user_check_password to check the password with string and user_hash_password for hashing.
How can I approach the same in Drupal 8.

Please help.

The hash is different every time, that's by design, because it is salted.

If you want to change the password of a user, you don't have to hash it yourself. Just load the user, set the password and save.

$user = User::load(1);
$user->setPassword('secret');
$user->save();

For the fatal error that you mentioned before, @mradcliffe already had the answer in a comment of this (now deleted) answer:

  I think MigratePassword is overriding the default password service. You can try changing the constructor argument to be PasswordInterface instead of PhpassHashedPassword if the Drupal instance is using MigratePassword. Or disable migrate module.

Always type hint on the interface if an interface is available. Services might be switched out, like migrate is doing that for example.

To check the password, you just have to use the other method of that interface, \Drupal\Core\Password\PasswordInterface::check(). Those two methods are a direct match for user_hash_password() and user_check_password()


Direct query with Search API Solr I am new to Drupal. I'm trying to implement advanced search on my Drupal8 website. It's working perfectly with the logical operator 'OR' and 'AND' but not with 'NOT', '+', '-'.

Here is my request :

$index = \Drupal\search_api\Entity\Index::load('videos_full');
    $query = $index->query();
    $parse_mode = \Drupal::service('plugin.manager.search_api.parse_mode')
                  ->createInstance('direct');
    $query->setParseMode($parse_mode);
    $query->addCondition('search_api_language', \Drupal::languageManager()->getCurrentLanguage()->getId());
    $query->addCondition("status",5);

    $query->setFulltextFields(['field_title', 'title', 'resourcetype', 'tag', 'choreographer', 'director', 'producer', 'structure', 'contributor', 'secondaryauthor']);
    $query->keys($search);

    $query->sort('created','DESC');
    $results = $query->execute();

Thank you for your help !

Please refer to following Drupal documentation example for advanced configuration of search query:

https://www.drupal.org/docs/8/modules/search-api/developer-documentation/executing-a-search-in-code

$query->keys($search);

'+', '-' works by default in $search(searched keyword)


How to add custom price for custom line items added using commerce customizable products? I have created custom line items using "commerce customizable products" module by following the steps provided in this screencast. I want to add custom price for each added custom line item and it would be great if i could add/specify the price while creating that line item. Is there any way to do it? If not I will be glad to help to do so, All I need is proper guidance. This is a well known issue and solving it would be an awesome addition to this module.

Thank you in advance.

I havent found anything for line-items per say, but found this module that might work

https://drupal.org/project/commerce_pricing_attributes


Creating entity fields based on the fields from another entity I've been trying to create a data structure that resembles something like:

            +-----------+-----------+-----------+
            | Service 1 | Service 2 | Service x |
            +-----------+-----------+-----------+
            |  Price 1  |  Price 2  |  Price x  |
+-----------+-----------+-----------+-----------+---------------+
| Feature 1 |    Yes    |    Yes    |    Yes    | Description 1 |
+-----------+-----------+-----------+-----------+---------------+
| Feature 2 |     1     |     6     |    20     | Description 2 |
+-----------+-----------+-----------+-----------+---------------+
| Feature x |    No     |    No     |    Yes    | Description x |
+-----------+-----------+-----------+-----------+---------------+

I've created a content entity Services, which has the following fields:

Service Name
Price
Feature 1
Feature 2
Feature x

This works great, until I realise that I'm not including the descriptions of each feature.

Drawing on my knowledge of database normalisation, I intend to extrapolate the description and feature to its own content entity, Services Info. I think that would probably work just fine, with one small exception, I now need to maintain the list of features in two entities, something I'm loathed to do.

Is there any way I can get Drupal to synchronise the fields across two tables? So that if/when I add more features to the Services entity, it'll appear in the Services Info entity, waiting for me to input a description for it?

Or, if there's a better, more Drupally way to approach this problem, then please feel free to chime in!

UPDATE:

I realise that my question might not be clear enough, so I thought I'd explain what I'd do if I weren't using Drupal to make this...

I'd have the following SQL tables:

tbl_services:

SERVICE NAME (FK)
FEATURE NAME (FK)
SERVICE FEATURE VALUE

tbl_services_info:

SERVICE NAME (PK)
PRICE

tbl_services_features:

FEATURE NAME (PK)
FEATURE DESCRIPTION
FEATURE RECOMMENDED

... Now I'm looking at it, I guess I'm missing an entity..? Which if I introduced I could have them reference each other correctly?

If I were to implement it this way I'd also have the issue of not being able to REQUIRE that ALL SERVICE NAMEs have ALL SERVICE FEATURE VALUEs declared for ALL FEATURE NAMEs... Could I? Or would I just have to create a custom input form for the entities?

Sounds like you want to "listen" for the creation of entities of type Services, and upon creation, you want to programmatically create another of type Services Info. For that, I'd recommend adding the hook_ENTITY_TYPE_insert hook into your custom module. Replace hook and ENTITY_TYPE with your custom module name and entity type, of course.

The function signature will include $entity as a variable, so you can do any sort of tests you want to do on it (for example, make sure the corresponding Services Info entry hasn't already been created, to avoid a possible infinite loop if you ever decide to write the sync for both entity types).

This method will look something like:

function my_module_services_insert($entity) {

  // If desired, add code here to check for pre-existing mathing Services Info; this will depend on your implementation.
  // For example, if name is unique, run an entity query for services_info entities with a matching name.

  $new_entity_fields = [
    'name' => $entity->getName(), // This assumes you want the entry to have the same name as the Services entry; change if desired
    // Other fields as desired
  ];
  $storage = \Drupal::entityTypeManager()->getStorage('services_info'); // replace 'services_info' with your entity type
  $entity_new = $storage[$content_type]->create($new_entity_fields);
  $entity_new->save();
}

That should do the trick. Good luck!


How can I get the cid of the latest comment I saved using comment_save? This is my code to programmatically save comment:

  $comment = (object) array(
    'nid' => $loaded_node->nid,
    'cid' => 0,
    'pid' => 0,
    'uid' => $loaded_node->uid,
    'mail' => $account->mail,
    'thread' => '00/',
    'created' => $loaded_node->created,
    'changed' => $loaded_node->created,
    'is_anonymous' => 0,
    'homepage' => '',
    'status' => COMMENT_PUBLISHED,
    'subject' => $comment_body_subject,
    'language' => $node_language,
    'comment_body' => array(
      $node_language => array(
        0 => array (
          'value' => $comment_body_value,
          'format' => 'msg_filtered_html',
        )
      )
    ),
  );

  comment_submit($comment);
  comment_save($comment);

I want to get the cid of comment just saved. How can I get that?

The cid value should be in the comment object after it has been saved. So you should simply be able to use something like this:

comment_save($comment);
drupal_set_mesage("ID is " . $comment->cid);


Drush Open_BaseDir Error I keep getting the following error, although I've turned off SafeMode in my .ini file, and confirmed it's off with a PHP status page.

  The following restricted PHP modes have non-empty values:
      open_basedir. This configuration is incompatible with drush.  Please
      check your configuration settings in
      /usr/local/php-5.2.17/etc/php.ini or in your drush.ini file;

safe_mode            Off        Off
memory_limit        168M       168M
open_basedir    no value   no value

UPDATE:
I think it's worth noting that this is on MediaTemple's Grid Service (gs). It looks like the PHP CLI is actually using a different .ini file with open_basedir set. So I'm still trying to figure that part out.

My solution was to add this line to my .bash_profile

alias drush='/usr/bin/php5 -c /home/000000/etc/drush.ini ~/bin/drush/drush.php'

It turns out the CLI on MediaTemples Grid Service uses a different PHP.ini file. So that line basically tells it to find your drush.ini file to override some settings. Make sure to replace the 000000 in with your server number. Thanks to kiamlaluno and MediaTemples support folks for the help.


Attaching fields to files I have a couple of forms where I need to attach metadata fields to files (a description, and a category).

The file_entity module alone lets me specify fields, but doesn't change the form fields.

When enabling the Media module, it sort of works, but the Media module

does its work in an overlay, which is unacceptable - I need something that looks like if you enable the "description" option in the core File element
breaks the look of the site as soon as I click on the "edit" button that opens the overlay - it loads the entire Bartik CSS even if the current theme is not related or using Bartik!
is way too overcrowded - I don't need support for youtube
is a security hole because people can browse all uploaded files!

So, basically, I need some way to attach a dropdown box to the standard file upload widget, nothing more - how do I achieve this? If possible, I'd prefer something that integrates at least with file_entity, so I don't have to define the field in code.

Sounds like you are looking for something like https://www.drupal.org/project/file_entity_inline


Is there a rule condition to check if the url is the front page? Just wondering if is there a rule condition to check if the url is the front page of the site?

I dont think there is such a rule, but you can do this: add a rule for User is going to view page and in condition add PHP snippet and check for drupal_is_front_page() based on this add actions as desired.


How to read JSON data from external URL and display it in a node I want to read json data from external url and display those data in a node. After that I would like to add filters in the result using views. I have created a view using external url(query settings) and display result in a block.. But I cant add filters for that. How to add Filters for that data.. I am new to this.. Please help me..

If the data does not have to be live and can be fetched / updated every x number of minutes, then I suggest you create a task with scheduler which loads the remote data into a local database table at a specified interval (drupal_json_decode can help converting the JSON string into an array that can be inserted in the database). After you do that you would be able to adopt that table into Drupal & Views using the Data module. This would make the data available as a view with sort handlers and filters, like any other view. Otherwise, to handle live data I would suggest integrating Angular JS to retrieve the remote JSON and to filter the results. NgApp module can help you in this regard.


Cannot see user_stats module logs in drupal site I have used  User Stats Module for the purpose to find the users login count till date.
I am able to see the data in database but can't find the logs in my drupal site.

I have checked in "Reports" but can't see. Please help.

Apart from some pages available under admin/reports/ip_tracking, which are visible when the Views module is enabled, and the "Track IP addresses" option is enabled on admin/settings/user_stats, the module doesn't show those values. You need to do one of the following:

Install the Advanced Forum module
Use user_stats_get_stats() in a template file

Reference

The module's README file (Drupal 7)
The module's README file (Drupal 6)


Rules: how to display the value of variables? I use the Devel module on Drupal 7 to debug some rules of my site but I can't debug without knowing the value of variables I created.

In the case, I have a loop where I sum different values and at the end of the loop I store that in a second variable that I compare to fixed parameters.

Is there something that can show me every value of the rules variables?

In the default log I have only events but I don't know anything else...
Thanks!

Two options:

At admin/config/workflow/rules/settings, set "Show debug information" to "Always."
In the rule's actions, add the action "Show a message on the site" (under the System group, I believe). Pass it the variable(s) you want to debug.


I want to write the logs for users info, page navigation in drupal 7 I want to write the logs for users info, page navigation in drupal 7.
For example: from the time the user log in what actions he has performed, pages visited

Is there any module available? Please help.

User log in/out is always logged. Switch on the statistics core module for page view statistics. If you need more details google analytics is very handy (or Piwik if you don't trust google).


drupal 7 add element after the username input text element on login form I would like to add the domain name of my company in a simple  element right after the username login text input element. Something like this:

I already tried the instructions defined in https://drupal.org/node/350634 and this only affects the text field label or anything around the login form, but not the input fields themselves (unless I'm misunderstanding the directions). This method doesn't seem to affect how I can add an html element after the username text field but before the password text field.

I'm not certain how I should attempt this? Any direction would be wonderful.

BTW - I tried LoginToboggan to simply allow my users to use either their username or their email address, but that solution only partially works. We have LDAP integration, so for the first time the user attempts to log into our Drupal site they must use just their username (without the @companydomain.com) to allow the LDAP authentication to go through. I did not see a way to configure LoginToboggan to force the username through to the LDAP authentication.

Thanks

You need to add suffix element to username field in login form. You can do it using hook_form_alter(&$form, &$form_state, $form_id)

Implement above hook in your custom module

function YOURMODULENAME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_login_block' || $form_id == 'user_login') {
    $form['name']['#suffix'] = '@mycompany.com';
  }
}


How can I convert special characters to normal characters in an URL query string? ? and = will be used as parts in my url. In generating the url, I use

<?php echo l('node/'. $someID .'/delete?destination=chapter/'. $anotherID);?>. When I check on Firebug, the href attribute of the link is not the usual url, instead of having ?, it is being replaced with %3F and = is being replaced with %3D. How do I fix this?

To generate URL we use url() function. l() function is used to generate a text with link. See the example below:

// Generate a Text with link
echo l('Link Text', 'node/' . $nid . '/delete', array('query' => array('destination' => 'chapter/' . $cnid)));

// Generate a Link.
echo url('node/' . $nid . '/delete', array('query' => array('destination' => 'chapter/' . $cnid)));


What is the correct template filename? I created a new content type using Drupal 8 with the machine name "reviews." I thought that by duplicating the original content type template file, node.html.twig, and renaming it node--reviews.html.twig, I would be able to override the original template.
However, any new change is not reflected when I open any of my review pages. I have already cleared the cache.

What is the correct way to override the default template file?

node--reviews.html.twig is correct. In my current theme, I have node--staff.html.twig and node--video.html.twig; they work perfectly fine. It could be a cache issue or probably a spelling issue.


Targeting nodes dynamically with breadcrumbs I'm using a 'resource' content type that can be browsed, searched, or accessed via a custom module. I'm also using the Custom breadcrumbs module.

I'm wondering if anyone knows a way to target [whichever] resource profile I user happens to have been viewing (dynamically since I won't know ahead of time which profile they're coming from)...and then target it in the breadcrumbs so that on pages accessed FROM the profiles (ie. a webform to give feedback on the profile for example)...a user can click the resource profile in the breadcrumb to go BACK to the profile they were viewing.

Anyone know a good way to do this?

I feel like what you are looking to implement would require you to use hook_menu_breadcrumb_alter and then using drupal_get_destination() to give you the necessary URL parameter. The results from drupal_get_destination() will be compatible with the l() function and can be handled from the hook_menu_breadcrumb_alter().


How can I get module configuration for testing I write tests for a form in a custom module using Drupal\simpletest\WebTestBase. I want to test, if the module settings are displayed in the configuration form. But the problem is, that I can not get the saved settings:

$config = $this->config('mymodule.settings');
debug($config->get(), 'Configuration object'); // Returns an empty array

I have found, that the same problem is e.g. in the demo module described in an article  on Sitepoint, see: https://github.com/upchuk/d8-demo-modules/blob/master/demo/src/Tests/DemoTest.php#L59

  E.g. $config->get('demo.email_address') returns always ''.

The tests seem to work well, but when I add debug($config->get()), then I also receive an empty array. It means, that all the test cases use empty variables and return false positive results.

I have also tried:

debug(\Drupal::config('mymodule.settings')->get()); // Empty array
debug(\Drupal::configFactory()->getEditable('mymodule.settings')->get()); // Empty array
debug(\Drupal::config('system.site')->get()); // Correct array with site settings

The module and the form are working correctly and all the settings are stored in the database.

The tests do not care about the settings, which are saved in the database. They work with settings in config/import/mymodule.settings.yml

The file can look like this:

var1: 'Some text'
var2: 1
var3: http://example.org

More info: https://www.drupal.org/docs/8/creating-custom-modules/include-default-configuration-in-your-drupal-8-module


How to show the contents of view page from template? I'm trying to theme a view page on Drupal 7, I used views-view--name-of-page.tpl.php

So now it's blank right? I invoked some blocks on the view page and added some divs to style but I can't seem to show the contents of the view page.

I have tried

print render ($content);
print $content;
print $page;

etc.

Like what we do for node. but it's not working on views template.

Can anyone suggest me?

In view Advanced Section  Theming information click Rescan template Files for your theme.


View Table Format with a group by Is there a way to create a group by in a table views.

Here is how I would like that the group by looks like

Here is a module that does exactly the same as you want.

From Module page.

    Create a new view (eg: a list of node).
    Set format Table Rowspan for this view.
    Add some field to this view.
    Group field that has same value.
    Check option "Merge rows in group".

Click on settings and group by your results by Principal, Guest, Email Member, Non Email Member. This module will render your table in exactly the same format you want.


Why are my radio buttons not displaying? I'm working on enhancing a search form on a site I inherited. I'm trying to add a radio button set to allow the user to narrow potential search results, but I cannot for the life of me get the radio buttons to display. The label displays, but the buttons themselves do not.

Here's the function in template.php:

function ismiv3point1_search_block_form($form) {
    $form['search_block_form']['#title'] = '';
    $form['search_block_form']['#value'] = 'Search mysite.org';

    $form['submit']['#type'] = 'markup';
    $form['submit']['#value'] = '<input type="image" name="submit" value="Search the Site" src="/icons/search.png" alt="Search the Site" />';
    $form['submit']['#weight'] = 2;

    // this is the new field I'm trying to add
    $form['image_switch'] = array(
        '#type' => 'radios',
        '#title' => t('Image Switch Radios'),
        '#prefix' => '
',
        '#suffix'   => '',
        '#weight' => '3',
        '#options' => array(
            1 => t('Images'),
            2 => t('All'),
        ),
        '#default_value' => 1
    );

    return '

'.drupal_render($form).'

Sort by newest first

Sort by newest first

Sort by relevance

';
}

Here's the rendered source:

<form action="/"  accept-charset="UTF-8" method="post" id="search-block-form">

      <input type="text" maxlength="128" name="search_block_form" id="edit-search-block-form-1" size="15" value="Search mysite.org" title="Enter the terms you wish to search for." class="form-text" />

   <input type="image" name="submit" value="Search the Site" src="/icons/search.png" alt="Search the Site" />
   <input type="hidden" name="form_build_id" id="form-17ad7cfea143f9acf10cca6602a02df0" value="form-17ad7cfea143f9acf10cca6602a02df0"  />
   <input type="hidden" name="form_token" id="edit-search-block-form-form-token" value="65a199ea9da3f7a52ed4c2693012997b"  />
   <input type="hidden" name="form_id" id="edit-search-block-form" value="search_block_form"  />

    Image Switch Radios

Sort by newest first

Sort by newest first

Sort by relevance

</form>

Any ideas? Is it because the field is being added after the submit? The reason for that is because the submit is a graphic (the magnifying glass) at the end of the search box; we want the radio buttons to be positioned below that.

Form builder functions must return a form array, not a string, otherwise they won't work with drupal_get_form(). If you need to add markup before and after the form you you should use the #prefix and #suffix properties, or do it outside of the form function altogether.

Also the function signature for Drupal 6 should not contain the $form variable as an argument, but the $form_state variable instead. And you're currently setting the value (text) of the submit button to the HTML representation of a an <input> field which will never do what you want.

Try using code like this instead:

function ismiv3point1_search_block_form($form_state) {
  $form['search_block_form']['#title'] = '';
  $form['search_block_form']['#value'] = 'Search mysite.org';

  $form['submit']['#type'] = 'markup';
  $form['submit']['#value'] = 'Search the Site';
  $form['submit']['#weight'] = 2;

  // this is the new field I'm trying to add
  $form['image_switch'] = array(
      '#type' => 'radios',
      '#title' => t('Image Switch Radios'),
      '#prefix' => '
',
      '#suffix'   => '',
      '#weight' => '3',
      '#options' => array(
          1 => t('Images'),
          2 => t('All'),
      ),
      '#default_value' => 1
  );

  $form['#prefix'] = '
';
  $form['#suffix'] = '

Sort by newest first

Sort by newest first

Sort by relevance

';

  return $form;
}

EDIT

Just a bit of extra info on how to do this with a form alter hook:

function ismiv3point1_form_search_form_alter(&$form, &$form_state, $form_id) {
  $form['image_switch'] = array(
    '#type' => 'radios',
    '#title' => t('Image Switch Radios'),
    '#prefix' => '
',
    '#suffix'   => '',
    '#weight' => '3',
    '#options' => array(
        1 => t('Images'),
        2 => t('All'),
    ),
    '#default_value' => 1
  );
}


Store information from hook_form_alter to be used in later hook_user_update? I have a hook_form_user_profile_form_alter (hook_form_FORM_ID_alter) where I'm capturing user information that was changed when a user updates their profile.

I want some of that information available in hook_user_update, which is called after the form alter - maybe no more than 6 fields.

Is there a way to hold some of the information from the hook_form so it is available when I get to hook_user_update? I'm looking for a server side solution. In Java I could use class variables or session storage. I see PHP has session storage. Is that the best practice or is there's a Drupal specific solution or a better PHP usage pattern?

Since someone will probably ask why I don't perform what I need done in hook_form_user_profile_form_alter:
That function gets called twice (which can be problematic) and I cannot be sure that the transaction is complete until I get to hook_user_update. So I feel that hook_user_update is a much better place to execute what I need to execute, because I'm synchronizing information with another application. I need to be sure the transaction went through before I perform the call to the other app.

As far as I'm aware, all form element values entered by the user on the profile edit form are available in the hook_user_update()'s $edit argument. The only element that won't be there is the plain text password.

There is no "drupal way" to avoid this, as core handles this functionality and it's trying to stop you from accessing the plain text password.

REMOVING SUGGESTION PER @znerol. Will update later this evening


Is it possible to create a template (tpl) file for comment view mode? I created a new view mode for comments called "cool", as shown in the image below (click the image for full size):

I created comment--cool.tpl.php and added it to my theme template folder.

Based on the question about Custom tpl for view mode for all contenty type, I also need to add a pre-process to my theme. I tried:

  function MyThemeName_preprocess_comment(&$vars) {
  $vars['theme_hook_suggestions'][] = 'comment__' . $vars['view_mode'];
  }

But I get an error "Undefined index: view_mode"

Seems like comments preprocess doesn't have view_mode as an argument. So I guess it's not possible to create a tpl for comments? OR is there another way?

With take look at  Template Comment Preprocess You find out that you just need use  $vars['elements']['#view_mode'] instead of $vars['view_mode'].


How do I compare a date field with the current time in a twig template? I have a date field on a node – set to a custom date format (c which is ISO) in the Manage Display.
I have a twig template checking to see if that date field comes before today, in which is should output Past.
Outputting the fields/comparison values gets me the properly formatted dates I want to compare.
{{ content.field_closing_date.0 }}
{{ 'now'|date('c') }}

which outputs
2021-05-05T16:30:00-07:00
2021-05-14T12:01:53-07:00

My comparison is
{% if 'now'|date('c') > content.field_closing_date.0 %}
Past
{% endif %}

But it's not outputting Past. What gives?
You can see that the todays date does come after the date field.

If you feel like a preprocess function is overload and if you can afford to ignore timezones, try converting both date values to Unix timestamps to make them properly comparable. And prefer raw node values over formatted content values:
{% if ('now'|date('U') > node.field_closing_date.0.value|date('U')) %}
  Past
{% endif %}


Admin menu for client, each menu for each content type I want to create a admin interface for my client. For now, if my client wants to add an article, he needs to click Content, Add content, and select Article as content type; at the end, he can create a new node. This is not user-friendly.

I want to have Article, Photo, and Video as menu link in the Admin menu. If the user clicks on Article, it will show the list of all the articles list; I don't need to use the "type filter" to filter the content type, as users will click on the Add link in this list view directly, to add a node of each content type.

How can I achieve this?

Since you just need a few links, I would use the Shortcut module which is a Drupal 7 core module. The documentation on this is pretty good: https://drupal.org/documentation/modules/shortcut.

You can configure under user permissions whether the user can edit the menu themselves or not. You can have different shortcut menus for different users.

Out of the box, you can only have 7 shortcuts on the shortcut bar at one time. There appears to be a patch for this, but I haven't tried it yet myself: https://drupal.org/node/682000#comment-6493066

However, to display the shortcut toolbar, it appears you have to expose the Admin toolbar to that user. You can make the admin toolbar pretty minimal by just giving the tool bar and create content permissions to the user.

If you really don't want to expose the admin toolbar to this user at all, then you might want to go with a menu block that only this user sees (set under block config>Roles). Your user would need to be given a unique role for this (which other users are not given). This assumes you have the Menu, Block and Menu Block modules installed.


Adding custom classes to Views Filters (view-filters) and Content (div.view-contents) I'm using a theme that includes bootstrap. I'd like to inject class one_third into
 and two_third last to
. Is there a way to do so from any theme theme_preprocess_area?

I know I could accomplish using javascript (selecting div.view-filters and addClass()), but I think it would be most prudent to handle in perhaps the preprocessing?

Views provides a lot of .tpl files for doing just this. They are found in the /theme folder of the views module folder. The one you want is views-view.tpl.php

Simply copy views-view.tpl.php into your theme's templates folder and edit ~ line 43 to include your bootstrap classes and whatever other markup you require ;)


How to make a module prerequisite in drupal How should i make a module that is prerequisite for an existing module.

For example:

Step 1 : There is comment module in core itself.

Step 2 : In my module i am doing some form alter which affects comment module. Consider my module name as  comment_test.

Step 3 : While enabling comment module my custom module that is comment_test should be as required module.

Step 4 : How can this be done?

Thanks in advance...

using below format in .info file of the module.

dependencies[] = D1
dependencies[] = D2

I the above lines, D1 & D2 represent the names of the modules you module depend on.


How to show drupal error messages in batch scripts? I'm using a few scripts for one-time data checking and scrubbing. They load the Drupal bootstrap but not the UI:

require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

How can I display any error messages that they generate?

You should really be using Drush.  It handles bootstrapping and reporting error messages, etc.  In particular, the command drush php-script will be useful to you.

$ cd /path/to/drupal/sites/mysite
$ drush php-script /path/myscript.php

Write your script as usual.  Drush will bootstrap for you, so you may simply start calling Drupal APIs.  Any error messages generated will be printed to stderr.  See the readme file, http://drush.org, and  drush topic for all sorts of advice on getting started.


How to trace an Error: PDOException: SQLSTATE[23000]: I'm trying to trace this error which is shown when I save a new basic page node.

It seems to me that I am trying to save a duplicated title value in field_data_title_field, but it doesn't make any sense to me. I found this question PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1532856' for key 'PRIMARY': INSERT INTO {watchdog} but it was related to dblog table (Watchdog module). Mine is related to: modules/field/modules/field_sql_storage/field_sql_storage.module

Drupal core is updated to last version.

How can I trace and fix this?

ERROR:

  PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'node-4294967295-0-0-und' for key 'PRIMARY': INSERT INTO {field_data_title_field} (entity_type, entity_id, revision_id, bundle, delta, language, title_field_value, title_field_format) 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] => node [:db_insert_placeholder_1] => 4294967295 [:db_insert_placeholder_2] => 3187 [:db_insert_placeholder_3] => page [:db_insert_placeholder_4] => 0 [:db_insert_placeholder_5] => und [:db_insert_placeholder_6] => My node title [:db_insert_placeholder_7] => ) enfield_sql_storage_field_storage_write() (line 514 of /home/examplesite/www/modules/field/modules/field_sql_storage/field_sql_storage.module )

The composite primary key for field tables is entity_type,entity_id,deleted,delta,language. The error itself lists the key:

'node-4294967295-0-0-und'

You can confirm that there is a pre-existing field in the table by querying your database with a search on those values.

Also of note, your node id is at 4294967295. This is the upper limit of 32-bit unsigned integers; anything higher than that is going to start causing problems with your SQL storage.


Can't import from XML using Feeds importer and XPath parser I'm trying to import book objects from the XML file you can see XML file Here. I will tell step by step what I did to achieve this, so it would be easier to help me.

Created a Book content type with all the corresponding fields from the XML file
Installed Feeds importer and XPath parser modules with their dependant modules
Created a Feed importer called bookImport
In the Basic settings I attached it to Book content type
The fetcher is a default one - HTTP
For parser I chose XPath XML parser
Processor is Node. As I want to create new Nodes for every single book
In the Node processor settings I chose Book bundle and everything else is left as it was by default.
In the mapping I mapped all the xpathparser:* source values to target ones from Book content type.

When trying to import, in the XPath Parser Settings for context I put book and leave everything (all the other book fields empty), I turn on my error messages and after clicking Import I get these two lines:

context :
There are no new nodes.

I've been trying to solve this for 2 days now without any luck, any help would be highly appreciated and I hope my post is informative enough, if there is something missing, please let me know and I will update!

Solved this on my own, the problem was that in context I had to write //book, instead of book. Stupid mistake which caused me headache for 2 days. I hope this will be helpful for people who will face the same problem.


In Drupal Commerce, what is the difference from a product, product type, and product display? I'm coming from ubercart and want to transition to drupal 7 commerce 1.x, but its very confusing on how this all relates to one another. First off I just want to clarify, what the difference from a product, product type, and product display?

I read a few online tutorials, but its not very clear on distinguishing how each one relates and how it is setup.

Okay after reading a bit and messing around with the commerce module, its a bit more clear now. Don't even try to just read the documentation without clicking around and testing Drupal commerce as its very confusing if your not messing with the site. It's best to install just the Drupal Commerce module and not the Commerce Kickstart module so you can get a CORE knowledge of how it works from the ground up. Kickstart has too many other modules installed and will make it confusing of how thins are built.

Hopefully I can explain it a bit easier than the documentation. When starting out with Drupal Commerce and your coming from Ubercart, its good to know that there are no Options or Attributes as a configuration option as you have it in Ubercart. The idea of how Drupal Commerce was constructed was that every type of options within an attribute is its own product. (This is something I had to get my brain used to.)

Let's say I am selling T-shirts and I have SIZE and COLOR as an attribute. Now I have 5 difference sizes (X-Small, Small, Medium, Large, X-Large) and have 5 different COLORS (Red, Blue, White, Black, Green). YES, I know its a crap load of products to deal with compared to Ubercart which would have been only ONE and you just set attributes and options for it!

In Commerce, a product page is constructed in this way:

Product Type > Product > Product Display

Product Type
You can think of Product Type as you creating a new Content Type under structure, but it just has its own section for it. Which is why this is called an Entity! Structure > Content Type is a type of Entity. And Product Type is just another Entity. Hence the different page to set this up.

Product
You create a product out of a product type. Same as if you create a new content type called "Basic Page", you would create a new page when you click on basic page under structre.

Product Display
Now here's the tricky part to wrap your head around. When you create a product, there is no page where you can view it as its not a "DISPLAY". Its just a record in your site saying you have this product, but you cant view it. Now you create "PRODUCT DISPLAYS" via the regular structure menu as if you were creating a new content type. You can call it whatever. You know what, just use the default "Basic Page" and add a new field to it. That new field will have to be a type of "Product Reference", which you select under the type option when you add new fields. Once you add a product reference option. Your BASIC PAGE is now considered a "PRODUCT DISPLAY".  When you first install commerce without anything else, you will have to make your own product display, so don't expect to see a product display option under structure. Once that is done, create a new BASIC PAGE and add a few products you already made and it will pop up with the add to cart forms and stuff.

I hope this was clear, if not let me know and I'll try to be a bit more precise.


Organic Groups Permissions and Site-wide Roles I currently have a Drupal 6 site set up using Organic Groups and OG User Roles. This is important because we have mainly public groups, however some pages in the groups are restricted by a user's role, such as staff or student. In this way, a page can be private to its group members, and additionally visible by those users who have the staff or student role.

OG User Roles has not been upgraded to Drupal 7 and we are attempting to find a replacement. OG 7 does provide integrated roles for groups, BUT it does not include the ability to set viewership based on these roles. Public / Private is too black and white, we need much more granular settings for our editors.

I have looked at Content Access, but we have about 20 roles on our site, and our editors would be overwhelmed by the options. Additionally, Content Access does not provide a way to prevent an editor from assigning "edit" or "delete" permissions, which is an issue for us.

We only want editors to be able to say "For this group page, this site-wide role can see this page." Very similar to the existent OG audience selection, but including site-wide rules as OG User Roles does currently in D6.

Is there any solution for this in D7 with Organic Groups?

In order to solve this we had to use an additional content access module, and we picked Simple Access.

Using the OG user roles built into OG for D7 we got our editing permissions under control, but that did not allow us to control viewership permissions for the content at all.

By utilizing Simple Access in addition to OG, we have the solution that we needed.


How do I display a "Thank You" message after submitting a Webform 3.x form? I recently upgraded a Drupal 5 site to Drupal 6.  This upgrade also entailed upgrading the Webform module from version 2 to version 3.

I have a very simple webform setup that asks for a name and email address to sign up for a newsletter.  Before upgrading, the webform administration area had a textarea labeled Confirmation message or redirect URL, but I no longer see this option.

When the form is submitted, it just reloads the form with empty values.  The form is submitted properly, but I would like to be able to present a "Thank You" message instead of reloading the form page.

From the webform node, click the Webform tab, then the Form Settings sub-tab. There should be a large textarea labeled "Confirmation message".

If you are on node 1, the URL would be example.com/node/1/webform/configure.


Drush How to sync between local and server? I always deploy drupal locally, install need modules, and then write the theme. Then I upload the local site to my server.

But when something needs a update or change, I will modify the local site, and I re-upload the local site to server.

It's very troublesome.

I want to:

  sync my local site to my production site, so that when my local site is changed, the updates are uploaded to the server automatically.

It seems that Drush can sync between local and server, and might be useful for this issue, but I can't find useful post explaining how to do this.

Thanks

what your looking to learn to do is called drush aliases.

You can read this: https://drupal.org/node/670460

And here are some examples of it: http://deeson-online.co.uk/labs/drupal-drush-aliases-and-how-use-them

I would suggest you to use a virtualbox installation of drupal to test this out so you can get familiar with it first by setting this up: https://drupal.org/project/quickstart

My main local environment for developing drupal sites resides in the virtualbox quickstart. From there I do my tests and you can sync to your live environments using drush aliases. You can test syncing just using the local sites first.


How to create a pie chart of user points and taxonomy terms? I have 3 terms in Taxonomy > User Points: Articles, Comments and Favorites. I created some rules to grant user points of one of these categories, based upon the users' actions. So far, everything works fine.

Now, I'd like to create a pie chart of the user points per category for the profile pages. For example, such a pie chart might look like this:

How can I achieve this?

Edit: I'm working with User Points 7.x-1.0.

There are a number of chart modules for drupal.
If you used the charts module, it has views integration, so assuming you are using the user points module, and that user points has view integration, you should be able to create a view with items grouped by term and display as a chart.
Update
Replicated your environment as above, updated the userpoints module to 7.x-1.x (dev), installed charts module (and included google charts module to test), constructed view of userpoints with contextual filter on user and the chart  works perfectly! Thanks for asking the question, I have suddenly thought of loads of places I could use similar graphic incentives.
Here is the exported view - in this example it uses taxonomy terms article, page and comments:
$view = new view();
$view->name = 'points_chart_userpoints';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'userpoints';
$view->human_name = 'points_chart_userpoints';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'userpoints table block';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'chart';
$handler->display->display_options['style_options']['library'] = '';
$handler->display->display_options['style_options']['label_field'] = 'tid';
$handler->display->display_options['style_options']['data_fields'] = array(
  'points' => 'points',
  'tid' => 'tid',
);
$handler->display->display_options['style_options']['field_colors'] = array(
  'points' => '#2f7ed8',
  'tid' => '#0d233a',
);
$handler->display->display_options['style_options']['width'] = '';
$handler->display->display_options['style_options']['height'] = '';
$handler->display->display_options['style_options']['xaxis_labels_rotation'] = '0';
$handler->display->display_options['style_options']['yaxis_labels_rotation'] = '0';
/* No results behavior: Global: Text area */
$handler->display->display_options['empty']['area']['id'] = 'area';
$handler->display->display_options['empty']['area']['table'] = 'views';
$handler->display->display_options['empty']['area']['field'] = 'area';
$handler->display->display_options['empty']['area']['label'] = 'no points';
$handler->display->display_options['empty']['area']['empty'] = TRUE;
$handler->display->display_options['empty']['area']['content'] = 'no points found';
$handler->display->display_options['empty']['area']['format'] = 'filtered_html';
/* Relationship: Userpoints: User */
$handler->display->display_options['relationships']['uid']['id'] = 'uid';
$handler->display->display_options['relationships']['uid']['table'] = 'userpoints';
$handler->display->display_options['relationships']['uid']['field'] = 'uid';
/* Field: Userpoints: Current points in category */
$handler->display->display_options['fields']['points']['id'] = 'points';
$handler->display->display_options['fields']['points']['table'] = 'userpoints';
$handler->display->display_options['fields']['points']['field'] = 'points';
/* Field: Userpoints: Points category */
$handler->display->display_options['fields']['tid']['id'] = 'tid';
$handler->display->display_options['fields']['tid']['table'] = 'userpoints';
$handler->display->display_options['fields']['tid']['field'] = 'tid';
/* Contextual filter: User: Uid */
$handler->display->display_options['arguments']['uid']['id'] = 'uid';
$handler->display->display_options['arguments']['uid']['table'] = 'users';
$handler->display->display_options['arguments']['uid']['field'] = 'uid';
$handler->display->display_options['arguments']['uid']['relationship'] = 'uid';
$handler->display->display_options['arguments']['uid']['default_action'] = 'default';
$handler->display->display_options['arguments']['uid']['default_argument_type'] = 'user';
$handler->display->display_options['arguments']['uid']['default_argument_options']['user'] = FALSE;
$handler->display->display_options['arguments']['uid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['uid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['uid']['summary_options']['items_per_page'] = '25';

/* Display: Chart (block) */
$handler = $view->new_display('block', 'Chart (block)', 'block');

/* Display: Table (block) */
$handler = $view->new_display('block', 'Table (block)', 'block_1');
$handler->display->display_options['defaults']['style_plugin'] = FALSE;
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'points' => 'points',
  'tid' => 'tid',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'points' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'tid' => array(
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
$handler->display->display_options['defaults']['style_options'] = FALSE;
$handler->display->display_options['defaults']['row_plugin'] = FALSE;
$handler->display->display_options['defaults']['row_options'] = FALSE;

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page_1');
$handler->display->display_options['path'] = 'userpoints/chart';


How to insert html tags to a node content? I am wondering is it possible to insert a plain full html tags to a node content? Currently I have a node content type having a list of fields, but if I add some html tags in tpl.php file for that node, the html tags are actually outside the main content of the node field (but I want to put new-added html tags inside that.)

Can anyone brief me what is the best way of doing that?

Regards!

To use html tags in the Body field of a Basic page content type (for example) you need to select "Full HTML" or "Filtered HTML" in the "Text format" dropdown menu below the input text box (see image). As far as I know, only fields of type "Long text and summary" and "Long text" allow you to select Full or Filtered HTML.

To configure text formats and permissions go to Configuration -> Content authoring -> Text formats (www.example.com/admin/config/content/formats).

For more information see Text filters and Input Formats.


How to find orphaned files and images which are not linked from any css stylesheet or from any node? Is there a way to list all unused files which reside inside public file system and inside a theme directory and list them, or maybe even have an option to delete them automatically?

I mean files which are currently not linked from any css stylesheet or from any node.

You can find orphaned files by running the following MySQL query:

SELECT fm.*
FROM file_managed AS fm
LEFT OUTER JOIN file_usage AS fu ON (fm.fid = fu.fid)
LEFT OUTER JOIN node AS n ON (fu.id = n.nid)
WHERE fu.type = 'node' AND n.nid IS NULL

This returns all files which have no associated node. I'm not sure if it's safe to delete the returned rows and files, probably also depends on your module setup. Only use at your own risk!

Source: http://drupal.org/node/733258#comment-5582764


Programmatically created nodes are not appearing under table 'nodes' I have written a PHP script for the programmatic creation of nodes:

<?php

define('DRUPAL_ROOT', getcwd());
$_SERVER['REMOTE_ADDR'] = "localhost";
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

// Get a list of Office ID's
$office_ids = db_query('SELECT OFFICE_ID FROM sage.OFFICE');

// Loop through and edit each user
foreach($office_ids as $office) {

  // Create a new node object
  $node = new stdClass();

  // Set our new node content type
  $node->type = "office";

  // Set the node title
  $node->title = "Office " . $office->office_id;

  // Set the language
  $node->language = LANGUAGE_NONE;

  // Set the UID of the author of the node; or use $node->name
  $node->uid = 1;

  // Set node details
  $node->body[$node->language][0]['value'] = $bodytext;
  $node->body[$node->language][0]['summary'] = text_summary($bodytext);
  $node->body[$node->language][0]['format'] = 'filtered_html';

  $path = 'office-' . $office->office_id;
  $node->path = array('alias' => $path);

  if($node = node_submit($node)) {
    node_save($node);
    echo "Node with nid" . $node->nid . " saved!\n";
  }
}

When I run the above script, I can see my NIDs incrementing (and I assume this means my nodes are created), however when I go and check in the 'nodes' table in the database, I see nothing added.

Does anything know what could be wrong?

The $node object you pass to node_save() wouldn't get it's nid member populated unless the node has been successfully saved to the node table in the database.

The auto-increment ID actually comes from the database table so if the $node object has a nid, you can pretty much guarantee the record has been successfully inserted into the table.

Make sure that the software you're using to view the table doesn't have some sort of paging turned on, meaning that only the first x number of records are actually showing in your results. Most MySQL UI software (PHPMyAdmin, Navicat, etc.) limit the number of results you see in a table by default; if you want to see more you need to change the setting.

If you want to do a quick check run the following query on your database:

SELECT MAX(nid) FROM node

Note down that number, then run your code again. Finally run the above query one more time. If the nid you get the second time around is greater than the one from the first time round, you know the record has definitely been added to the database.


Different Status Message templates for different pages I have been trying to use different status message templates. But I do not know if we can use different status message templates for different pages.  Is it possible?

Right now, I am using

status-messages.html.twig

Any help would highly be appreciated. Thanks!

Here is an example adding routename to status messages' templates suggestions (you may also add some parameters or whatever you need)

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function HOOK_theme_suggestions_status_messages_alter(array &$suggestions, array $variables) {
  $route = \Drupal::routeMatch();
  $suggestions[] = 'status_messages__'.str_replace('.','_', $route->getRouteName());
}

This way you can have status-messages--[routename].html.twig as a template, and if this file not exists, have a fallback to status-messages.html.twig


Translate path controller I have the following path defined in my routing.yml:
path: '/department/{department_node}/qualifications/{qualification_id}'

I need to translate that route into other languages, for example into Spanish:
path: '/departamento/{department_node}/titulaciones/{qualification_id}'

department_node would be a "department" node
qualification_id would be a dynamic id from a web service
So the result should be:
en: /department/department-title/qualifications/99
es: /departamento/department-title/titulaciones/99

As the qualification_id is a dynamic value, I can't create an alias, as I would have many after a while and they would be out of date. Does anyone know any method of translating the routes in this case?

Routes != URLs, you can't translate a route, you only can translate URL aliases.
One route has only one path, which - through optional wildcards - could match more than one URL. Because no single part in your desired URLs is stable, you can't do this with one route. (And AFAIK the first /part/ of a route path must be constant too in Drupal, it cannot start with a wildcard.)
An URL alias is an optional, separate entity that matches an arbitrary URL to an existing route.
You either have to dynamically create/update URL aliases, or add new route only for the spanish translation. But it is allowed to reuse the same controller for multiple routes, so overhead would only be a single entry in a routing.yml file.


Comment form on a separate page I want to have "Add new comment" link to open in a new page. I already read Placing the comment form on a separate page, but this didn't solve my problem. When I go to /comment/reply/[nid] or /comment/reply/[nid]#comment-form, a page opens with "Add new comment" as the h1 page title. Then underneath the page title is my entire custom content type, followed by the comment form. I don't know why my content type is also displaying. In my content type, I've got "Show reply form on the same page as comments" unchecked. In the "Comment Fields" tab, I only have the fields I want on the comment form and no fields from my content type are listed. Can anyone offer any suggestions?

Thanks,
Paul

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

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

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


Handling One-to-Many relationship view? I am trying to learn Drupal, and getting stuck every hour. I wish someone could walk me through this. I am trying to create a Employee-Company relationship. I have created a Company Content Type with just Name, Address and Telephone Numbers. And a Employee with Name and an Entity Reference to Company and multi-value Term Reference to skill set.

Now in my page skill/[whatever_the_skill_may_be] - I get a list of Employee. This happens automatically. Now I want to show the Company information along with each employee, but surprisingly can't seem to do this easily. I get the Company name which can be linked, but not the address or Telephone number.

Some of the pages I searched for the answer seem to suggest creating a View for this. I am not sure if I really need to, for such a simple requirement. But even if I do so, how do I override the default view of skill/[whatever_the_skill_may_be], and also the employee/[name-of-employee] page, where I would like to show the company information?

I hope I am not asking a stupid or very obvious question. Thanking u in advance,

Its simple, follow the steps.

Create a view of employees.
In the Format section show fields instead of content
Add the fields, Employee Name, Skill, Company Name
Add a Contextual Filter, Content: Has taxonomy term ID

Provide default value as Taxonomy term Id from URL
Select Specify validaion criteria

Select the validator Taxonomy term and choose your vocabulary - Skillset
In filter value type, select Term name converted to Term ID

Add a relationship Entity Reference: Referenced Entity
Now add the fields, Phone, Address, but make sure you are selecting the relationship that you added.


Discount by time and not by date How can I achieve the discount by time on not by date functionality.
I have to provide discount on 8 March from 8AM to 8PM.

Currently, Commerce Discount doesn't support specific times in it's discount rules.

You could use PHP evaluation to make this work, though.


Get all fields for a given content type including title I'm using field_info_instances($entity,$bundle) to read through every field in a given content type in their weighted order. However, field_info_instances does not include the node title. Why not and how can I remedy it so its added to the $fields array for sorting and processing in this scenario:

<?php
function do_something($content_type){
    $fields = field_info_instances("node",$content_type);
    usort($fields,"sort_stuff");
    foreach($fields as $field_name=>$value){
        do_something($value);
    }
}

function sort_stuff($a,$b){
    return $a['widget']['weight']-$b['widget']['weight'];
}
?>

The node title is not a field handled from the field API. If you want to know if a content type has a title, you can use the following code.

$types = node_type_get_types();

if (isset($types[$content_type]) && $types[$content_type]->has_title) {
  $title = $types[$content_type]->title_label;
}

The code you are looking for is the same code used by Drupal to sort the fields (and extra fields) in admin/structure/types/manage/article/fields.

The function that handles that page is field_ui_field_overview_form().

Basing on the code of that function, I wrote the code you would need to get the list of fields, and extra fields, with their label, and weight.

  $fields = array();
  $instances = field_info_instances('node', $content_type);
  $extra_fields = field_info_extra_fields('node', $content_type, 'form');

  // Fields.
  foreach ($instances as $name => $instance) {
    $field = field_info_field($instance['field_name']);
    $fields[$instance['field_name']] = array(
      'title' => $instance['label'],
      'weight' => $instance['widget']['weight'],
    );
  }

  // Non-field elements.
  foreach ($extra_fields as $name => $extra_field) {
    $fields[$name] = array(
      'title' => $extra_field['label'],
      'weight' => $extra_field['weight'],
    );
  }

Notice that the extra fields don't contain just the title, but every extra field for which a module returned information in hook_field_extra_fields(). There are modules that add fields to the node editing form, and implement hook_field_extra_fields() to allow the users with the right permission to decide the order in which their fields appear. For example, if you have installed the Mollom module, the page I shown in the previous screenshot becomes the following one.

Notice also that it is easy to notice which fields are not implemented using the field API if you look at admin/structure/types/manage/article/fields: For those fields, the Field column doesn't contain a link. That is what happens for the fields labelled Title, and Mollom.


Why is this Drupal services RESTful API not working? I'm using the Services module on Drupal 7. I want to implement a service that allows me to submit a search term via AJAX and receive an array containing the top 5 nodes (node id and title) that loosely match the title. When connecting to http://example.com/api/ I receive this message

  Services Endpoint "search" has been setup successfully.

but when attempting to navigate to something like http://example.com/api/search/Test, I get a 404.

Later of try and try, when read from other tutorial, i make a resource with rest, soap for me is imposible in drupal, i try but without success, you can copy and page this code and modify only the custom module name and hooks.

/**
 * Implements hook_ctools_plugin_api().
 */
function core_custom_webservice_ctools_plugin_api($owner, $api) {
  if ($owner == 'services' && $api == 'services') {
    return array(
      'version' => 3,
      'file' => 'core_custom_webservice.services.inc'
    );
  }
}

function core_custom_webservice_services_resources() {
  $resources = array(
    'webservice_resources' => array(
      'operations' => array(
        'retrieve' => array(
          'help' => t('Response of webservice'),
          'file' => array('type' => 'inc', 'module' => 'core_custom_webservice', 'name' => 'core_custom_webservice.resource',),
          'callback' => '_core_custom_webservice_get_response',
          'access callback' => '_core_custom_webservice_access',
          'access arguments' => array('view'),
          'access arguments append' => TRUE,
          'args' => array(
            array(
              'name' => 'parameters',
              'type' => 'string',
              'description' => 'The parameters that define requested data',
              'source' => array('path' => '0'), // first argument in the url
              'optional' => FALSE,
            ),
          ),
        ),
      ),
    ),
  );
  return $resources;
}

/* * *************************************************************************************************
 * Access callback
 * For now only view/retrieve is implemented and if the user is logged in, he gets access
 */

function _core_custom_webservice_access($op) {
  global $user;
  $access = TRUE;

  switch ($op) {
    case 'view':
      if ($user->uid) {
        $access = TRUE;
      }
      break;
  }

  return $access;
}

function _core_custom_webservice_get_response($arg) {
  $response = 'something';
  return 'print '.$response;
}

try again in your service path and success with
http://path.come/?q=webservice_server_rest/webservice_resources/string.json


DrupalTemporaryStreamWrapper::stream_open" call failed in file_unmanaged_save_data() DrupalTemporaryStreamWrapper::stream_open call failed in file_unmanaged_save_data()

I do not identify the problem. Could anyone help me?

You can solve this by setting up temporary path i.e.

Goto :

  Home » Administration » Configuration » Media and fix temporary
  directory.

or Goto to the path & add temp url :

config/media/file-system


How to add css using the Preprocess_image function? I'm trying to preprocess my image style like this example

<img class="media-object img-rounded img-responsive"  src="http://placehold.it/350x250">

My preprocess_image function looks like so:

function bootstrap_subtheme_preprocess_image(&$variables) {
  if(isset($variables['style_name'])) {
    if($variables['style_name'] == 'logged-in') {
      $variables['attributes']['class'][] = "media-object";
      $variables['attributes']['class'][] = "img-responsive";
      $variables['attributes']['class'][] = "img-rounded";
    }
  }
}

But it is not adding the classes.

Why not?

Try this.

function mytheme_preprocess_image(&$variables) {
   if(isset($variables['style_name'])) {
    if($variables['style_name'] == 'image_style') // this is an image style used in drupal's image styles {
     $variables['class']['img-responsive'][] = "true";
  }
 }
}


how to output image file from database drupal 7? I have created testing module that will upload image and outputting it to my page. but, I can't seem to output my image file from my database. here's my code

function database_ex_menu() {
  $items = array();
  $items['database-ex'] = array(
    'title' => 'My Database Form',
    'type' => MENU_NORMAL_ITEM,
    'access arguments' => array('submit database_ex'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('database_ex_form'),
  );
  return $items;
}

function database_ex_form($form, $form_state) {
  $form['myimage'] = array(
    '#type' => 'file',
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Add item'),
  );
  return $form;
}

function database_ex_form_submit($form, $form_state) {
  $fe_id = db_insert('example')
    ->fields(array(
      'myimage' => $form_state['values']['myimage'],
    ))
    ->execute();

  drupal_set_message(t('Your entry has been added'));
}

//This function supposedly will output my image file inside a div.

function database_ex_submission(){
  //What to do From here!
}

Firstly save image to your server and then you can output the image.

You can save image by using file_save_upload().

  file_save_upload : Saves a file upload to a new location.

$file = file_save_upload('myimage',array(), 'public://');

Get fileid(fid) of the image

$fid=$file->fid;

And then save this $fid to your database.

After it get fid from database

  $upload_record = file_load($fid);
  $url = $upload_record->uri;

  $render_image = theme(
    'image_style',
    array(
      'style_name' => 'Style_name',
      'path' => $url,
      'getsize' => TRUE,
      'attributes' => array(
        'width' => '250',
        'height' => '162')
      )
    );

Now print $render_image variable where you want to display image.


Having views respect hook_node_access I am using hook_node_access() to deny users access to some nodes based on a custom criteria. However, I do not want this content to show up in a view that lists it if the user does not pass the criteria. Is there any way to have views respect hook_node_access() implementations?

I had the same question a while ago here.

hook_node_access is not recognized by views or menus. It should only be used as the last line of defense.

A better way to control node access is through hook_node_access_records and hook_node_grants as described here and here  .


How to add reCaptcha while doing comments on my drupal website I am developing a drupal website. To avoid spam I have decided to use reCAPTCHA module while user registration and before putting comments on my website.

How to achieve this? Can I use reCaptcha while submitting comments?

Thank you all, Its done. Procedure as follows :

I have downloaded 2 modules CAPTCHA & reCaptcha.

Then extract them into /var/www/site/modules/ .

Then I have restart my web server. Then goto browser.

Next I have found CAPTCHA and reCaptcha options on modules section.

Then I configured CAPTCHA settings in configuration section according to my requirement.

Thats it !!  When I try to do comment on my website it was given me captcha challenge This is what all i need.

Thanks!! :)


what to fill in after $items in hook_field_is_empty I'm trying to build a module that constructs a field that needs to show in Manage Fields. I'm trying to understand what it is function by function. Looking at the example field module the code says

function field_example_field_is_empty($item, $field) {
  return empty($item['rgb']);
}

Where does this 'rgb' come from? What is $item? How do I know what to put there in another field? My guess is that it just represents whatever is filled into the field, the actual value. Becuase the value of my field is going to be an HTML link, my guess is, for now at least, to type $item['link']. But I can't really verify it.

rgb is one of the column names defined by the field_example module's implementation of hook_field_schema():

function field_example_field_schema($field) {
  $columns = array(
    'rgb' => array('type' => 'varchar', 'length' => 7, 'not null' => FALSE),
  );
  $indexes = array(
    'rgb' => array('rgb'),
  );
  return array(
    'columns' => $columns,
    'indexes' => $indexes,
  );
}

These columns are the actual storage for your field's various values, and represent the columns you'll find in the field_data_* and field_revision_* tables in a normal Drupal installation.

In the case of the rgb field there's only one column, but for many fields there are multiple columns (for example the image field which besides a 'fid' (file id) column has 'alt' and others).

The $item passed to hook_field_is_empty() is the representation of an instance of your field attached to an entity...essentially it contains the values filled in (or not as the case may be) by the user.

All of the columns you define in hook_field_schema() will be available in $item in hook_field_is_empty()...you then use whatever custom logic you need to decide whether the field has been sufficiently completed for storage, and return a TRUE or FALSE to represent that.


Is there a way to do concurrent editing? Is there a MediaWiki-like method for supporting concurrent editing of text bodies in Drupal 7?

If no feature currently exists, what are some decent PHP diff libraries that could be wrapped up by a Drupal module that could do the job?

You can use etherpad kind of feature which allows you to do concurrent edit of node body.

Etherpad is collaborative editor by which you can write any node field using concurrent editing. Check Readme.txt for installation purpose.

And one more thing if you have no permission to install etherpad on your server(as shared hosting will not allow it) then you can use Piratepad module, which allows you to embed the pad using iframe from piratepad site.


How can I Eliminate render-blocking JavaScript and CSS in above-the-fold content? I am using drupal 7 and Page speed in 82 for desktop on Google Page Insights.
I am having some issues regarding eliminating render blocking js and css.
How can I do this for aggregated js/css ?
I know we cannot enable Leverage browser caching for external js.
I have used following modules:
1. Minify
2. Advanced CSS / JS Aggregation.

Please see the attached screenshot of Google Page Insights.

They are not render blocking. That is the main Drupal's js and css aggregated. Because they have most of the site's js and css in them, they end up quite large, and that makes most optimizers detect them as problematic.

There is a high probability that you don't want to do anything about this.


Adding link with image in the .tpl.php file I have just started with drupal and have very little understanding and experience with it. I was able to develop a module by referring to sample modules available online. I have a .tpl.php file that is supposed to have a link in the form of an image, I am hoping to execute a php function (php function is ready) by clicking on that image.
So my question is how to add a link inside the .tpl.php file, do I have to implement a form? if so, what file should have this form? How to execute the php function on click from this link?

Please let me know if the question doesn't make enough sense.

Thanks

I think what you want is something to link to that will execute your PHP "callback". Have a look at hook_menu() in the Drupal API.

Here's an example:

/**
 * Implements hook_menu().
 */
function MODULENAME_menu() {
  $items = array();
  $items['mymodule/callback'] = array(
    'page callback' => 'MODULENAME_do_callback',
    'access arguments' => array('access content'), // You can specify a permission here.
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function MODULENAME_do_callback() {
  // your php here
}

With that you should be able to link your image (just with standard HTML) to yourdomain.com/mymodule/callback and it will execute your code.

Note: Be sure to clear all caches after adding your hook_menu() implementation.


Using Rules module to Auto Post the content to Linkedin Account I am using Drupal 7. I used Feeds module for content from the RSS. So i can get the content from RSS Feeds. Now Feed Content types automatically saved with RSS Feeds content. So now I want to auto Post the Feeds content to the twitter,linkedin and facebook.I am using Twitter module.

So i can Auto post the content using rules module to Facebook.
Same Time I Can Auto Post the content using rules module to twitter..
 I want to post this content via rules module to linkedin.. I am using Linkedin module also. But it doesn't work for rules module ? Using linkein module for particular content types only. I want to post the content for particular user linkedin account?Admin can submit the content post to the linkedin account.But i want to auto post the content for particular user account?

Is there any way to auto post the content via rules module to linkedin account. I am in critical situation.Please anyone guide to me. Thanks in advance.

Have you tried the LinkedIn Module?

  This module provides integration with the LinkedIn API. At the moment
  it supports the following features:

  Per-user OAuth authentication between LinkedIn and Drupal Post
  LinkedIn status from node edit form (like the Twitter module)
  Synchronise LinkedIn user profiles with a user profile tab in Drupal

For Drupal 7 it's still dev and there may or may not be any updates coming. But it would be a good place to start.


Move CSS and JS cache folder I want to move the CSS and JS cache folders (sites/default/files/css and sites/default/files/js to another place. Is this possible?

I want to do this because I'm planning to have the files folder on a remote file system and I think that accessing the CSS and JS from remote would slow down the site.

Edit: I'm using Drupal 6.

I'm not saying this is the best or correct way to do it, but I think you could use hook_file_url_alter to change the url for your script and stylesheets:

 function hook_file_url_alter(&$original_uri) {
      // rewrite url for your javascript files
      if(strstr($original_url, 'sites/default/files/your-script.js')) {
          $original_url = 'http://example.com/js/your-script.js';
      }
 }


How to add custom permission for a node? Is there any way to add custom permissions for a node?

Here is the requirement: I have a node where I have to set 2 permission, view & subscribe. View permission I can use the default content view permission. But how can I introduce a new permission for subscribe?

A possible alternative is to use the Rules module, and create a rule that is a variation of the rule mentioned in my answer to the question aboutr "How to make the permissions of a module more granular?".

The variation in your case will be something like so:

Use the path specific to the node of your case.
Adapt the "Rules Action" to fit your needs.

You may also want to add some "Rules condition(s)" related to the "role" that is required to allow actions like edit, delete, etc. If you have multiple actions like that, you either build one such rule for each action, or you use the Conditional Rules module to make it all fit in a single rule. Obviously, this approach does not "introduce" a new permission that can be assigned by an admin (which is not a requirement either in the original version of this question, right?).


Convert taxonomy to entity reference I have a migration use case where I can't figure out a way to get along with:

I have a Drupal 7 site which shall be migrated to D8. I don't want to migrate the content 1:1 but rearange some things to better fit the D8 way.

In the old site there are products which have an "ingredients" field which is a reference to taxonomy terms. Additionally there are "griege" nodes which technically represent an ingredient but are not associated with the taxonomy vocabulary "ingredients". They have indeed the same title so could be mapped by string comparison.

Now I want to do the following:

Import all "Griege" nodess from the old site and save them as
"Ingredient" nodes
Import all "Product" nodes to the new site
Check if they have ingredients (taxonomy terms) assigned
If so, search for "Ingredient" nodes in the new site (term name == Ingredient title) and attach them to the newly created "Product"

In short I want the assigned taxonomy terms to be converted into "normal" content entities.

What I did so far is to extend the Drupal 7 node source plugin by adding the following left joins within the query() method:

$query->leftJoin('taxonomy_index', 'ti', 'ti.nid = n.nid');
$query->leftJoin('taxonomy_term_data', 'ttd', 'ttd.tid = ti.tid');

My problem is that I don't know what to do with that information within the process plugin. I could return the correpsonding Ingredient ID but as it's an 1:N relation between Prdouct and Ingredient that would mean it would overwrite the array holding the product ingredients everytime I process a row.

I hope my problem is somehow clear... :/

Some general questions I have:

Is there a way to access the datasource (the D7 source database) within a process plugin? E.g. do a select on the old product (get all terms, do the lookup in the new DB and return an array of Node Ids)
Could my solution somehow involve the usage of a destiantion plugin (I haven't fully understood the usage of those I fear)?
Is there something completely different I missed out to do the job?

Many thanks in advance!

Dennis

I don't have time to fully flesh it out at the moment, but the approach I would take would be to:

In your product migration, which presumably is using the d7_node source plugin, override that source plugin and implement prepareRow() (not forgetting to call parent::prepareRow()!) to query the related ingredient terms and $row->setSourceProperty('ingredient_names', /* array of term names *?);
Use the migrate_plus entity_lookup process plugin to map those ingredient_names to existing (previously imported) ingredient node titles. You'll be looking at the example with full configuration for your use case...

Hope this helps!


remove all active sessions for given uid How to remove all active sessions for given uid who has logged in from different browsers or apps.

I used

drupal_session_destroy_uid($uid);
drupal_session_regenerate();

but old sessions still valid and user can create content from apps having that sessions.

I need to delete all sessions for that user and create new one .

Why not just delete the corresonding entries from the sessions table? e.g.
in sql, delete from sessions where uid = <uid>

This won't work if you're using memcache for your sessions table, but I imagine there's an equivalent if you are.


Install issues via composer I ran composer global require drush/drush:dev-master. I'm not sure how to  resolvirthis issue as it seems that the package isn't found anymore. Do I have to update somehow?

Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for drush/drush dev-master -> satisfiable by drush/drush[dev-master].
    - drush/drush dev-master requires codegyre/robo ~1.0.0-beta1 -> satisfiable by codegyre/robo[1.0.0-beta1] but these conflict with your requirements or minimum-stability.

Installation failed, deleting ./composer.json.

I did a work around without using composer to do the install by doing the following:

make a drush directory in your home folder (~)
git clone https://github.com/drush-ops/drush.git
cd into that directory
./drush --version (it should complain about composer install)
run composer install
./drush --version WORKING!

I'm using ubuntu so initially I did apt-get install drush, but that version is 5. Then I did the following to download the latest into ~/drush

From there I went to my global run folder: /usr/bin and renamed the old drush to drush_old and then did a ln -s ~/drush/drush drush now its on the latest drush!


Does the summary area support input filters? I have noticed that text filters placed in the summary area don't seem to work, that the raw text appears in the summary info when posted in Twitter, Facebook and the like.

Is that some inherent problem in the summary area, or is it something like the Metatag filter that sends the unfiltered text directly to Twitter and Facebook?

I will check whether the Metatag output can be filtered in the mean time.

Text filters should definitely work in the Summary. You can test this by creating a View that uses the formatter "Summary" or "Summary or Trimmed" and using an input format like Plain Text in the Summary. HTML tags should be stripped from your View.

It sounds like something else is at play here.

Edit your Content Type (Structure > Content Types > Your Content Type) and look for the field in question (probably the Body field.)

Make sure Text Processing is set to "Filtered Text (user selects text format)" and the "Summary input" box is checked.

In the "DEFAULT VALUE" fieldset, select the desired Text format (e.g., Full HTML).

EDIT:

I'm sorry, you are correct. The built-in summary is just a summary and it does not support text filters. HTML in that field will be stripped.

This thread on Drupal.org says this won't be fixed until Drupal 9:

https://www.drupal.org/project/drupal/issues/1529188

The workaround is to create a new field called "Summary" and set its text format to the desired WYSIWYG format:

Then, manage the display of your content type to hide the new field from the Default view mode.

In the Teaser view mode, hide the Body field and show the Summary field instead.

The other solution is to edit the "Filtered HTML" text format to allow the <span> tag and other HTML that you require.

Honestly, it's a bit ridiculous that you have to do this to get what you want. I guess it's just one more reason to look forward to Drupal 9!


Ajax pager won't work after other ajax event I have a View called 'example' with the Pager turned on and Ajax turned on.

I have a script that refreshes the View by providing a path as an argument.

    $('.view-example a')
        .live('click', function(e) {
            e.preventDefault();

            var trigger = $(this),
            arg = trigger.attr('href');

            $.ajax({
                dataType: 'json',
                type: 'GET',
                url: '/views/ajax?view_name=example&view_display_id=block_1&view_args='+arg,
                success: function(data) {
                    $('#container').html(data.display);
                },
            });
    });

That all works fine. Although once the Ajax event has succeeded the View's pager doesn't work as expected. Instead it displays the json data of the view.

Append the following line in the 'success' function

Drupal.attachBehaviors('#container');


Issues trying to understand and debug simplesamlphp error Simplesamlphp used to work on the site. Something changed and now it does not.

The IDP remote config has been verified, including the cert
The SP cert and pem in the simplesamlphp/config folder have been verified
All the required settings show green on the admin page
When the ACS URL is entered as a test, a JSON file with the metadata is downloaded

All there seems correct. But when a user attempts to login, the following is thrown into the log file. I note that despite the entry about the candidate having :443, the URL with or without the port results in identical json.
This is Drupal 8.9.6, PHP 7.3.21, simplesamlphp_auth 8.x-3.2, simplesamlphp 1.18.8

simplesamlphp ERROR [ffdf5e0102] SimpleSAML\Error\Error: UNHANDLEDEXCEPTION
simplesamlphp ERROR [ffdf5e0102] Backtrace:
simplesamlphp ERROR [ffdf5e0102] 1 /mnt/www/html/mysite/vendor/simplesamlphp/simplesamlphp/www/_include.php:17 (SimpleSAML_exception_handler)
simplesamlphp ERROR [ffdf5e0102] 0 [builtin] (N/A)
simplesamlphp ERROR [ffdf5e0102] Caused by: SimpleSAML\Error\Exception: > This SP [https://admin.mysite.gov/simplesaml/module.php/saml/sp/metadata.php/default-sp]  is not a valid audience for the assertion. Candidates were: [https://admin.mysite.gov:443/simplesaml/module.php/saml/sp/metadata.php/default-sp]
simplesamlphp ERROR [ffdf5e0102] Backtrace:
simplesamlphp ERROR [ffdf5e0102] 4 /mnt/www/html/mysite/vendor/simplesamlphp/simplesamlphp/modules/saml/lib/Message.php:718 (SimpleSAML\Module\saml\Message::processAssertion)
simplesamlphp ERROR [ffdf5e0102] 3 /mnt/www/html/mysite/vendor/simplesamlphp/simplesamlphp/modules/saml/lib/Message.php:640 (SimpleSAML\Module\saml\Message::processResponse)
simplesamlphp ERROR [ffdf5e0102] 2 /mnt/www/html/mysite/vendor/simplesamlphp/simplesamlphp/modules/saml/www/sp/saml2-acs.php:141 (require)
simplesamlphp ERROR [ffdf5e0102] 1 /mnt/www/html/mysite/vendor/simplesamlphp/simplesamlphp/lib/SimpleSAML/Module.php:260 (SimpleSAML\Module::process)
simplesamlphp ERROR [ffdf5e0102] 0 /mnt/www/html/mysite/vendor/simplesamlphp/simplesamlphp/www/module.php:10 (N/A)
simplesamlphp ERROR [ffdf5e0102] Error report with id 86f8550b generated.

It turns out that the issue was the entityID on the authenticator end containing the port number, and the default entityID provided by simplesamlphp not so. Having the authenticator change their config entries, dropping the explicit port reference, resolved the issue.


Can DrupalGap consume Views as HTML? Is it necessary to write all the mobile app's own html files for displaying Drupal configured Blocks / Pages / Views? I was hoping I could just rebuild my primary Navigation menus using the DrupalGap settings.php files or hook_menu, but leave the callbacks to just inject the return HTML?

For example...

drupalgap.settings.menus['user_menu_standard'] = {
    links:[
    {
        title: 'A Title',
        path: '/some-content-type',
        options: {
            attributes: {
                'data-theme': 'b'
            }
        }
    },
};

function my_module_menu() {
  var items = {};
  items['airlines'] = {
    title: 'airlines',
    page_callback: 'my_module_airlines_page'
  }
  return items;
}

// No mobile dedicated html file necessary. I essentially want a webview with a phonegap native menu.
function my_module_airlines_page(html) {
  div.innerHTML = html;
}

Is this - or something similar - possible to automatically reuse the Drupal's front-end within DrupalGap?

DrupalGap is typically used to consume Views as JSON results. It can then use the JSON to decide how to display the HTML inside the app.

Check out this example for creating a page in your App that will fetch and display Views content:

http://www.drupalgap.org/node/219

Out of the box, it easily lets you create lists and tables of your Views data.


Startup Growth Lite - How To Set Width For Content Type I'm using the theme Startup Growth Lite for which we've created a content type but I can't find how/where to set it's default width. We want it to be the same width as the 'Basic Page' but for some some reason our content type is always much narrower as if it's expecting left & right sidebar content (I've checked the blocks and there are none assigned).

Pulling my hair out on this one!

Thanks

Typical, minutes after posting the question I finally found the answer.

What has worked for me was adding my content type to the template.php file startupgrowth_lite_preprocess_page function, our content type was called 'client_work' which once added set it to display the same as the 'page' content type.

I added the following

&& $variables['node']->type != 'client_work'

to the end of the first if statement in the function below (around line 494).

function startupgrowth_lite_preprocess_page(&$variables) {

    /**
     * Insert variables into the page template.
     */
    if (isset($variables['node']) && $variables['node']->type != 'page' && $variables['node']->type != 'client_work') {


Advanced CSS/JS Aggregation Module Breaks My Site Layout When I enable my module Advanced CSS/JS Aggregation it breaks my site layout.  Is there something I need to do before or after when enabling this module.

To fix the site layout I need to disable the Advanced CSS/JS Aggregation module and it works again.

I faced the same issue, here is some steps to check:

check if your css loaded and optimised in your page source code some files like /sites/default/files/css/css_QnKw33sohmgUyVqs9lGXvHTJTZsphXTkXdkVVmt25ts.css if it's no check if there is any errors in your console, if this is the case Check your status page and log messages, and permissions
If it's yes all files well loaded this is was my case i had some css errors that's why even my css files loaded not taking any effect:
So i had to check / validate all my css files and correct any errors.
I used this https://codebeautify.org/cssvalidate.
there is a lot other websites to validate your css.
I hope this help you !


Import CSV with Single Quoted data I need to use feeds importer to import csv file. But there's single quote in the values like doesn't. Is there anyway to escape the single quote?

Thanks

Part of the problem here is that there's no standard specification for CSV.

Added to that, Microsoft does not have much incentive to ensure interoperability between their version of CSV and Drupal's version, and so it is not surprising that they do not offer any (direct) way to encapsulate the contents of cells with single quotes within double quotes, so you've got to do something a bit more complicated if you want Excel to output Drupal-friendly CSV files.

Or, since Drupal is telling you where the problem is, you can do it manually.  If you only have a few rows with apostrophes, then that may not be a big deal.  If you have a lot of rows in your CSV with apostrophes or single quotes, then you've got a bit of pain.

Alternately, if you've got Python on your machine, or are willing to install it, this python script to add double-quotes to CSVs may work for you, and may be much easier than dealing with Excel macros.  It all depends on the languages and language environments you're comfortable with, however.

One might argue that Drupal (or more specifically the Feeds module) should support Microsoft's CSV, and thus handle apostrophes gracefully when not wrapped in double quotes.  If you are of this opinion, you may want to file a request with the Feeds project.  Since there is no (standard) CSV spec, this can't be considered a bug (AFAIK), but it does seem like a useful feature that they might want to add.


jQuery animation isnt repeating Im pretty sure that my jQuery should below should work but when I use it in a Drupal site the animation doesn't repeat like it should.

http://smartpeopletalkfast.co.uk/t/

$(document).ready(function() {
    if ( $(window).width() > 960) {

    function fadeOutFunc() {
        $('.image-list .bottom').delay(1000).fadeOut(500, function() {
            $('.image-list .bottom').delay(1000).fadeIn(500,fadeOutFunc);
        });
    }

    fadeOutFunc();

    //  jQuery('.image-list .bottom').css('opacity','0.6');

    }
});

Try putting js code using Drupal Behaviours

(function($, Drupal)
{
  Drupal.behaviors.animation = {
    attach:function()
    {
      if ( $(window).width() > 960) {

      function fadeOutFunc() {
        $('.image-list .bottom').delay(1000).fadeOut(500, function() {
          $('.image-list .bottom').delay(1000).fadeIn(500,fadeOutFunc);
        });
    }

    fadeOutFunc();
    }
  };
}(jQuery, Drupal));


What is the best way to redirect node to node I am trying to figure out what is the best way to create a redirect from one node to another.  For example, say we have two nodes:
node/1 | path-one
node/2 | path-two

I created the following redirect:

But when visiting path-one it still shows node/1 instead of redirecting to node/2.
The only way I can do it is to remove the path alias for node/1 and then it works.

Try the redirect when logged out of your admin account as I believe when logged in as an admin any redirects from a page that exists won't get triggered. This is to allow you to be able to still access that page as an administrator


How to stop menu links being disabled after saving nodes? A localised Drupal 7 site I'm working on has a navigation menu along the top. Each node is provided with a menu link with a given weight. Nodes are translated into three (non-English) languages (the admin language is English). The nodes show on the menu correctly depending on the current language.

Whenever I edit a node (eg edit the title, body) and click Save, its links disappears from the menu.

The same thing happens if I edit a node but don't actually change anything, then click Save.

I can re-enable it by:

Edit the node again
Untick the menu link
Save
Edit the node yet again
Tick the menu link (re-filling the title/weight)
Save again

Or:

Go to admin/structure/menu/manage/main-menu
All the other menu links are enabled, but the recently saved is not and has "(disabled)" after its name
Tick the box to re-enable
Save configuration

But how can I stop menu links from being disabled when a node is edited?

Here's a quick fix:

Download version 1.7 of i18n.
Unzip it and find the folder named i18n_menu
Go to your site's modules directory (could be /sites/all/modules/)
    Find the folder i18n
Replace the subfolder i18n/i18n_menu with the version from version
1.7 you downloaded in step 1

You can also check this bug report: http://drupal.org/node/1905268


How to create menu link to an individual field within a node in Drupal 7 Assume a content type with two user fields, being a description and a file.  Assume that a few content items, or nodes, have been created that are based on this content type.

Description                                    Image
Joe Brown                                      www.images.com/picture_of_JoeBrown
Joanna White                                   www.images.com/picture_of_JoannaWhite
Jeremy Green                                   www.images.com/picture_of_JeremyGreen
etc

Easy enough to create a menu item that points at the node.  Once the user has opened the node they can click on the image's URL and retrieve the image.

Easy enough to create an "external link" that points directly at the image and jumps straight to it.  However the external link's address is static.

How does one create a menu item the jumps directly to the image that is currently stored in the Drupal node/content without an intermediate step?

In this example, I need to append the name of the field that contains the image url to the menu node address so that the system will show the person's current image with a single click from the menu without an intervening node/content display.

This seems like it should be easy, but I can't see it......

The quickest might be with a MENU_LOCAL_TASK in a custom module, e.g.:

function YOURMODULE_menu() {

  $items=array();

  $items['node/%node/avatar'] = array (
    'title' => 'Avatar',
    'page callback' => 'YOURMODULE_node_avatar',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'weight' => 64,
    'type' => MENU_LOCAL_TASK,
  );

  return $items;

}

function YOURMODULE_node_avatar($node) {
  // drupal_goto($node->field_avatar[0]['filepath']); // Drupal 6
  drupal_goto($node->field_avatar[LANGUAGE_NONE][0]['filepath']); // Drupal 7 (I think :)
}

which would create an Avatar tab for you that when clicked on would display the image in field_avatar.  Obviously you'd have to change that up to your exact field (and I think I got the D7 language stuff right in there if you are on D7).

It could also be called directly, e.g. www.YOURHOST.com/node/1/avatar would display the avatar of node with nid 1.  If this is going to be how you access it, you could change MENU_LOCAL_TASK to MENU_CALLBACK and then the Avatar tab wouldn't show up on the page.