Reference a Field in Content Type I created a content type with a text field in an Omega subtheme called "Prepaid" in Drupal 7. When a user inputs a hex value, it will create a div within the content area with inline CSS that changes the background color.  I know the PHP to make this work, but I am having issues determining where to place the function, where to call the function, and how to reference the field I created in the code. I am not new to coding, but I am new to coding within Drupal.  If anyone can help, I would be eternally grateful.

Create node--YOOR_TYPE_NAME.tpl.php and print_r($node) object, find what you need and place it on write tag style


Attach library to a specific page I am developing a custom module in Drupal 8. My custom module include many JavaScript and CSS files which make the site really slow and I don't want them in all pages. I have developed some custom blocks and each JavaScript and CSS library correspond to a block. I want those files on those pages of the site where my custom blocks are visible.

In my last Drupal 8 project, I have done something like the following.

function HOOK_page_attachments(array &$attachments) {
    $user = \Drupal::currentUser()->getRoles();

    if(in_array("administrator", $user)){
        $attachments['#attached']['library'][] = 'module/library';
    }
}

I am not sure how to check which blocks are visible in the page.

If you're using a twig template, you can add it there.

{{ attach_library('module/library') }}

Which is helpful when you want to control whether the library loads before or after the content.

https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme


Why is my custom parameter converter class not used? I start banging my head on the table, the wall or anything else... please help me.

Here is my my_module.routing.yml:

my_module.api.validate_coupon:
  path: '/api/v1/{coupon_code}/validate'
  defaults:
    _controller: '\Drupal\my_module\API\ValidateCouponController::validate'
  requirements:
    _permission: 'access content'
  options:
    parameters:
      coupon_code:
        type: coupon_code_converter

This is my services.yml

services:
  paramconverter.coupon_code_converter:
    class: Drupal\my_module\Routing\CouponCodeConverter
    tags:
      - { name: paramconverter }

This is my converter class - it is taken from Drupal\language\LanguageConverter and I added some breakpoints which should make the script stop in my IDE:

namespace Drupal\my_module\Routing;
use Drupal\Core\ParamConverter\ParamConverterInterface;
use Symfony\Component\Routing\Route;

/**
 * Converts a coupon code to a fully loaded coupon
 */
class CouponCodeConverter implements ParamConverterInterface {

  /**
   * {@inheritdoc}
   */
  public function convert($value, $definition, $name, array $defaults) {
    if (!empty($value)) {
      return $this->languageManager->getLanguage($value);
    }
    return NULL;
  }

  /**
   * {@inheritdoc}
   */
  public function applies($definition, $name, Route $route) {
    return (!empty($definition['type']) && $definition['type'] == 'language');
  }
}

And this is my controller class:

namespace Drupal\my_module\API;

use Drupal\Core\Controller\ControllerBase;

class ValidateCouponController extends ControllerBase  {

  public function validate($coupon_code) {
    $container = \Drupal::getContainer();
    $kernel = $container->get('kernel');
    $services = $kernel->getCachedContainerDefinition()['services'];
    ksort($services);
    return array(
      '#markup' => 'hallo'
    );
  }
}

I can enter http://mypath.com/api/v1/1/validate and the controller gets the value '1' for $coupon_code. But I want my CouponCodeConverter class to do some magic before the parameter gets sent to the Controller... but the converter gets not called... what do I wrong?

I think the condition in applies() doesn't match with the route parameters, try this:

  public function applies($definition, $name, Route $route) {
    return (!empty($definition['type']) && $definition['type'] == 'coupon_code_converter');
  }


Form is not submitted with arg() in URL I have a list of items. By clicking on an item I open a form at /items_form/123 where 123 is the itemid. When filling the form I use the arg() function to get the 123 and read some data from the database. No problem.

My problem is, when submitting the form, the default submit handler is not called.
When I open the form without the arg e.g. /items_form and submit this form, the submit handler is called.
Where is my missing link?
Here is my hook_menu:

$items['items_form'] = array(
'title' => 'Item Form',
'page callback' => 'drupal_get_form',
'page arguments' => array('get_item_form'),
'access arguments' => array('access items_form content'),
'type' => MENU_NORMAL_ITEM, //Will appear in Navigation menu.
);

Any ideas?

First, if you want to get an argument from the URL, you should declare it in hook_menu, as such:

$items['items_form/%'] = array(
  'title' => 'Item Form',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('get_item_form', 1),
  'access arguments' => array('access items_form content'),
  'type' => MENU_NORMAL_ITEM, //Will appear in Navigation menu.
);

Drupal's menu system will then pass in the itemid to drupal_get_form(), which will then pass it along to your form declaration function. You will need to add an argument to your function definition to access it, suggest something like this:

function get_item_form($form, $form_state, $itemid = NULL){
  $form = array();
    ...
}

Please look at the documentation for hook_menu for more information about how to handle URL arguments. I would caution against using arg() in your code.

The reason this is important is what happens when you submit your form with a URL argument. By default, if you do not override with the #action parameter in your form, it submits a POST request to the present URL. By not declaring that your URL has an argument in it, Drupal actually doesn't know how to handle a request to *items_form/123*. The only reason you see anything but a 404 when you go to *items_form/123* is that Drupal attempts to find the nearest path. I suspect that since it doesn't know explicitly what to do when a request is made to *items_form/123* it breaks the form submission handling.

I should also mention that you'll need to declare both *items_form* and *items_form/%* menu paths if you wish them both to work. They're distinct paths in the eyes of Drupal's menu system.


How do I remove all default styles (such as div.widthMarker) from CKEditor? I have copied ckeditor.styles.js to /themes/seven/ckeditor.styles.js,
and in the configuration page /admin/config/content/ckeditor/edit/Advanced
I altered the predefined styles drop down to point to this new file:

if(typeof(CKEDITOR) !== 'undefined') {
    CKEDITOR.addStylesSet( 'drupal',
    [
            { name: 'Larger', element: 'span', attributes: {'class': 'size-1'} },
            { name: 'Epic', element: 'span', attributes: {'class': 'size-2'} },
            { name: 'MASSIVE', element: 'span', attributes: {'class': 'size-3'} },
            { name: 'Stupid!', element: 'span', attributes: {'class': 'size-4'} },
    ]);
}

Now when I load the WYSIWYG editor I still see other styles in the styles dropdown:

How do I remove the other styles that are not present in my ckeditor.styles.js file?

I have searched through all the code but can't find any reference to div.widthMarker or div.sortableListDiv except for in a .CSS file, but not everything in the CSS file is showing up.

Cheers,
- Paul

In CKEditor profile settings /admin/config/content/ckeditor
click the edit link on the profile you want to change.

Under "Editor Appearance" uncheck "Stylesheet Parser plugin" and save.
This will remove the default classes.


How to skip form validation with ajax? I am building a form with tabledrag and ajax "add more" and "remove item" buttons.

I tried different variations with '#type' => 'button' and '#type' => 'submit'.

Currently, pressing one of those ajax button always triggers form validation and then a form rebuild. (this means every element is processed twice).

If a user wants to add a bunch of items with required values, then validation errors will block and disrupt the "add more" mechanic, or they will show up with the error colors, which is all undesirable.

I experimented a bit with '#limit_validation_errors', but I am not sure this does what I need. If I understand correctly, this only suppresses the error output, but the actual validation is still executed.

I looked at drupal_process_form(). The validation and rebuild happens here:

  $form = form_builder($form_id, $form, $form_state);

  // Only process the input if we have a correct form submission.
  if ($form_state['process_input']) {
    drupal_validate_form($form_id, $form, $form_state);
    [..]
      $form = drupal_rebuild_form($form_id, $form_state, $form);

This means the form is processed one time, then it is validated, and later it is built and processed again.

For my purposes, the entire validation and rebuild could be skipped.
I managed to implement the "add more" mechanic in a value callback, so I don't need a #submit handler on the ajax "add more" button.

The code in drupal_process_form() suggests that I could skip the validation and rebuild by setting $form_state['process_input'] = FALSE. However, this also suppresses the detection of $form_state['triggering_element'], which means that ajax_form_callback() won't work correctly anymore.

I might figure something out here, but perhaps there is something simpler that I missed.

I think the problem is the same as described here, https://www.drupal.org/project/drupal/issues/2476569.
But I am not going to wait for this issue to be done for D8 and backported  to D7. I am looking for something I can do right now.

You want #limit_validation_errors. Setting this value to an empty array will mean that nothing is validated when the button is clicked.


How to add two fields on one add another items? I have 2 fields with unlimited values both fields show its own add another items button.
i am trying todo is add both fields add with one add another items button.

CCK version 6.x-3.0-alpha3 contains a module called Multigroup. It allows you to group multiple fields together and repeat that group of fields multiple times with a single add-another button. This is an alpha version though, so if you decide to use it, test well to make sure it doesn't break something else.


Migrate taxonomy terms with CSV I would like to import some taxonomy terms with a taxonomy term in it.
field_regio2 is a entityreference field to an existing taxonomy term Regio.
But for some reason it is not working. Everything is working except the field_regio2.

$ drush mmsg import_gemeentes gives:

  the entity_lookup plugin requires a value_key, none located

?

uuid: 7eef6b86-80db-40ab-8359-91d20675e0f2
langcode: en
status: true
dependencies: {  }
id: import_gemeentes
class: null
field_plugin_method: null
cck_plugin_method: null
migration_tags: null
migration_group: migrated_terms
label: 'Migrate gemeentes from the source CSV to taxonomy terms'
source:
  plugin: csv
  path: 'public://gemeentes.csv'
  header_row_count: 1
  keys:
    - id
  column_names:
    -
      id: id
    -
      vid: vid
    -
      name: name
    -
      field_stratenplan_luchtfoto_refe: field_stratenplan_luchtfoto_refe
    -
      rid: rid
    -
      rid22: rid2
process:
  vid:
    plugin: default_value
    default_value: gemeente
  name: name
  field_stratenplan_luchtfoto_refe: field_stratenplan_luchtfoto_refe
  field_regio: rid
  field_regio2:
    plugin: entity_generate
    source: rid22
destination:
  plugin: 'entity:taxonomy_term'
migration_dependencies: null

The syntax for entity_generate is:

field_regio2:
    plugin: entity_generate
    source: rid22
    entity_type: taxonomy_term
    # This is where migration breaks. It need to know which key to look for.
    value_key: name
    bundle_key: vid
    bundle: YOUR_VOCABULARY_MACHINE_NAME


How to find all Drupal modules which has dependence I would like to know if it possible to find all contributed modules that depend, for example, on the Subform module.

This information could be useful if you are working with a module, and want to create yours because you don't know that the same module already exists.

That's really easy to do with Gotta Download Them All. Once you have downloaded all the modules, you can just run a grep command to search the whole contribution space.


display custom order fields in a checkout pane of drupal commerce I have added a custom field in orders and I can view and edit. I want to display this custom field in checkout panes, so users can fill them. but by default there is no relation between fields that we can add to checkout panes and the fields that we add to orders.

How can I display fields that I add to orders in the checkout form?

Try Commerce Fieldgroup Panes module.

  This enables an easy way to collect information in the checkout
  process... The collected information is auto added to the order... You
  can watch a demo usage in Commerce module Tuesday videocast:
  http://www.commerceguys.com/resources/articles/257


Add class of user role to page? I need to add a class of the user's role to my page. Ive tried the following but it doesn't work, and it seems from the comments its not working for others aswell.

function THEMENAME_preprocess_page(&$vars) {
  if ($vars['user']) {
    foreach($vars['user']->roles as $key => $role){
      $vars['class'][] = 'role-' . drupal_html_class($role);
    }
  }
}

http://grasmash.com/article/drupal-add-current-users-role-body-classes

Use the hook_preprocess_html:

function THEMENAME_preprocess_html(&$vars) {
  foreach($vars['user']->roles as $role){
    $vars['classes_array'][] = 'role-' . drupal_html_class($role);
  }
}


Enable users to edit user profile and nodes in same page In my project I would like my users to be able to edit their profile from the same page they view their profile.

In order words when they click on the fields or an edit button beside the fields, they will be able to enter a new value.

What I want to achieve is pretty much how users edit their profile on LinkedIn.

Please is there a module that can help me achieve this?

(Please note that I am displaying the user profile with "views").

Try these modules
https://www.drupal.org/project/quickedit
https://www.drupal.org/project/jeditable

And for views, use editableviews


What are the URL Alias pattern replacements for taxonomy parent terms when building up Node paths? SCENARIO:

I created taxonomy terms with 3 depth levels. Example:

Term 1 ( Root )
   Term 2 ( Child of Root )
      Term 3 ( Child of Term 2 )

In the URL Alias for my vocabulary I set:

[term:parent:parent]/[term:parent]/[term:name]

That successfully creates a path that looks like this:

"http://mydomain.com/term-1" for the root term
"http://mydomain.com/term-1/term-2" for the root's child term
"http://mydomain.com/term-1/term-2/term-3" for the child's child term

In my Content Type, I created a Term Reference field that forces the user to select the deepest term ( 3rd term down ) with the help of Simple hierarchical select module.

ISSUE:

When creating nodes, I would like to set the node's URL Alias to term-1/term-2/term-3/node-tile. I am having trouble finding the Replacement Pattern for doing just that.

Does path auto allow me to do that out of the box? If so, what pattern should I use?

There are some advanced uses of tokens (not sure off the top of my head if that's just in the context of pathauto or not). You can get what you're looking for with join:

[node:field-name:parents:join:/]/[node:field-name:name]/[node:title]

You could also replace your term pattern with:

[term:parents:join:/]/[term:name]

Using that method your vocabulary can grow gracefully to 4 (or more) levels without having to change the pathauto pattern.

You'll need to go to admin/config/search/path/settings and set the Slash (/) option to "Do not Replace" under "Punctuation" for that method to work.


Send login link in email to registered users On my Drupal 6 website, there are around 400 users registered by site admin and none of then know that they are registered on the site. Now I want to increase the number of registered users but in a secure manner.

I want the registered users to be able to invite at most 5 people whom they think are the most eligible. This is very easy and has been done.

The problem is that to invite new users, the current users will need to login and I dont want them to know their username and password as they will be given to them later.

So the only solution that remains is that I send them a login link in their e-mail so that they can click on the link and get automatically logged in so they can invite 5 other people of their choice.

You should be able to use the Login one time module for this.

  Login one time provides the ability to email one-time login links to
  users. You can also choose the pages they will land on.

I would imagine that the users might be able to change their own paswords after using this one time link.  To prevent this, you should be able to use the Edit own user account permission module.

  This module manage edit permissions to the name, mail and password
  profile filed. You can manage permissions to the other profile
  entities by other admin menu settings.


Using jQuery from Google CDN doesn't work I used drupal 6.22 and I enabled the jQuery Update and jQuery UI modules; I used the latest version (JQuery 1.6.4 and 1.8.16) in my libraries. When I added this code in template.php (my theme) all the page worked correctly in my web site.

drupal_add_js('sites/all/libraries/jqgrid/js/jquery.js');
drupal_add_js('sites/all/libraries/jqgrid/js/jquery-ui-custom.min.js');

When I decided to use a content delivery network (CDN) some of the pages don't work correctly.

drupal_set_html_head('<script type=text/javascript src="https://www.google.com/jsapi?key=my site"></script>');
drupal_add_js('google.load("jquery", "1.6.4"); google.load("jqueryui", "1.8.16");'

Why is this happening?

If I use the following code, some of the pages still don't work correctly.

drupal_set_html_head('<script type=text/javascript src="https://www.google.com/jsapi?key=my site"></script>');
drupal_add_js('google.load("jquery", "1.6.4"); google.load("jqueryui", "1.8.16");

In Drupal 6, you cannot use drupal_add_js to add external JS files. You need to use drupal_set_html_head. Thankfully, in D7 this has been fixed.

drupal_set_html_head('<script type="javascript" src="https://www.google.com/jsapi?key=my site"></script>');
drupal_add_js('google.load("jquery", "1.6.4"); google.load("jqueryui", "1.8.16");', 'inline');


What causes DatabaseSchemaObjectExistsException error on existing table while reverting feature? When trying to revert my updated exported changes on features from development site to production site via Drush, it returns DatabaseSchemaObjectExistsException error stating that there is an existing table already on the schema. Revert could not be completed, so the feature field_base component status is always Rebuilding. Shouldn't features detect if the table is already existing and ignore field creation if it already is? What could have caused this issue? Any possible workaround for this issue?

This is usually caused when the initial feature revert or install went bad. The feature has attempted to created a field (I've only seen it happen with fields) and it's got as far as creating the base table and it's revision table but as far as features is concerned the field doesn't exist. Features then tries to re-create the field but Drupal errors out with that error message because the fields tables already exist.

My usual solution to this is to take a backup of the fields tables (including revisions) and then drop the effected tabled. You should then be able to revert the feature successfully and restore the data from your backup.


Customizing the comment form with custom user profile fields I've just started using Drupal 7 and cannot find an answer to this question so I'm hoping for some help here. I've added custom fields to the user profile on the /admin/config/people/accounts/fields page. For example, I've defined a School field which is text type and a Specialty field which is a list text type.

I'd like logged in users to be able to update their user profile information when submitting a comment to an article. How do I customize the comment form to allow a user to update the custom user profile fields. I've looked in the form and there is an author field, however this only contains the basics like name and email, not the custom fields.

Edit: I want this to be one form submission, both adding a comment and updating user profile information. It seems the way to customize the comment form is through the method function THEMENAME_form_comment_form_alter(&$form, &$form_state), however the $form object doesn't contain the custom user account fields that I've defined.

The module Profiles2 will allow you to add fields through an associated profile structure and provides the familiar Drupal form format for managing fields.


Get result view with formatter programmattically Example a view with show fields:

I want retrive array result like this:

[
  [title,
   date_start
   data_end
   ...
  ]
]

Use $view->result to get the filtered rows, $view-field for the fields, on which you can use the methods getValue() for the field value and render() for the formatted field as render array.

An example:

use Drupal\views\Views;

  $values = [];
  $view = views::getview('view_example');
  if ($view) {
    $view->execute();
    foreach ($view->result as $rid => $row) {
      foreach ($view->field as $fid => $field ) {
        $values[$rid][$fid . '-value'] = $field->getValue($row);
        $values[$rid][$fid . '-render'] = $field->render($row);
      }
    }
  }


$form_state->setRedirect not working after a $form_state->setResponse In the submitForm of a custom form, I have this:

$sFileName = 'sites/default/files/_private/bulletins/' . $form_state->getValue('adherent')[1] . ".pdf";
$response = new BinaryFileResponse($sFileName);
$response->setContentDisposition(
  ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  'bulletin.pdf'
);
$form_state->setResponse($response);

This triggers the download of a pdf document and it works.
Then, I try to execute:

$form_state->setRedirect('<front>');

and that is not working!
In FormState::setResponse documentation, I read « If a response is set, it will be used during processing and returned directly. The form will not be rebuilt or redirected ».
I guess it is why my redirection to  doesn't work...

How can I do it anyway?

short answer RedirectResponse;

use Symfony\Component\HttpFoundation\RedirectResponse;
$response = new RedirectResponse('/where-ever');
$response->send();


How do I expose a contextual filter? I have created a view that shows few entities. To be able to see only a particular entity, I created a contextual filter.

How can I expose the contextual filter I added?

Contextual filter is an an argument to the view, for example through the path or block/plugin context.

It is not visible to the user, it's visible to Drupal.

If you want something to be visible to the user, you need to instead add a filter and then tick the checkbox to expose it, creating a so called "exposed filter". That should then show up in a filter form.


Privatemsg overwrites page title for custom code. How do I correct it? I am using Private message as PHP in a block on the node of a page so that a person can contact the node author without having to leave the page. Here is the code:

$node = menu_get_object();
if ($node->uid != 0) {
module_load_include('pages.inc','privatemsg');
  $recipients = $node->uid;
print "
Contact " . $node->name ." about this post.
";
  $subject = $node->title ." question.";
  print drupal_render(drupal_get_form('privatemsg_new', $recipients, $subject));
}

However, Private message hijacks the title of the entire page, and now every single node  value is 'Write so-and-so' a new message, instead of what the page title should actually be.

Thoughts on how to correct this?

You can check out what's happening here on the test server:

http://g.hokkaido-select.com/classifieds/cars-and-vehicles/motorcycles-and-scooters/2006-150cc-scooter (note, you have to be logged into see the block, but the page title error can still be seen)

I guess the private message form sets the title directly. A simple way round it might be to cache the current title before you render the form, then set it back again afterwards:

$stored_title = drupal_set_title();
print drupal_render(drupal_get_form('privatemsg_new', $recipients, $subject));
drupal_set_title($stored_title);


Pasting text from GoogleDocs into D7 Body field causes imagestyle error? Super strange - I'm copying and pasting text from a GoogleDoc into a D7 article post. When I do this and publish my article, it drops onto the main page into a slider that I've created via a View. This works seamlessly usually, however when I paste the text from the googledoc, it actually distorts my entire main page - seemingly stripping the image styles from my other article posts in the slider, thus, ruining my slider? Any idea why this is and how I can fix it?

You may have better luck exporting the Google Doc to "RTF" format first then copy + pasting that format into the article body.

You could also try the "Paste without formatting" option, such as Ctrl+Alt+Shift+V or Ctrl+Shift+V but would need to re-add the formatting (headings etc..) with that approach.

There may also be some WYSIWYG toolbar options to paste with various formatting options (paste from word, paste as plain text etc..)


Drush & Fbconnect on Windows 7 I have installed fbconnect module with Drupal 6 on Windows 7. Everything seems to be working fine. From front end I can login to my site via fbconnect. However when I try to run and drush script, for example drush updatedb, it throws me following fbconnect error

Message is

  WD php: Exception: Facebook needs the CURL PHP extension. in
  require_once() (line 19 of
  E:\wamp\www\foo\sites\default\modules\contrib_modified\fbconnect\facebook-php-sdk\src\base_facebook.php).
  Drush command terminated abnormally due to an unrecoverable error.

Edit: Curl is enabled but still I am getting this error, please see below screenshot

Drush uses a different php.ini than the web server does.  The phpinfo() you are looking at above is from your web server's php.ini.  Run drush status to see the path to the php.ini that Drush is using.  Then, compare the two and copy directives from the web server php.ini, such as the directives that enable the CURL PHP extension and memory_limit, and put them in Drush's cli php.ini.  Then everything should work fine.


After drush arr - cannot login php 5.5.x, mysql 5.5, drush 5.x, drupal 7.33,

backed up drupal: 'drush ard default --destination=/manual_backup/backup_site_2014_11_15.tar'
switched to new 14.04 Ubuntu server, installed drush, import tar file:

drush arr ./backup_site_2014_11_15.tar --destination=/var/www
edited /etc/hosts:

127.0.0.1 mysite.local

edited /etc/apache2/sites-available/default.conf

    ServerName  mysite.local
    Root            /var/www

        AllowOverride …

Restarted apache

While 'drush cc all' I got the message:

    PHP Fatal error: Call to undefined function node_load() in /data/www/fdb/includes/menu.inc on line 593 <<

    Drush command terminated abnormally due to an unrecoverable error <<

    Error: Call to undefined  function node_load() in /data/www/fdb/includes/menu.inc on line 593 <<

Then I did 'drush dl registry_rebuild' and 'drush rr'.

Unfortunately I couldn't login. So I created a one time login which works.

I see all nodes, users, views, rules etc.

But after logging out I cannot login regularly.

Then I created a new password for user admin_ip via '/scripts/.create-new-pwd newpwd' and put the hash into the users database.

Finally I tried to login again but it didn't work.

How would you start to see what's wrong?

Here are few tips:

make sure your Drupal core has all the files in the right place (especially node module),
make sure your imported database is in UTF-8 format,
upgrade your Drupal core to the latest version (drush fr && drush up drupal)
clear all your caches (drush -y cc all), including your memcached (killall memcached),
rebuild your registry by using Registry Rebuild (which you already did),
if you're using modules which are implementing drupal_bootstrap() (such as Secure Site), disable them,
try disabling your PHP cache engines (such as XCache, Zend optimizer) to see if that's the problem,
test it on different environment/machine,
eventually restore your database from the point where it was working before


Get id of selected option in Drupal Forms API I have a select element in my form.

function myid_print_user_page_form($form, &$form_state)
{
    $form = array();
    $form['options'] = array(
        '#type' => 'select',
        '#options' => array(
            0 => t('All'),
            1 => t("Printed ID's"),
            2 => t("Unprinted ID's"),
        ),
        '#default_value' => 0,
        '#ajax' => array(
            'callback' => 'myid_print_all_submitted_id_callback',
            'wrapper' => 'myid_print_search_idnumber_wrapper',
        ),
    );

    $form['myid_print_search_idnumber_wrapper'] = array(
       '#type' => 'item',
       '#markup' => '

'
    );
    return $form;
}

I'm stuck in the callback function. It always return 1, even though I selected other options.

function myid_print_all_submitted_id_callback($form, $form_state)
{
    return $form_state['values']['options'];
}

Where am I missing?

You can use this code

function myid_print_user_page_form($form, &$form_state)
{
    $form = array();
    $form['options'] = array(
        '#type' => 'select',
        '#options' => array(
            0 => t('All'),
            1 => t("Printed ID's"),
            2 => t("Unprinted ID's"),
        ),
        '#default_value' => 0,
        '#ajax' => array(
            'callback' => 'myid_print_all_submitted_id_callback',
            'wrapper' => 'myid_print_search_idnumber_wrapper',
        ),
    );

    $form['myid_print_search_idnumber_wrapper'] = array(
       '#type' => 'item',
    // When the form is rebuilt during ajax processing, the $selected variable
    // will now have the new value and so the options will change.
       '#markup' => isset($form_state['values']['options']) ? $form_state['values']['options'] : '',
       '#prefix' => '
',
       '#suffix' => '
',
    );
    return $form;
}
function myid_print_all_submitted_id_callback($form, $form_state){
// rebuild the form
    return $form['myid_print_search_idnumber_wrapper'];
}


Create OG group on registration I have different registration pages for different user roles in drupal, for some users i would like them to be able to create an OG group when there accounts is created.

I have a field in the registration form for group name which i would like to be used in creating the new group.

Im sure this is something you can do with rules but i cant seem to find any good tutorials on seeting it up any help appreciated

Use this module http://drupal.org/project/uc_node_checkout

You can assign a node/content type to a product in uber cart, so once a visitor has selected a product in the cart they can create an og group node.

for my needs I then just used rules to make the group unpublished until the visitor had a fully paid for the role in the ubercrt


How do I programmatically retrieve the inputs from a form? I am implementing a hook_form_alter in my custom module and I want to get all the inputs from the $form variable.

So, if for example there is a textarea, a radio button and a checkbox, I want to grab these elements and put them in a clean array for later use. What I basically want to do down the road is create a dropdown list and have these inputs as the options in the list.

Is this a clean way to do that through the FAPI?

You can use the element_children() function to grab all of the child elements within a particular element (including a form element). The thing with Drupal forms is that often all elements are not on the same level of the array, so you'll need to make a recursive function to get them all reliably. This is untested but should give you a place to start:

function _element_children_recursive(&$element) {
  $names = array();

  foreach (element_children($element) as $element_key) {
    $names[] = $element_key;
    $names = array_merge($names, _element_children_recursive($element[$element_key]));
  }

  return $names;
}

$all_element_names = _element_children_recursive($form);

There's even one further caveat to this...since form elements can be on different levels you might well end up with two identically named keys. This is perfectly valid in Drupal so you'll probably want to do a bit of checking in the recursive function to avoid duplicates.


Twig template suggestions for paths such as page--node--page-url using D8, I'd like a twig template for a page I've created based off the path of the page and not node %. I look in my twig suggestions and all I see are:

page--node--8.html.twig
page--node--%.html.twig
page--node.html.twig
page.html.twig

As template suggestions. However, as I'm working in multiple environments and don't know what the node number will be when I actually create this page I'd like to just base it off the path I've set for the page which is '404-error'. Anyone know how to do that?

I'm imagining something like page--node--404-error.html.twig

However that doesn't seem to work (I tried it).

You can add suggestions for the page template in a hook:

mytheme.theme:

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function mytheme_theme_suggestions_page_alter(&$suggestions, $variables) {
  $path = \Drupal::requestStack()->getCurrentRequest()->getPathInfo();
  if ($path != '/') {
    $path = trim($path, '/');
    $arg = str_replace(["/", '-'], ['_', '_'], $path);
    $suggestions[] = 'page__' . $arg;
  }
}

This is an example how to add a suggestion with the path for any page. You can narrow it down to the pages you are interested in and if necessary check for paths that are too long.


Multiple form on module page i created a module. I created a form and implemented it on the page:

function tudakozo_menu() {

  $items['tudakozo'] = array(
    'title' => t('Tudakozo'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('tudakozo_nevszerint_form'),
    'access callback' => TRUE,
  );

  return $items;
}

I would like to have an another form on this

Instead of using drupal_get_form as the page callback, you can specify a custom callback and build the forms there.  An implementation in Drupal 6 would look similar to the following:

function tudakozo_menu() {

  $items['tudakozo'] = array(
    'title' => t('Tudakozo'),
    'page callback' => 'tudakozo_page_callback',
    'access callback' => TRUE,
  );

  return $items;
}

function tudakozo_page_callback() {
  $output = '';

  // Render your two forms here.
  $output .= drupal_get_form('tudakozo_nevszerint_form');
  $output .= drupal_get_form('tudakozo_second_form');

  return $output;
}

The only difference in Drupal 7 would be working with a render array as opposed to a string in the custom page callback similar to the code below:

function tudakozo_page_callback() {
  $build = array();

  // Render your two forms here.
  $build['form_one'] = drupal_get_form('tudakozo_nevszerint_form');
  $build['form_two'] = drupal_get_form('tudakozo_second_form');

  return $build;
}


Filtering a date field in views I have set up a view that shows users a set of nodes for an athletic season that runs September through August.  Each node has a field called Start Date. I would like to filter this start date using the year of the season, i.e. 2012 for the 2012-2013 season.  I've looked into contextual filters but I don't think this is going to work for me, as I don't see a way to provide a range (say 2012-09-01 through 2013-08-31). Will this require a custom module and if so, where can I get some concise instructions on hooking that custom module in with the specific view.  Most of the documentation I read gives a quick code snippet with no specifics on where that snippet is supposed to go.

Is the "Start Date" field a date field? Or is it a text (or some other type of field)?

If it's an actual date field, you can configure this behavior through the UI.

Add the field as a filter in the Filters section. Then you should see an Is between operator radio button. Select that and enter your range in the Value section. Screenshot:

You need to activate the date_views module to see the filters appearing in the Views module interface.


altering user tag input I have a content type that allows users to make their own tags, for me to be able to properly search through these tags I need them to be in a specific format.

Rather than burden users with my strict formatting guideline I would like to just alter the input to my format before creating the tag. Is such a thing possible?

Implement  hook_taxonomy_term_presave  in a custom module and alter the terms according using PHP's string manipulation functions.


Adding a button or text link to a content's view (Drupal 7) I would like to add a link or a button to my content's main view (I.E. ?q=node/120) that will redirect the user to a java applet that the node already has a reference to.

Is there an easy way to add such a button or link?

I was able to do this in hook_node_view.


How do I change the views handler type for a field from string to int? I'm using Views 3 on Drupal 7 with the Computed Field module.  My Computed Field calculates an int, and it is stored in the DB as an int, but Views is using the string handler by default.
How can I change the handler for one specific field from string to int?
This is the code I'm using in a custom module in mymodule.views.inc.
function mymodule_views_data_alter(&$data) {
  dpm($data);
  $data['user']['field_my_custom_field']['field']['handler'] = 'views_handler_field_numeric';
}

However, in my view, the filter choices are still:

Is equal to
Is not equal to
Contains
Contains any word
Starts with
etc.

These are the string options; I need them to be the choices for int (greater than, less than, etc.)

You "should" just need to override the filter handler for the field, e.g.

function mymodule_views_data_alter(&$data) {
  $data['user']['field_my_custom_field']['filter']['handler'] = 'views_handler_filter_numeric';
}

Untested, use with caution!


Modify the store for hundreds of products I have a drupal 8 commerce website with 2 stores (store1 and store2). Most of the products belong to both stores but there are a few that only belong to either one.

Now, I need all the products (hundreds) to belong to a new store(store3) that i created on the website.

Obviously, I will not manually edit each product to assign it to the new store but what i was looking into is to write a SQL script (given that it's a one time thing) that will update the products in the DB. Soon after that i found out that it's more than the commerce_product__stores table that i would need to update, i would also have to update the commerce_promotion__stores and commerce_shipping_method__stores tables. and to make the things more complicated, some tables like the commerce_product__stores need its values updated where as with the other ones, i need to add the entries.

What better, Drupal way, ways of doing it are out there?
Another option that i found was talking about exporting all the products with the views data export module, modify the data and import it back in with the Feeds module but the author was complaining about some issues that were still not resolved in D8...

Any suggestions?

There are two methods that are the "Drupal" way.

One is to write a PHP script that changes the products as needed.  You would write a loop, load the products, update, and then save them.  You then can the execute this script with drush as drush scr whatever.foo.  This will bootstrap Drupal, and then execute the script in the context of a running Drupal install.  Just keep in mind that loading a lot of entities in the same process can cause problems with the static cache getting too big.  There are other questions here about how to handle this.

The second is to write a hook_update_N() function, and put it in a custom module.  This is essentially the same as the standalone script.  If you go with this approach, you can batch the changes (say update 50 at a time).  You can then run the update from the UI or with drush updb.  This approach works a little better with database backups / restores, and also works nicely if you have a dev -> staging -> production environment, especially if it also pulls the database backwards at each step and automatically runs updates.


How to name views-exposed-form.tpl.php per views display I tried views-exposed-form--"view_name"--"display_name".tpl.php but it doesn't work. Is it possible to make a template file which applies only to the exposed filter of a views display?

I have two exposed filters from two different displays within a same view, and I would like to theme the two exposed filters differently by two template files.

For Drupal 7, you can use views-exposed-form--view_name--display_name.tpl.php (Replace underscores with dashes in view name and display name.)

It worked for me that way.


Can't get CKEditor to work on Drupal 7.8 I've tried both the CKEditor module, as well as the WYSIWYG module (with CKEditor library installed). I've configured it all correctly and it should work, but it doesnt. I've also tried changing the CSS options but still nothing.

I'm getting "r is undefined" in the console, but only if I change the text format option underneath where the editor should be.

I'm currently working off localhost - might that be an issue?

Well I finally got it working...

I installed CKEditor module, CKEditor library, and then had to hack the CKEditor library folder by creating new subdirectories with the appropriate files (it was looking for the skin and language files in the wrong directory within the CKEditor library folder)...

I'm using the latest version of everything - why is this happening? I would have thought since this happened to me its happening to everyone else as well!

If anyone else has this problem, ensure you have these files in your /modules/ckeditor/ckeditor/ folder:
"lang/en-gb.js"
"skins/kama/images/sprites.png"
"skins/kama/editor.css"
"skins/kama/icons.png"

All these files are just in the root folder by default for some reason.


Analyzing slow mysql querries Our Drupal site has recently started to get much more traffic and often pegs the CPU and memory when we have 50-100 active connections. We have 8cpus and 16GB of RAM. I notice that when the cpu is pegged mysql is by far the largest consumer so I decided to look at the mysql-slow.log and found that some queries take over 1 second and I am wondering if this is reasonable. Here is one example:

# Time: 150330 12:01:34
# User@Host: root[root] @ localhost []
# Query_time: 1.131631  Lock_time: 0.000301 Rows_sent: 4  Rows_examined: 151102
SET timestamp=1427738494;
SELECT
  node.nid AS nid,
  node.title AS node_title,
  users_node.name AS users_node_name,
  users_node.uid AS users_node_uid,
  votingapi_cache_node_points_projects_sum.value AS votingapi_cache_node_points_projects_sum_value,
  node.created AS node_created,
  node.changed AS node_changed,
  node_revision.timestamp AS node_revision_timestamp,
  'node' AS field_data_field_screenshot_node_entity_type
FROM node AS node
INNER JOIN users AS users_node
  ON node.uid = users_node.uid
LEFT JOIN votingapi_cache AS votingapi_cache_node_points_projects_sum
  ON node.nid = votingapi_cache_node_points_projects_sum.entity_id
  AND votingapi_cache_node_points_projects_sum.entity_type = 'node'
  AND votingapi_cache_node_points_projects_sum.value_type = 'points'
  AND votingapi_cache_node_points_projects_sum.tag = 'projects'
  AND votingapi_cache_node_points_projects_sum.function = 'sum'
LEFT JOIN votingapi_vote AS votingapi_vote_node_points_vote
  ON node.nid = votingapi_vote_node_points_vote.entity_id
  AND votingapi_vote_node_points_vote.entity_type = 'node'
  AND votingapi_vote_node_points_vote.value_type = 'points'
  AND votingapi_vote_node_points_vote.tag = 'vote'
LEFT JOIN node_revision AS node_revision
  ON node.vid = node_revision.vid
WHERE node.status = '1'
  AND node.type IN ('arcade_project_container')
  AND EXISTS (
    SELECT na.nid AS nid
    FROM node_access AS na
    WHERE na.gid = '0'
    AND na.realm = 'all'
    AND na.grant_view >= '1'
    AND node.nid = na.nid
  )
ORDER BY
  node_created DESC,
  node_changed DESC,
  node_revision_timestamp DESC
LIMIT 4 OFFSET 5800;

This query comes from the front page where I have a view which shows the most recent submissions. Should this query really take 1.13 seconds?

EDIT: Here is a screenshot of the results of running EXPLAIN on this query on phpmyadmin:

Here is the EXPLAIN after switch nid and uid as suggested by mikeytown2:

Add a new index of type index on the node table with these 7 columns; I would label it "status_type_uid_nid_vid_created_changed"

status, type, uid, nid, vid, created, changed

Once you have done that run explain again; odds are the index will need to be re-ordered or another table will need to have an index added to it.

Try #2. Flip nid & uid.

status_type_nid_uid_vid_created_changed

status, type, nid, uid, vid, created, changed


Drupal 7 Tokens in Field Help text In Drupal 7, I've created a content type, with a textfield. In the field settings, I'm invited to add some "Help text", and the description for this specifically says "This field supports tokens".

However, I'm finding that the tokens are never replaced with actual values. The token just displays literally under the form field.

I've also been unsuccessful when testing with "simpler" tokens than "current-date". What am I missing?

Tokens in the "Help text" field work, at least for the taxonomy term reference field.

I tried adding "[current-date:long] [current-user:ip-address]" to the help text of a taxonomy reference field, and I obtained the following.

Tokens didn't work for the image field, though.

I have also tried with [current-date:custom:e], and it worked.

What confused me is that I didn't notice the summary of available tokens I normally expect from the Token module. It doesn't appear for the taxonomy reference field, but it appears for the image field, for which the tokens are not replaced.


hook_form_alter() Ajax suffix replace I'm trying to rewrite a form item's suffix on an AJAX callback and it keeps prepending the first choice and then doing nothing else. My code:
function my_dashboard_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){
  if($form_id == 'node_job_listing_owner_job_form_form'){
    $tid = $form_state->getValue('field_job_description')[0]['target_id'];
    if(empty($tid)){
      $tid = $form['field_job_description']['widget']['#default_value'][0];
    }
    $link = null;
    if(!empty($tid)){
      $link_url = \Drupal\Core\Url::fromRoute('entity.taxonomy_term.canonical', [
        'taxonomy_term' => $tid
      ], [
        'attributes' => [
          'class' => ['use-ajax'],
          'data-dialog-type' => 'dialog',
          'data-dialog-options' => \Drupal\Component\Serialization\Json::encode(['width' => 420]),
          'data-dialog-renderer' => 'off_canvas',
        ],
      ]);
      $link = \Drupal::l('Preview Job Description...'.$tid, $link_url);
    }

    $form['field_job_description']['#suffix'] = $link;
    $form['field_job_description']['widget']['#ajax'] = [
      'callback' => 'updateJobDescriptionPreviewLink',
      'wrapper' => 'edit-field-job-description-wrapper',
      'event' => 'change',
    ];
  }
}

function updateJobDescriptionPreviewLink(&$form, \Drupal\Core\Form\FormStateInterface $form_state){
  return $form['field_job_description'];
}

Basically, I'm trying to put a link below the "Job Description" drop down to preview the description of that term. I have the term id appended to the link text temporarily so I can see what happens. When I edit an existing node, it renders the link correctly the first time (i.e. "Preview Job Description...102"). But then, if I select a different option, it prepends another link to the existing suffix (i.e. "Preview Job Description...99 Preview Job Description...102"). Both links work correctly, but obviously two links aren't what I want. And also after that, it won't change anymore no matter what I select.
I feel like there's something simple I'm overlooking, but I confess Drupal AJAX has always confused me somewhat. Any ideas? Thanks!

I think the estrange behaviour it's because the suffix is after and not inside the wrapper, thus not get replaced and since you're ajaxly returning $form['field_job_description']; which contains the wrapper; thus, you end up with two same ID wrappers and fails on the second run.
Move the link generation to a function.
Here is an alternative AJAX approach where we target the link wrapper rather than the form wrapper.
function my_dashboard_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){
  if($form_id == 'node_job_listing_owner_job_form_form'){
    $link = _my_dashboard_get_term_link($form, $form_state);
    $form['field_job_description']['#suffix'] = '
' . $link . '
'; // wrap link
    $form['field_job_description']['widget']['#ajax'] = [ // removed 'wrapper' =>
      'callback' => 'updateJobDescriptionPreviewLink',
      'event' => 'change',
    ];
  }
}

function updateJobDescriptionPreviewLink(&$form, \Drupal\Core\Form\FormStateInterface $form_state){
  $link = _my_dashboard_get_term_link($form, $form_state);
  $response = new \Drupal\Core\Ajax\AjaxResponse();
  $response->addCommand(new \Drupal\Core\Ajax\HtmlCommand(".term-link", $link));
  return $response;
}

function _my_dashboard_get_term_link(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $tid = $form_state->getValue('field_job_description')[0]['target_id'];
  if(empty($tid)){
    $tid = $form['field_job_description']['widget']['#default_value'][0];
  }
  $link = null;
  if(!empty($tid)){
    $link_url = \Drupal\Core\Url::fromRoute('entity.taxonomy_term.canonical', [
      'taxonomy_term' => $tid
    ], [
      'attributes' => [
        'class' => ['use-ajax'],
        'data-dialog-type' => 'dialog',
        'data-dialog-options' => \Drupal\Component\Serialization\Json::encode(['width' => 420]),
        'data-dialog-renderer' => 'off_canvas',
      ],
    ]);
    $link = \Drupal::l('Preview Job Description...'.$tid, $link_url);
    return $link;
  }
}


How to create a field which contains the entity created date I need to create a field which contains the date an entity/node was created. I know some people achieve this by using a bit of code in their template, but I need this to be a real, accessible field I can use on the entity/node display, as well as in Views (sort, filter, etc). Additionally I would like a field for the last modified date.

How would I do this properly in Drupal?

We did create a bit of SQL that we ran in PHPMyAdmin (it was a one time script, we need to schedule it to be run daily), but I have a feeling I could be doing something in Drupal. Am I wrong?

You could use the Computed Field module to display the date on your page. Create a field and set the php code to display the date in readable format.

Call your field something like 'Date created' and enter code like the following under Computed Code (PHP):

$entity_field[0]['value'] =date("Y/m/d",$entity->created);

Do not store the value in the database. You do not need to derive the value for views as the created date is available to views directly.

The last modified date is available as well as $entity->changed.

As an alternative, you might have a look at the Node Display Fields module, which has several widgets to display the type of information you are looking for.


Show total amount of results for an exposed filter Found this answer, show amount of results for exposed filter and this answer.

However, my issue is that i'm trying find the total number of results after executing an exposed filter.

Views calc looks like it only returns the count of results from a single result not an exposed filter result. Or if i'm wrong please correct me.

Anyways, the question: How do you find the total number of results from an exposed filter?

Desired result:

Complete an exposed result form
return "x number of results found" as a block

I'm using Views 3.7 in Drupal 7 right now and finally found out you simply can add a result summary Global: Result summary to the header/footer.


Get a particular module's information programmatically Is there any function to retrieve all the hook used by a particular
module and also
A function to return all menu links (along with its description) created by
    a particular module

  I looked into module_hook and module_implements but both
  were used to find whether a particular hook is used in a module. But
  what I need is vice versa.

I need it because configuration options for a particular module can be easily found by getting menu links in a page as a overview.

No - as you've already discovered, the association is the other way around (i.e. a list of modules against each hook, not a list of hooks against each module). Nothing in Drupal's core needs to know a list of all hooks a module implements, so no such function exists. As there's no requirement for a module to declare which hooks it provides (though they can through hook_hook_info()), such a function would be difficult or impossible to implement reliably.

If you can trust that all the modules you have installed are well documented, you could write something that looks in the comment block of each function for Implements hook_, and build a list yourself that way. Or you could compile a list of all the hooks you're interested in knowing about, run each of them through module_implements, and build your list.
Assuming by "menu link" you mean a path provided by a module that has the default menu type, and will subsequently appear in a menu automatically, something like this will do it for all modules:

$menu_items = array();
foreach (module_implements('menu') as $module) {
  $func = $module . '_menu';
  if (function_exists($func)) {
    foreach ($func() as $router_path => $item) {
      if ($item['type'] == MENU_NORMAL_ITEM) {
        $menu_items[$module][$router_path] = $item['title'];
      }
    }
  }
}

That will probably need to be be tweaked for your requirements.


Adaptivetheme Subtheme usage I'm using Adaptivetheme with the pixture_reloaded sub-theme. Keep in mind, it's structured as:

Adaptivetheme
  -Adaptivetheme_Subtheme
      -Pixture_Reloaded

I'm creating custom edits to template.php to add a node preprocess which creates a custom variable for me, and then editing node.tpl.php to add my variable to the output.

Editing adaptivetheme_subtheme node.tpl.php and adaptivetheme_subtheme node preprocessor gives me the output I want. I understand that the best practice is to edit the sub-theme files...

In my case is the "sub-theme files" the adaptivetheme_subtheme files or the pixture_reloaded files?

Pixture_reloaded itself doesn't have a node.tpl.php file, so I've tried copying both the one from adaptivetheme and adaptivetheme_subtheme to the pixture_reloaded directory, but it's like it never reads the file.

EDIT:

  Pixture_reloaded itself doesn't have a node.tpl.php file, so I've
  tried copying both the one from adaptivetheme and
  adaptivetheme_subtheme to the pixture_reloaded directory...

I had shutdown my server yesterday, and after bringing it back up, my output was correct.

I had cleared out the cache in the backend of the site... shouldn't that have done it for me?

To answer my own question, pixture_reloaded is the sub-theme I want to edit, as that is the last child/sub theme in the hierarchy.


Full website translate in multilingual website we are developing a multilingual site.
We have done all setting like installing Internationalizatio,Entity Translation and enabling local and content translation modules etc.

but there are some content which no get translate on choosing particular language, We want to translate my full website content on choosing particular language.
How can I perform full transable website in multilingual site?

You need to enable the Content Translation module, and then, in the content type settings, set the content types to translatable. Then, you can translate content. You do that by creating translations though, in the ui, not in the interface translation ui. So, you translate content, not strings.

https://www.drupal.org/documentation/modules/translation


How do you 301 redirect links in Drupal via the .htaccess modredirect rules to keep spidered links? I am migrating a site to a new domain and I would like to do a 301 redirect via the .htaccess file to create a redirect rule. I have over a 1000 dynamic links generated via views so this isn't do able with a redirect module as easily. I just want to get an example modrewrite rule to put in my .htaccess file.

Also have a look at the Redirect module. Managing redirects in the database might have some advantages over putting them in a .htaccess file.


menu item  does not get class expanded nor active-trail when at homepage I have a menu which has a link to the homepage in it.

This link to the homepage has subItems.
I was hoping for the menu item to expand and show the links of the lower lvl when i was at the homepage.

This does not happen.
It does expand when i'm on one of the pages of the links of the lower lvl.

Is there any way i can expand this menu item when on the frontpage?

version:
 - drupal 7.14
 - Menu   7.14

Go to admin/structure/menu/manage/[your-menu-name] and Enable the show as expanded checkbox in your parent menu item settings.


Why is drupal not changing the value when renderd after value change in preprocessor? I wrote a preprocessor for one of my views but when i change the title value the value in my view keeps the same! But dpm show the right modified title. Why is that...do i have to save something somewhere?

function mytheme_preprocess_views_view(&$vars) {
    if (isset($vars['view']->name)) {
        $function = 'mytheme_preprocess_views_view__'.$vars['view']->name;
        if (function_exists($function)) {
            $function($vars);
        }
    }

function mytheme_preprocess_views_view__myviewname($vars) {
    //alter here that specific view
    $vars['view']->result[0]->field_field_title[0]['raw']['value']="Newtitle" ;
    dpm( $vars['view']->result[0]->field_field_title[0]['raw']['value']);

}

You need to pass $vars in by reference:

function mytheme_preprocess_views_view__myviewname(&$vars) {


How to create a link in my view of users to perform an operation like Active or Block? I am using Views to create a view for user management, which looks like in the image below:

How to create an "Active" or "Block" link in my view which performs an operation for the selected user like so:

When I click on "Active" in the Operations column, then the user should be active.
When I click on "Block" in the Operations column, then the user should be blocked.

Note: Views Bulk Operations (VBO) is not working. Refer to the image below. When l select all users in my view results and select "Block current user" as theoperation, then the users are not blocked. I have unstalled the VBO module and re-installed it again. And I also gave permission "user block" to that role. But nothing solved my issue.

Have a look at the Rules Link module. Some details from its project page:

  This module lets you create links which trigger arbitrary functionality with the help of Rules.

  Features:

  Attach the link to any entities.
  Show the link only for certain bundles.
  Narrow the entities on which the link will be shown using the visibility conditions.
  The links are usually displayed using Views.
  For entities that can be displayed, the links can be shown on node view.
  Supports an arbitrary number of additional Rules parameters for passing context via Views.
  3 types of links: Javascript, Normal and Confirmation form links.
  Use individual permissions for each link.

Some more details (from its README.txt):

  To create a new link go to admin/config/workflow/rules_links and click on "Add rules link". Enter the title of your link and set all the settings. After clicking on the "Save Rules Link" button, the module will generate a new And- and Rules-Set and their forms will be embedded into the rules link editing form.

  The And-Sets are called Visibility Conditions and will define when to render the links. The Rules set is the rule, that will be triggered on clicking the rule. Additionally Rules Links also generates access permission for each link, which you'll have to set in admin/people/permissions.

  The best way to display the links is currently using views. Rules Links link will create a Views field for each link, using the title of the link as title for the field. So if you have link for nodes with the delete 'Delete node', you'll find the Views field under name 'Content: Delete node'.

  Alternatively you can use render the links directly in the entities that can be displayed, using the option 'Show link in entity' in the Rules Links settings.

  Note that this will not work for links were the parameters have multiple
  paramaters.

  If you would like to render a link yourself in a theme or in a module, than use the function rules_link_render_link().

Note the "The best way to display the links is currently using views" in the above quoted text, which is pretty close to what you're asking for.

PS: I'm assuming this question is about D7.


Is it possible to POST values to next page with a Drupal URL? I have the following link that works if I link to an external page outside Drupal. However, when I place the same code in a Drupal page that is on orangeEDIT, and change this URL to point to the Drupal location, it says the page cannot be found.

<a href="http://host/drupal1/?q=node/17?orange_id=<?= $row['orange_id']; ?>">Edit

I should probably use the Form API for this, as it is a link that allows a form to be edited, but it seems a way too complicated, compared to the PHP solution.

To prepare links in Drupal, use the l() function:

$options = array('query' => array('orange_id' => $row['orange_id']));
$link = l('Edit', 'node/17', $options);

You can also add 'absolute' => TRUE to your options array to get the full URL; full options are on the docs page.

Using l() you can ensure that your URL is valid at all times.


Link field type displaying '&' as '&' When I have a Link title field populated with '&' it will be displayed as '&' when rendered.

I have done a fair share of google searching but haven't quite nailed it down.

I was thinking this was a start in the right direction https://stackoverflow.com/a/5019423

Drupal 7.19 with a zen subtheme

visual -

rendered http://imgur.com/JrBVRAx

on form http://imgur.com/nL0Xz6H

Any hints?

Keep in mind l() passes the text through check_plain which escapes the HTML characters for display.

So, there's no need to double escape the link with another check_plain later.

Pass the raw text, including the single "&" through as the link text and output it as such, that way it should be fine.


Log where permissions are being refused? When not logged in as admin my view is returning no results. I believe it to be a permissions issue but everything appears to be configured correctly.

Is there a way to get a log of what permissions are being attempted and then rejected, and by what?

No. Permissions usually are checked by a function call to user_access and for performance reasons there is no way to override that (not that D6 was so big on overrides like D7 is -- still that function can't be overridden in D7). You can set use devel to see the query if one is run or Views can display the query. As a last resort, you can add error_log(4, $string); into user_access itself to send the permissions into Apache error log or similar.

Note that it can be a node access issue, in this case the query log will help you.


Views-based page access? I need to restrict a View-generated page to authorized users only. (D7.9, Views 3)

I generally want to hide the Drupal's built-in user login block, but have the login form appear when a guest tries to access that page. I have been messing around with Fancy Login (which is supposed to appear whenever there is a need to authenticate), and also with roles and permissions, esp. with "Views: Bypass views access control". Somehow I cannot get the desired result - the page is either fully accessible, or an Access denied page comes up.

Anyone been through a similar challenge?

Artur

Just configure your "Default 403 (access denied) page" to "user/login". It's under "configuration / system / site information"


How to add Facebook share/like icon in Blog Entry header? I want to add a header to my "blog entry" content type that will have a couple icons for sharing with Facebook, Twitter, email, and Google +1.

How can I do this?

I currently have the icons in a block in the sidebar.

The AddToAny module lets you do this.  You choose to have the button show in the content, and then use a negative weight to float the button to the top of your content (aka the header section).


Print the current source node of the comment I wold like to have some clues to search.
Out of the box Drupal let you see the original article or page when you write a comment and click "preview". I search everywhere and I haven't a clue about how to fix the problem when I make a custom tpl for the coment-form.tpl.php I lost the part where I see the original source of the subject I'm posting. I just see the comment form. I think is not comment.tpl or comment-wrapper.tpl I also make a custom module but no luck.

The node id for the comment is stored in:

$comment->nid

e.g, in the template, to print out the node, you could:

if (isset($comment->nid)) {
  print render(node_view(node_load($comment->nid)));
}

You could also add it as a template variable in preprocess function.

See node_view for more options


Views hook gets ignored after 1 execution I registered this hook in my module:

function MYMODULE_views_pre_render(\Drupal\views\ViewExecutable $view) {
        die('hello world');
}

I cleared the caches, and ran a view.

Output is "hello world" as expected.

I refreshed the view, and my pre_render plugin is completely ignored (view is shown normally).

What's happening?

Solution is to put the code in a file called MYMODULE.views_execution.inc.
I was using MYMODULE.views.inc


How to customize the node edit form? I need to customize the access to details like 'Publishing options', 'menusettings', 'authoring information' etc while the user is editing the node.

These options should be shown only if the admin has allowed the users to view those. I Have searched for this, but unfortunately found no answers for Drupal 8.

You can use Simplify

  Simplify allows particular fields to be hidden from the user
  interface. This helps to de-clutter forms and present a more
  user-friendly experience to content editors.

Enable the module, then go to People >> Permissions and check mark View hidden fields for the user role you want to allow to see them.


Why won't taxonomy list sort alphabetically? Running Drupal 7.28, I've created a taxonomy vocab 'care centers' with a list of terms with care center names 'Atlanta''Boston''Cincinnati' 'Detroit' etc. Problem: Care centers were entered in random order 'Detroit' 'Boston' 'Atlanta' 'Cincinnati', when I click on 'Reset to Alphabetical' they reorder alphabetically, but when I save, they go back to order entered. People self-select their care center from a drop down list populated by the taxonomy, would help if it were displayed alphabetical.

How do I get the list to sort and display alphabetical?

Have you already tried with "Show row weights", it looks like a javascript problem; adding the weight manually will give you some hint about that problem.


What is the difference between 'Groups audience' and 'Groups content visibility' in Organic Groups Access? I am trying to set up Organic Groups Access for an existing site where I want to add gated content. I was watching this tutorial about setting it up, and it briefly addressed it. They said that 'audience' is better for sites where you have a bunch of existing nodes. Can someone give me a more technical answer, indicating what exactly the difference is?

Group audience = which group(s) content was posted to.

Group content visibility = who can see the posted content, only group members or all site users.

Do contact the author directly to ask them and/or let them know that the tutorial could be improved.


Search Including Node Taxonomy Field I have a content type with a taxonomy field on it that needs to be included in the standard search of Drupal 7.

Is there a way to do this or do I have to set up a view to override the standard search?

If I do have to use a view, how can I set it up to allow searching all fields on a node from one text field in the search form?

I thought Drupal did this with it standard search but it doesn't seem to.

If you choose "Node" as an active search module it will index the full node including taxonomy terms:

Here you can see the tag "bros" is returned in the core search:

Are you sure that the site is fully indexed?


Panels in-place editor shortcut won't appear from gear wheel I use Drupal 7.34, and Panels module suit version 3.4.7.

The Panels in-place editor shortcut refuses to show up after I click on the gear wheel of a Mini-Panel...

Tried to reinstall, didn't help.
Tried to change Render mode from Default to "In-place editor" in the settings page. Didn't help.
Tried to clear cache afterwards. Didn't help.
No serious solution appeared in a Google search...

Is it bug?... What else can cause it not to appear?

Tried to reproduce this with Drupal 7.34 and Panels 7.x-3.4. I created a page, selected In-Place editor for Renderer under General tab of the Panels edit page, added some blocks and added a Mini panel with blocks in it, went to the page and all the gear icons work. Maybe some JS issue is causing this?

Update

Based on checks, I think Contextual links displays the edit link for the "renderer" only. Ex. if Blocks is displaying the Mini-panel, the contextual link module displays the "Configure block" link. Same for Panels with mini-panels rendered inside it. So that's the explanation why the "Edit mini-panel" link isn't displayed under the "gear" icon.

NOTE: Please correct me if I'm wrong with this analogy though because this is just based on observation

Solution 1: Using the Custom Contextual Links. Though this uses Tokens it doesn't get the mini-panel's name so if you had 10 mini-panels you should create 10 CCLs also w/c would be quite tedious though but of course if it's needed, nothing is tedious I guess? :)

Solution 2: Creating a custom module that would check each rendered "block" in a page is a mini-panel and if it is, display both the "renderer's" link and add the mini-panels link.


Active menu for a node with two different terms I have a node which has two different terms. The problem is when I'm on such a node, the active menu and breadcrumbs point only to one of the terms. How can I find a solution to this problem without duplicate that node for each term. Or if you have an idea how to duplicate that node but they will be edited in one place that's is also a good solution.
Thanks!

You can adjust the breadcrumb using hook_menu_breadcrumb_alter() in your custom module. There's an answer about proper using of hook_menu_breadcrumb_alter() similar to your use case and with helpful references at https://drupal.stackexchange.com/a/49952/10176


Problem using ColorBox with Media Galllery I want to create photo gallery using the Media Gallery module. One of the requirements given is to unpack the ColorBox jQuery plugin in sites/all/libraries.

I downloaded the file colorbox-master.zip and extracted it in sites/all/libraries so the path of colorbox is sites/all/libraries/colorbox-master

I am able to create gallery but effect of the ColorBox is not visible. What do I have to do to make the gallery photo show up in the ColorBox?

Actually all you should need to do is change... Well, you'll need to change two things actually:

Rename sites/all/library to sites/all/libraries
Rename colorbox-master to colorbox

The final output should look like this: sites/all/libraries/colorbox

And don't forget to flush the caches after you make the changes, just to make sure the system recognizes them. ;)

Hope that helps... :)


Multisites with shared files folder – good or bad idea? I'm lacking experience on the following issue and unfortunately it isn't documented explicitly. I'ld like to have a shared files folder for a handful of multi-sites. As those sites all represent sub-organisations of one and the same parent organisation it should be possible that all of them have access to the same files in one certain files subdirectory using a shared file manager like IMCE.

The only concrete clue I found is on https://www.drupal.org/node/53705. But this is about Drupal 5.

  A /files directory could easily be shared across two domains without
  being shared across the remaining domains.

I wildly guess this didn't change much for following versions. But, have anybody ever tried it this way in production? Would you have any concerns doing it this way? What else could I consider to do instead?

As far as I've tested it right now this seems to work. Also images and files uploaded to image and file fields on site A stayed in the shared files folder even after multiple cron runs on site B and site C (as Clive noted to have a look at the file_usage logic).

I also then deleted the files and images from site A's nodes and run site A's cron multiple times. Still the files stayed there. But this simply might be a permission issue, maybe.

This should not work. Managed files should be automatically removed once there are no more entries in the file_usage table for them. I see you say that it's not happening on your setup, but maybe that's a permission or some other issue. That's not how it's supposed to work.

I'm curious how you plan on this working, in any case. If you're using file fields, then Sites B and C would have no way to know that you uploaded a file to Site A, so how it is useful? You say that you're using a file manager. Is it like IMCE or something where you are just browsing the files by directory? If you upload a file through something like that, it wouldn't get an entry in the files_managed table, so it would not be automatically deleted. That would make sense.


Commerce order either stays as pending or grants double to customer I have 2 rules to handle orders of credits on my site.

The first rule changes the order status to Completed if the order is no longer a cart.
The second rule grants credits to the order owner using a loop.

The problem is that the credits are granted twice.

In the user's orders page, the order appears twice with the same ID. But it only appears once in the admin orders page.
If I omit the first rule and change the order status manually it works fine. In this case, it is still using the same loop. Can anyone think why this might be? Here are the rules:

{ "rules_order_paid_in_full_order_state_to_completed" : {
    "LABEL" : "Order paid in full: Order state to Completed",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "1",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "commerce_cart", "commerce_order", "commerce_payment" ],
    "ON" : { "commerce_payment_order_paid_in_full" : [] },
    "IF" : [
      { "NOT commerce_order_is_cart" : { "commerce_order" : [ "commerce_order" ] } }
    ],
    "DO" : [
      { "commerce_order_update_status" : { "commerce_order" : [ "commerce_order" ], "order_status" : "completed" } }
    ]
  }
}

{ "rules_grant_credits" : {
    "LABEL" : "Grant Credits on Completion",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "Checkout", "commerce", "credits" ],
    "REQUIRES" : [ "rules", "entity" ],
    "ON" : { "commerce_order_update" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "commerce-order:state" ], "value" : "completed" } }
    ],
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
          "ITEM" : { "line_item" : "Line Item" },
          "DO" : [
            { "component_rules_grant_credits_if_product_is_credits" : { "line_item" : [ "line_item" ] } }
          ]
        }
      }
    ]
  }
}

I seem to have fixed it by changing the weight of the second rule. I made the weight 10. I'm guessing that having the weight on default (0) was causing the double triggering.


How to get user.field value in node--teaser.twig That's how I getting user.field value for node--full.twig but this code does not work for node--teaser.twig

function MYTHEME_preprocess_node(&$variables) {
    if ($node = \Drupal::routeMatch()->getParameter('node')) {
              $variables['author'] = $node->getOwner()->field_name->value;
    }
}

}

Any ideas?

This bit's the problem:

$node = \Drupal::routeMatch()->getParameter('node')

Even if that returned a value, it would probably be the wrong one; it's not common to render the node as a teaser on its own view page.

As it happens, you don't need to load it yourself for any of the view modes. The node is already in $variables:

function MYTHEME_preprocess_node(&$variables) {
  $variables['author'] = $variables['node']->getOwner()->field_name->value;
}

You may need to add a further check of $variables['node']->getType() if the field is only available to certain content types.


Getting the id of all the elements in a form with errors I am using drupal 6.
All I want is to find the id of each element that has error in form_get_errors.
I am using preprocess to theme the form error section and tried using $vars['form'] with no luck so far.
how can i do that?

You might need to write a custom module for this:

Use hook_form_alter for the specific form and call form_get_errors.
Theme the results of form_get_erros with hook_theme to pass the results back to your theme.


Organic Groups "create post" content link needed with posting content type specific to group Organic groups  7.x-2.6
Entity reference prepopulate    7.x-1.5

Hello, I am trying to create custom "create posting" link for my organic groups. Each Organic Group has its own content posting content types, so when a user visits the panel page for that group the add posting link should be specific to that group.

I have 2 groups: Amigo group, and Authenticated group
I read that target bundles are globally defined for Groups Audience, so I read that you have to add an extra group audience to the Posting content type for your group.  You are then supposed to set the target bundle on the 2nd to match the group content type.
My problem is that when I try to set the "Content Create Links" section in my panel it wants to only set one group audience field, and I have 2 created, one for each group's posting content type.

I recorded images of each part of this problem for ease of understanding.

Here is my Amigo group's posting content type called "Amigo Group Post".
Notice the extra Group's Audience field added to the bottom of the content type. Clicking edit on this allows us to change the settings on this field

Clicking on group audience for Amigo Post takes us to that group audiences configuration page.  Here I am choosing to prepopulate the entity reference.

Here is my panel  for the Organic Groups group. Lets go to the Content Create Links setting page.

Here you can set ONE of the 2 posting content types to be the content type used for new group postings, but I need it to just choose the posting content type by the type of Organic Group. I chose one because I could only choose one.

Looking at the Amigo group page we can see that the create post section is not even showing up.

This is the Authenticated group page.  When viewing this page we do see the create post section, because we had to set one field name for the "content create links" section in the Panel.

Does anyone have any idea how to have the panel choose the content creation link type based on the current group?

I solved this problem. I am not sure if this is the best way. If a better way exists, please do inform me.

To solve this problem I create 2 "Content Create Links" panels within the page.  Each added panel references the group audience specific for the Group Posting content type for the group.
At first both will probably show up, but you have to go to the global "OG Permissions Overview" and for each group type make sure that create content for that Groups posting content type is checked.  For all other type on the page you should not have "Create ____ Content" checked otherwise that content type (a posting type) will also show up as a "Content Create Links" for the wrong posting type for that group.

Do that for each Group type you have created, allowing "Create__(groups post content type) Content" and not having the "Create__(other groups post content type)__ content" for all other group posting content types for the other groups.

Now when I open up "Amigos" groups, I only get "Amigo Group Post" as the posting content type, and NOT "Authenticated Group Post" as well.

If this is too "hacky" I welcome other suggestions on how to configure this properly.


Sending a message to users of a flagged node when it is referenced I have a site where a user can watch a node using the Flag module. Users can also reference the node and I wanted to set up a rule that when the node is referenced, a message is sent to all the flagged users of the original node notifying them that the node was referenced.

Can anyone help with the rule?

I would do this by creating a component of type Rule and calling this component from a separate rule that fires on one of the node save or node is updated events.

First create the component with two parameters of node type and name them "referencing_node" and "referenced_node". Create conditions Content is of type [your content type] for both referencing_node and referenced_node (this will bring in data selectors you need for the flagging user list and replacement patterns to construct your email subject and body). Next add a loop under Actions and choose the data selector for referenced_node:flag [your_flag]:user (Users who flagged the entity with flag [your_flag]) and name the list "flagging_users". Now add an action under your loop System: send mail and in your data selector for the To: field, use [flagging-users:mail] and also build your desired subject and message body from replacement patterns.

Next create a rule that calls your component with React on event: After saving new content of type [your_content_type] (you can also create a separate rule later to react on event After updating existing content however you need to build in conditions to prevent repeat email messages when no new references have been added). Now simply call your component as an action and provide your component's parameter with the variables from node (for "referencing_node") and node:your_reference_field_name (for "referenced_node").

I hope this helps you get the solution you are after.


Prefill taxonomy term reference field while in term page I have a content type A with a required term reference field (vocabulary: category, widget: radios). I would like to accomplish the following:

In every term page (of this specific vobaulary) i will have an "add type A" link.
When the node/add form appears (upon clicking on this link) i want the value of taxonomy term reference field to already be chosen as the category term which corresponds to the specific term page. Ideally i would like the above and also to dissapear this field from the form.

Any help?

There is a module for this and it's called Entity reference prepopulate.


Drupal 8 ajax form load error, context.querySelectorAll is not a function I have created a custom module with ajax call, which are sending render form data that I receive in my ajax prototype in a js file like below.

Drupal.AjaxCommands.prototype.loadCommentFormCommand = function (ajax, response, status) {
    if ($('#comment-form-wrapper').length === 0) {
        $('.wall-posts').prepend(response.html);
          Drupal.attachBehaviors(response.html);
        }
      };

But it's showing me

context.querySelectorAll is not a function

Error.
Does anyone face similar error or have some solutions for this?

The first argument to Drupal.attachBehaviors is an object representing a DOM element, context. You're currently providing it with a string.

In your case the correct code will probably be something like:

Drupal.attachBehaviors($('#comment-form-wrapper').get(0));

You don't pass data to behaviours through the attachBehaviors method, instead stash it somewhere in a global scope and pick it up later.

For example you might choose the window, drupalSettings, or some other object, depending on your general requirements and any other required uses of that HTML data.


unable to create new draft programatically for published node I am using workbench_moderation module.

When I edit the node and save it using node_save($node) it is changing the status of actual node to draft and original node is getting unpublished.

While I want to keep original node as published and want to create new reversion in draft status.

I used below code too but it is not working form me(It is immediately publishing my changes).

node_save($node);
workbench_moderation_moderate($node, 'published');

I've not tested or checked against the source code but I think you should try to node_load after node_save and before workbench_moderation_moderate.

node_save($node);
$saved_node = node_load($node->nid);
workbench_moderation_moderate($saved_node, 'published');


Aegir Drush Drupal 6 I am using the Hosting module through Aegir. I created a module with some extra fields such as "site_name," "fields," and "description," which was done successfully. I want to use these fields on a newly created website. I am using this code in the new site:

function silverpack_config_menu() {
  // Create additional primary menu items
  $items = array(
    array('link_path' => '<front>', 'link_title' => t('Home'), 'weight' => 0),
    array('link_path' => 'node/2', 'link_title' =>t(drush_get_option('site_name')), 'weight' => 6),
    array('link_path' => 'node/3', 'link_title' => t('Contact'), 'weight' => 8),
     array('link_path' => 'node/4', 'link_title' => t('Contact US'), 'weight' => 10),
     array('link_path' => 'node/5', 'link_title' => t('Terms & Conditions'), 'weight' => 10),
     );

  foreach ($items as $item) {
    $item += array(
      'mlid' => 0,
      'module' => 'menu',
      'has_children' => 0,
      'options' => array(
        'attributes' => array(
          'title' => '',
        ),
      ),
      'customized' => 1,
      'original_item' => array(
        'link_title' => '',
        'mlid' => 0,
        'plid' => 0,
        'menu_name' => 'primary-links',
        'weight' => 1,
        'link_path' => '',
        'options' => array(),
        'module' => 'menu',
        'expanded' => 0,
        'hidden' => 0,
        'has_children' => 0,
      ),
      'description' => '',
      'expanded' => 0,
      'parent' => 'primary-links:0',
      'hidden' => 0,
      'plid' => 0,
      'menu_name' => 'primary-links',
    );
    menu_link_save($item);
  }

}

Here, I want to use drush_get_option('site_name'). "site_name" is one of the fields I use in Aegir's Hosting module.

Does anybody have an idea on how to do this?

I see that you have not returned the $items array before exiting hook_menu. I assume it is a typo, but just incase it is not, you need to insert return $items; before the end of the function.

You need to check whether or not Drupal is able to fetch the value returned by drush_get_option().

Can you check in your hook_init(), the value of drush_get_option()?

Something like the following code should work.

function silverpack_config_init(){
  $test_sitename = drush_get_option('site_name');
  dsm($test_sitename);// Install Devel Module to use dsm()
}

Clear the cache, and refresh twice to see if you receive anything back from Drupal. If it is not returning anything, that means either "site_name" is not registered in your database table, or drush is not getting the context properly.


Trying to add CSS to certain pages using a custom module in 7.x I tried following the instructions here: How to override some admin theme CSS rules? and have spent a lot of time and energy googling and iterating this, so I'm turning to the stack exchange community for help.

What I'm trying to do is make some text fields larger when a user tries to edit a page. I'm attempting to do this by writing a custom module that checks if the page's url contains the string edit, and if so, enabling the custom css. The version is drupal 7, and I am working with Pantheon. So far, my module looks like this:

<?php

function admincss_preprocess_html(&$variables) {

$url_string = $_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];

if (strpos($url_string, 'edit') !== FALSE) {

  // reference your current admin theme
    $theme_path = drupal_get_path('theme', 'seven');

  // reference your own stylesheet
    drupal_add_css('sites/all/modules/admincss/css/admincss.css', array('weight' => CSS_THEME));
}

Why isn't my module being used by edit pages? And what, specifically, is the $variables variable referencing?
Thank you in advance!

To add CSS to node edit pages you can use hook_form_alter. Then check the $form_id to localize changes to desired node form(s) and add your call to drupal_add_css().

Example:

function admincss_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == "xxx") {
    drupal_add_css(drupal_get_path('module', 'admincss') . '/css/admincss.css');
  }
}

hook_preprocess_html() Is used to preprocess variables for the html.tpl.php file.


Automatically turning a profile to unpublished if membership is unpaid and v.v I am creating a website for a society, where members pay an annual fee. When members pay for the first time (through ubercart and 2checkout), they automatically receive a user role that enables them to create a member profile. I have set the membership to end a year after they have paid. I have also set up an e-mail reminder to be sent to the member, a week before, reminding them to renew their membership.

I've been playing with rules and relationships in views, unsuccessfully, to answer the following two questions, so I hope someone here has advice.

How do I automatically render the member profile invisible to other members once the payment due date has passed?
Is it possible to automatically render the same invisible profile visible should they renew their membership by paying and if so, how?

How do I automatically render the member profile invisible to other members once the payment due date has passed?

By blocking the user you can stop access on expired user.

  Is it possible to automatically render the same invisible profile visible should they renew their membership by paying and if so, how?

For making it automatic so that a user can activate its account himself, you have to write a custom interface for that. (e.g. A block user tries to login, redirect to a page for user to enter his email address, then process his/her payment against his identity and unblock user)

$user = user_load('mail'=>$email);
user_save($user, array('status' => 1));


How to show 2 instances of the user profile form, displaying different form modes, on the same page? I would like to show 2 instances of the User Profile edit form on the same page.  One form mode only shows the username/password widget with the submit button.  The other form mode only shows the contact information with the submit button.

When I try the following, I get Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException: The "user" entity type did not specify a "user.change_password" form class.  Note that I've changed the form class to change_password as well.

$user = User::loadMultiple([$this->account->id()]);
$form = $this->entityFormBuilder->getForm($user[$this->account->id(), 'change_password']

I asked a similar question regarding custom entities but using that solution would require modifying core files.

Is it possible to do this?

You don't need to modify core files, you can modify the "user" entity type in a hook. This is how you add a form class for the form operation change_password:

mymodule.module

function mymodule_entity_type_build(array &$entity_types) {
  $entity_types['user']->setFormClass('change_password', 'Drupal\user\ProfileForm');
}


Custom theming of login form I have used drupal built in form user_login and user_register_form, Is there a way to control label and textbox field separately, because in my markup each label and text field have different wrapping divs. For example, I have render a particular field like below:

<?php print render($form['name']); ?>

If I apply a wrapping div around this then it is applicable on both label and text field but I have separate divs with different class for each label and field. Is this possible?

If I understand you correctly, what you want to do is override the field template field.tpl.php.

To target specific fields you can rename your version of the file as per the template suggestion options for the field template.


OG groups: How to check if user is a member or not? What code can I use to check if a user is a member of a group?

For the 7.x-2.x branch of Organic Groups you need to use the following code.

og_is_member('node', $gid, 'user', $user)

'node' is the entity type. The function og_is_member requires 4 parameters to return the correct value.


Views merge rows: merge uniques values and show the first one I'm using Views merge rows to grouping rows by some fields, It worked good for me, but in some fields I want to show just the first filled value that means: merge uniques values+use the first value.
View after using VMR

Orginal view

Is there a way to do that using views merge rows? or I have to use an other solution?
Or how I can hide/remove rows which have cycle smaller than the max cycle value  for every every container -see the image above-? I couldn't do it with views filter.

I'll explain my use case below to show the purpose of creating this view:

  The objective was tracking the containers, so I have to show
  containers and there currents and previous places. The container
  pass by a number of positions (in depot, at port of delivery, at port
  of loading...) until being in the vessel( position: on board), or it
  can be in an exceptional position like "reformed". I called the
  passage through those positions from the start to the end a
  "cycle" If the container is on board we have to fill all
  information about previous positions in a form "bill of lading". What
  I did as solution, I created 3 content type : container,position,bill
  of lading. The position content type reference the container and
  contains a select list field "position container" and 10 field
  collection field, every field collection contains a specifics fields
  for  a single position. So for every node position, I fill the field
  container, I select "position container" , I fill the field collection
  fields corresponding to the position selected. For example if I
  created a new position for the container "blk001" in position "in
  depot", I fill the field collection fields "name depot" and "date in
  depot". For the bill of lading content type it reference the
  containers also, I redirect to it every time the node position is
  saved and "position container" is "on board". Now the challenge is
  providing a list of containers,with the current bill of lading "N°
  B/L", the current cycle and merging all the positions fields
  corresponding to this cycle.

Sure there is probably some way to do that with PHP or an advanced SQL query. I recommend looking at Views Aggregator Plus as it allows you to aggregrate over Views PHP values.

Views is a simple query builder. When you want to do something really really complex, it can be useful to try to do some business logic outside of the views admin ui.


How to send a email message to specific user role when the site goes to the maintenance mode in drupal 7? I would like to use emails to communicate with users. So i really want to send a email message for all users(or just a number of users with specific role) when the site goes to the maintenance mode and send another one when the site comes online.

I checked triggers, rules, actions but couldn't find anything to help.

How can I solve this?

Checkout this module Maintenance mode API .

  Maintenance mode API notifies other modules when the site is switched into or from maintenance mode.

  This means that other modules can respond to this, for example:

  Alerting a list of users when the site goes into or out of maintenance mode

This module provides a hook, hook_change_maintenance_mode which any custom modules can interact

EDIT:

You can create a custom rule set with actions as send emails to your desired users. (An example guide how to create it).

Then invoke the rule set using rules_invoke_event() function inside the hook hook_change_maintenance_mode