Drupal commerce - same product with different formats that determine price and get added to line item titles I have a taxonomy term select list where the administrator can add one or more formats to a product entity. The term itself has a price coefficient field that should be used to determine the price of the product in that format. On the product display page there should be a 'add to cart' button for every format of that product. The title of the product in the cart/order views should display the format and the price should be according to what was calculated using the product base price and the format coefficient.

Any generic ideas how I could implement this with the Drupal Commerce module or good alternatives that accomplish the same thing? It could be assumed that every product display has only one product entity associated with it if this makes things easier.

Googletorp's suggestion seemed like it won't give me quite the result I needed so I tried to do the whole thing with my own add-to-cart form, line item/order creation and so on, but ended up with a lot of issues and work that made me go back and try the suggested approach. Got exactly what I needed much easier in the end. Posting the entire solution here to save possible trouble for others.

First I added a format field (that referenced the same taxonomy terms as the one attached to the product) for the used line item. Set it up so it would be included in the Add to Cart forms. After that I added the pricing rule via the GUI:

Events - Calculating the sell price of a product.
Conditions - Entity has field (line item format field).
Actions - Multiply the unit price by some amount (amount specified in the terms coefficient field).

To modify line item titles to show the selected format I found help here: http://digibits.org/blog/drupal-commerce-dynamic-line-item-titles. The code:

function mymodule_commerce_line_item_type_info_alter(&$line_items) {
  $line_items['product']['callbacks']['title'] = 'mymodule_line_item_title';
}

function mymodule_line_item_title($line_item) {
  $term = taxonomy_term_load($line_item->field_line_item_format[LANGUAGE_NONE][0]['tid']);

  return t('!product (!title)', array(
    '!product' => commerce_product_line_item_title($line_item),
    '!title' => $term->name,
  ));
}

Now I needed to restrict the format selection for customers depending of what the administrator has chosen for the product and display them all as add-to-cart buttons not a select list. This was doable via hook_form_alter():

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  // Alter add to cart forms.
  if (strpos($form_id, 'commerce_cart_add_to_cart_form_') === 0) {
    // If the product is available for sale.
    if ($form['submit']['#value'] == t('Add to cart')) {
      // The form should only be for a single product so we can get the id from the product_id field.
      $product_id = $form['product_id']['#value'];
      $product = commerce_product_load($product_id);
      // The original submit button isn't needed.
      unset($form['submit']);

      $i = 1;
      // Create a submit button and additional markup for every given format.
      foreach ($product->field_format_types[LANGUAGE_NONE] as $format) {
        // #name will be used to determine the selected product format instead of the select list value.
        $form['submit_'.$i] = array(
          '#type' => 'submit',
          '#value' => t('Add to cart'),
          '#name' => $format['tid'],
        );
        $i++;
      }

      // This form submit handler needs to be called before any others.
      array_unshift($form['#submit'], 'mymodule_add_to_cart_form_submit');
    }
  }
}

function mymodule_add_to_cart_form_submit($form, &$form_state) {
  //drupal_set_message('<pre>'.var_export($form_state['triggering_element'], TRUE).'</pre>');

  // Get the clicked submit button name.
  $name = $form_state['triggering_element']['#name'];
  // Use the clicked submit button name to set the correct product format.
  $form_state['values']['line_item_fields']['field_line_item_format'][LANGUAGE_NONE][0]['tid'] = $name;
}

In the end I hid the select list via css and that was it.


How to move Composer created folder of drupal-8.x.x up one level to html? So I created a fresh install of Ubuntu 16.04 and installed the LAMP stack, installed phpmyadmin and composer and then finally drush. Everything worked fine until I downloaded and installed Drupal using the "drush pm download" command which worked fine but now my entire drupal site is located in a folder called "drupal-8.6.3". I used to use the wget command and the tar --strip components command to get it properly organized.

I can delete the drupal-8.6.3 directory but how can I download my drupal site using composer or drush from the html folder?

Since you are using composer to manage dependencies, you should install Drupal with Composer instead of using drush pm-download:

https://www.drupal.org/docs/develop/using-composer/using-composer-to-manage-drupal-site-dependencies#download-core

Also, you should use Composer to manage contributed modules instead of using drush pm-install:

https://www.drupal.org/docs/develop/using-composer/using-composer-to-manage-drupal-site-dependencies#managing-contributed

You can even use Composer to manage third-party libraries:

https://www.drupal.org/docs/develop/using-composer/using-composer-to-manage-drupal-site-dependencies#third-party-libraries

And to apply patches to Drupal core and contrib modules:

https://www.drupal.org/docs/develop/using-composer/using-composer-to-manage-drupal-site-dependencies#patches

Don't worry, you'll still use drush for a lot of things -- but once you've switched to using Composer to manage dependencies, you should stick with it as much as possible and avoid using Drush makefiles or installing / upgrading with Drush.

Here's an article with some common "gotchas" you may encounter when managing Drupal with Composer:

https://www.jeffgeerling.com/blog/2017/composer-and-drupal-are-still-strange-bedfellows


How can I get views_save_view($view) to return TRUE when using Drush? I have a script that calls various views API functions, namely views_save_view() or $view->save().

When using Drush 5 to run the script, these functions return false. However, when I run these with cron while logged into Drupal through the config, it works fine and everything executes as normal.

How can I get these to return true while using Drush?

I have feeling this is a permissions issue, but can't figure out how to get Drush to execute with the permissions it needs. This is a follow up question to here:

How can I run Drush as user 1 in version 5?

Also there is a somewhat related issue here:

http://drupal.org/node/1515616#comment-6312604

You can run a script as a user with the right command line option. Basically:

drush php-script YOURSCRIPTNAME.php --user=1

or --user=UID where UID is a valid drupal user ...


Drupal ui inside module Am i doing wrong to define, jQuery Accordion inside my .module file,
just like this:

<?php
  drupal_add_library('system', 'ui.accordion');

Drupal no longer loading jquery itself.

Yes that's wrong, you need to put it inside a hook function.

Which one depends on where you're trying to use it. To add it to a render array, for example a form, you might use

$form['#attached']['library'][] = array('system', 'ui.accordion');


How can I stop the cron tasks from being triggered by site visitors? My site's logs show that cron is triggered if someone visits the website. This is slowing down the load time for the first visit.

The cron is configured to run each 3 hours here: Administration » Configuration » System » Cron.

How can I run the cron scheduled and not triggered by visitors?

Drupal 7 incorporated in its modules the code that were in Poormanscron, whose purpose is exactly to run Drupal cron tasks on a site where it is not possible to set cron tasks, when a user visits your site, and every X hours (as set in the page you saw).

If you want to avoid that behavior, you just need to set "Run cron every" to "Never"; contrary to what it could seem, that just influences what happens when users visit your site.[1] You can still run Drupal cron tasks from outside Drupal, remembering that in Drupal 7 cron.php needs to be invoked, from outside Drupal, passing the value shown in "Administration > Reports > Status report."

[1]: In fact, neither cron.php, nor drupal_cron_run() checks the Drupal variable used in that settings page. The only Drupal variables used are:

"cron_key" that contains the cron key used to avoid the Drupal cron tasks are ran from unauthorized users
"maintenance_mode" that is set to TRUE when the site is in maintenance mode
"cron_last" that contains the timestamp of when cron tasks were ran last time


Rules in Drupal 7: EntityMalformedException in custom PHP I used to run successfully the following custom PHP code in rules before a node is stored

$update_node = node_load($node->nid);
$lat1 = floatval($node->field_geo["und"][0]["lat"]);
//SOME MATH HERE
$update_node->field_winkel_dorf["und"][0] = array("value"=>$winkel);
node_save($update_node);
}

But now after a major update of lots of modules I get this error:
EntityMalformedException: Fehlende Paketeigenschaft auf einem Element des Types node. in entity_extract_ids() (Zeile 7663 von /var/www/vhosts/mydomain/httpdocs/includes/common.inc).

I have no idea what changed....

Any help very very welcome.

You need to remove the first line $update_node = node_load($node->nid); because nid does not exist yet in node object then remove the last line as well node_save($update_node);.

Also, replace each $update_node variable with $node which is available by rules module.

Your final code should look like the following:

$lat1 = floatval($node->field_geo["und"][0]["lat"]);
//SOME MATH HERE
$node->field_winkel_dorf["und"][0] = array("value"=>$winkel);


how to show date filter by next 5 months via expose filter in drupal? I have a content type with date fields . For date I am using date module. I have created a views in drupal 7 and using exposed filter. I need to show filter my data via month , Means I need to show months(next 5 months including current) in dropdown.

What you're wanting is Grouped Filters. It will let you set pre-defined discrete filters for your date.

Under the Views UI for your exposed data filter set Filter type to expose to Grouped Filters. You can set your arbitrary label, set your operator to is between, and Value type to An offset from the current time... in the date fields, you can use a relative PHP strtotime() format to specify a filter between the current date ("now") and 5 months into the future ("+5 month").


How to get a value from block configuration's form control? I'm new to drupal stackexchange and drupal too.

I have made an example module that creates a block called "example". I added a textfield form control to the "example" block's configuration page using the hook_block_configuration hook function. Now I'm trying to get the value from the block configuration's form control in my hook_block_view hook function.

Here is what I have so far:

function example_block_info() {

    $blocks = array();

    $blocks['example'] = array(
        'info' => t('example'),
    );

    return $blocks;

}// end function

function example_block_configuration($delta = '') {

    $form = array();

    switch($delta) {

        case 'example' :

        $form['text'] = array(
          '#type' => 'textfield',
          '#title' => t('Text'),
          '#default_value' => '',
          '#size' => 50,
          '#maxlength' => 100,
          '#required' => true,
        );

    }// end function

    return $form;

}// end function

function example_block_view($delta) {

    $block = array();

    switch($delta) {

        case 'example' :
            $block['content'] = get_block_content(),
            break;

    }// end switch

    return $block;

}// end function

function get_block_content() {

    return /* textfield form control value */

}// end function

I figured I have to use the hook_block_save hook function to get the value from the '$edit' argument and store it somehow, but I'm not show how, or if that's the correct way to go about it.

function example_block_save($delta = '', $edit = array()) {

    switch($delta) {

        case 'example' :

            $edit['text'];

            break;

    }// end switch

}// end function

What you need is completely covered in example module: block_example.module

Have a look at following hooks:

block_example_block_configure
block_example_block_save
block_example_block_view


Is it possible to done search indexing locally, then upload it? I want to perform search items indexing on the local system .
Due to high number of items and And slowing down the server

Can I do something like this ,  then I upload the result to the DB?
Without completely erasing the previous database.just replacing drupal's index.

The suggestions in the comments are good, specially using solr.

But in your case you can index the whole data locally, and dump these three tables: search_dataset, search_index, search_total and then import it on the server.


Pass book node id as second parameter to drupal_block("book_navigation")? I'm trying to use drupal_block("book_navigation") in a twig template (with the twig_tweak module installed) to display a list of chapters for a book page. But I'm getting a list of all books and their chapters.

Is there a way to use drupal_block("book_navigation") to produce a list of chapters for just the one book, maybe by passing the id of the book node as a second parameter? Or some other way?

Compare to the user interface /admin/structure/block. There, when you place a Book Navigation block in a region, you can choose the configuration option "Show block only on book pages". This causes the block to produce a list of chapters for only the book whose page the list appears on. So it's clearly possible to do it using the book navigation block. Just need to know how.

After digging into the Book module code, I discovered that in a twig template (with the twig_tweak module installed) I can use

    {{ drupal_block("book_navigation", {block_mode: "book pages"}) }}

to create a list of chapters for only the current book (which is what I need). This is equivalent to the configuration option "Show block only on book pages". Probably in documentation somewhere, but much googling didn't find it for me.


Views show table of titles of last nodes for each content type I want to show a table (using views) displaying a list of the last node (latest pub date) for each content type.

Any ideas?

Use a View and code to embed that View for each content type.

To get the same View as what I created, import the View I've pasted here: http://pastebin.com/2xQx7BPs

Instead of having anything hardcoded, you can achieve this as follows:

Quick and Dirty

Enable the "PHP filter" module.
Create a Basic Page.
Use "PHP code" as the Text format in a Basic Page with this Body

Paste this:

<?php
    $content_types = node_type_get_names(); // get all content types
    $ct_machine_names = array_keys($content_types); // we just need machine names
    foreach ($ct_machine_names as $ct_name){ // loop through, adding them as an argument to the View
      echo views_embed_view('latest_node_by_type', 'block', $ct_name);
    }
?>

Proper Way

There are a few ways to achieve this instead of using the "PHP filter". Using a custom block in your own module isn't difficult. My favorite resource that explains this is located here:
http://kahthong.com/2013/06/create-your-own-custom-drupal-block-programmatically

Follow the directions, and replace the last block with something like this:

<?php
    function _YOUR_MODULE_BLOCK_ABC_CONTENT() {
      $output = '';
      $content_types = node_type_get_names(); // get all content types
      $ct_machine_names = array_keys($content_types); // we just need machine names
      foreach ($ct_machine_names as $ct_name){ // loop through, adding them as an argument to the View
        $output .= views_embed_view('latest_node_by_type', 'block', $ct_name) . '<br/>';
      }
      return $output;
    }
?>


Create content programmatically In Drupal 8, how can I create content programmatically ?
From the "Drupal 8" administration, I created a new type "House" (contain a description, an image, a reference field to users ...). How can I create a entity type "House" from a custom module ?

In my custom module, I have a form file (contain a class who extends FormBase). In the submit callback, I want create a new "house" and set values and save the new Entity.

I don't find examples on the web, in core...

Here's a simple example of creating a node in Drupal 8.

$data = [
  'type' => 'article',
  'title' => 'My new title',
  'uid' => 1
];
$node = Drupal::entityTypeManager()
  ->getStorage('node')
  ->create($data);
$node->save();

Updated to remove deprecated function as per comments from @mradcliffe. Thanks!

FYI, for testing out little snippets of code like this, the drush core-cli command works great. See: http://www.drushcommands.com/drush-7x/core/core-cli


How to use a view block in a dropdown menu item? I'd like to create a menu item that generates a dropdown menu with unread messages. I've already used Nice Menus for flyout menus, but I don't think that module supports what I'm looking for: the dropdown should be a view block and should appear when the user hoovers the 'block' in the menu bar.

Is there a module that makes this possible?

Try out for following modules

Menu Views

  Allows menu items to render views instead of links. This is useful for
  creating "mega-menus".

Menu Attach Block

  Menu Attach Block allows you to attach blocks to standard core Drupal
  menu items. This is especially useful for creating complex dropdown
  menus and mega menus.

  Any block can be used, including blocks generated by other modules.
  Blocks generated by Views are particularly good candidates for
  embedding.


Drupal 6 Form fields not displaying if nested too deep. I'm using Drupal 6 to create a form that's pretty big. Basically here is how the client wants this form to act:

Users create engagements, and an engagement can have multiple goals and multiple meetings. Each goal can have multiple recommendations, and each recommendation can have multiple action steps. So far I've been able to use AHAH to dynamically add meetings and goals to engagements, but I've hit a snag as I've started to try adding recommendations to goals. I'm doing something like this for recommendations:

 $form['goals_fieldset']['goal_'.$gid]['recommendations']['rec_'.$rid]['title'] = array(
    '#type' => 'textfield',
    '#title' => t('Recommendation Title'),
    '#default_value' => $title,
  );

This will nest the recommendations array under the goal its attached to, my issue is, the field doesn't show up on the form, is there a limitation to how nested you can go in a form? If I use:

  $form['goals_fieldset']['goal_'.$gid]['rec_'.$rid]['title'] = array(
    '#type' => 'textfield',
    '#title' => t('Recommendation Title'),
    '#default_value' => $title,
  );

The field will show up. I really need the ['recommendations'] piece in there cause it is where I've set the wrapper that AHAH replaces when you click the 'add another' button:

$form['goals_fieldset']['goal_'.$gid]['recommendations'] = array(
  '#type' => 'fieldset',
  '#title' => t('Recommendations'),

  // Set up the wrapper so that AJAX will be able to replace the fieldset.
  '#prefix' => '
',
  '#suffix' => '
',
);

Any insight as to why my fields won't show up, or insight into how to fix is greatly appreciated. Thanks!

So I found out why its not working, very simple mistake on my part. I was declaring            $form['goals_fieldset']['goal_'.$gid]['recommendations'] later in the form, erasing everything else. Sorry for wasting time!


On User Creation, send user registration email in his language preference Is there a way to send the welcome message to a new user in his preferred languages ?

As an Administrator of the website, I create all the users with their preferred languages. I Check the button to notify the user when the user is created.
The email is sent correcly but not in the languages that I specify for a particular user.

I already install the I18n module and made the translation between each languages.

Thanks a lot

I think you need to change the way drupal detect the language of the current user.

You can do so by going to /admin/config/regional/language/configure and check "Follow the user's language preference.". You may need to move this option as the first detection method.


How to allow users programatically to post and view posts regardless of they are trusted contact or not in drupal commons All is in the title, actually users can only posts privately to theirs trusted contacts and sees posts of trusted contacts.
I don't need such restriction in my project and want to bypassing this restriction so all users except anonymous can posts and see posts.

That beeing said, I don't wanna change they way groups works, so if group is private all posts in the group should stay private.

I've searched in commons_trusted_contacts module and I can't figure out where this is been handle.
I've tried to set group_content_access value to 1 in database (1|Public - accessible to all site users) but this doesn't seems to be the way.

I found out that commons_trusted_contacts module is setting content access as private while posting for trusted contacts, which add post to user group so that only user's trusted contacts sees posts.

In order to post regardless of users are trusted contact or not, I've changed value of group_content_access to public. This way posts are not assigned to any group so it's visible for all users. In database, gid is then set to 0 instead of uid representing user group.

Bellow the line I've changed

$wrapper->group_content_access->set(OG_CONTENT_ACCESS_PRIVATE);

to

$wrapper->group_content_access->set(OG_CONTENT_ACCESS_PUBLIC);


drupal_goto(request_uri()) replaces my '?', '=' and '&' in url I need to redirect user from a page with example.com/node/add/dispo?arg1=1&arg2=2 to the same type of URL. But when I simply do a drupal_goto(request_uri());, it redirects my user to example.com/node/add/dispo%25F%3C etc....

I tried a str_replace but it didnt work.

Would you have any workaround ?

drupal_goto() accepts an $options parameter to be passed on to the url() function. You can pass a query string like this:

$options = array('query' => array('foo' => 'bar'));
drupal_goto('path', $options);

That example will forward on to /path?foo=bar


Adding classes to individual list items in a site map I am using the Site Map module in my site but I need to style my list items individually. Is there a way to add a different class to each list item in the site map?

I prefer to use Menu Block blocks on a basic page for building a sitemap - it gives more control over the menu order, title display, etc. (unless, of course, you need the RSS feed icons in the sitemap - then the Sitemap module is more useful.) With Menu Block, you get a unique mlid class for each list item.


Formatting currency in Drupal Commerce I am using Views and Drupal Commerce in Drupal 7 to display a list catalogue of products (books).

By default the price column is formatted "12.34 ZAR" which is a format that is only really used in an international currency trade context for South African Rand. How do I override the format so that I can display it as "R12.34" which is the more common format.

You can do it just for your site using hook_commerce_currency_info_alter(), but more appropriately check out the information in the Drupal Commerce FAQ on Currency Formatting to get the proper format in core. The reason it's showing up as 12.34 ZAR is because that's just the bland default format we use for currencies we didn't know how to format. : )


How can I display a "loading" icon while a slow page loads? I have a custom module whose front-end page is slow to load due to extensive database work (no forms, just a bunch of db queries to display some long tables). I want to add the little "loading" icon (similar to the iphone) while the page is loading, to show users the page is working. I've seen it on some of the Views administration pages, but I can't seem to find the code for it. Is the display code done with jQuery or a drupal module? How do I add the code to my module/page? Thanks in advance!

There is Page Throbber module which suits your requirement.

  Page Throbber is a simple utility module which lets the site developer
  display a spinning "throbber" and a custom message to display when
  loading up pages which they know will be slow to load.


Flag : access, context, role I have a site where members (with different roles) can post projects.

My goal : To show to "recruiters" (role) a view of all the users who have flagged their nodes. In other words, the flag accessibility / visibility is dependant of the author's role and node type.

I need :

to show a flag to every user if the author of the node has the role "recruiter"
to let the "recruiter" unflag a user from his view of applicants.

I can't / I can:

I cannot figure out how to control the visibility / accessibility of the flag based on the author's role. I've checked a few modules, but did not find anything relevent yet.
I'm ok with Views: I guess I could make a second flag only for "recruiters" (available in the view) and set a double condition : if user has flagged node AND if "recruiter" has flagged the user in the list, then remove user from the view. By doing this, the user would not be able to flag again the node (job post) if the 'recruiter" has (un)flagged the user.

My hope : to be able to combine available modules (no coding).

I guess a custom module could look for a boolean field (checkbox) only available to some roles and show (or not) the flag. But I'm no coder unfortunately.

Let's start with available modules : is there anything that I missed?

I have the impression that what you're asking for requires more then just (only) the Flag module. I.e. you should get it to work if you also use the Rules Link module.

If you're not familiar with Rules Link, then have a look at "How to show authorized users a link for relevant Views results using the Rules Link module?". The scenario explained in that question is about users that are "blocked" or "active", and which you could consider as a variation of what this question here is about, i.e.:

think of "active" users as "users who have flagged their nodes" (as in your question).
think of "blocked" users as "unflag a user from his view of applicants" (as in your question).

Of course, you don't want to block or activate users for your case. But instead you could use 2 separate flags:

a 1st flag to be used by all the users, to indicate something like "I want to apply for this node" (adapt the label to whatever fits).
a 2nd flag to be used by the recruiter to indicate something like "reject a user as an applicant".

Obviously, you could show to "recruiters" (role) a view of all the users who have flagged their nodes (with the "1st flag"). And using Rules Link you could improve that view to trigger some additional Rules magic to simply flag an applicant (with the "2nd flag").

Note: no custom coding needed, only 2 flags to be configured, and some rules magic (combined with Rules Link).


Looking for multi step form in Drupal that can also show submissions in Admin I hope I am not offending someone with this naive question.

I am currently trying to create a customized JQuery + PHP + HTML multi step form in Drupal. I am hoping if anyone of you could let me know if there is some way I can create this and also see the submissions through Admin.

Many Thanks.

You can use Webform module and Webform steps module to visualize the steps.

The process is as follows:

Create Webform put some fields organized in Fieldsets if you like.
To make new page insert pagebreak

.

If you want more customization you can follow this tutorial for creating your own module for that.


Validation constraints on form fields ignored Trying to figure out custom validation with constraints, but no luck yet. Right now, my form posts content and gives no errors when form is filled out incorrectly.

(Please avoid suggesting validation modules -- I know those exist.)

Maybe somebody knows what I'm missing? Or maybe it's done different when I'm doing specific fields? Or maybe this isn't how to do it on a back-end content submission form?  Here's what I have so far:

I built a module called "custom_validation." It contains custom_validation.module:

  <?php

/**
 * @file
 */

/**
 * Implements hook_entity_type_alter().
 */
function custom_validation_entity_type_alter(array &$entity_types) {

  /** @var $entity_types \Drupal\Core\Entity\EntityTypeInterface[] */

  $entity = $entity_types['node'];
  $entity->addConstraint('BlogpostError');
}

Then, in subfolder src/Plugin/Validation/Constraint, I've got two files.
BlogpostErrorConstraint.php contains:

namespace Drupal\custom_validation\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;

/**
 * Prevent article creation if errors.
 *
 * @Constraint(
 *   id = "BlogpostError",
 *   label = @Translation("Added blog post category instead of story author in author field", context = "Validation"),
 *   type = "string"
 * )
 */
class BlogpostErrorConstraint extends Constraint {

  /**
   * {@inheritdoc}
   */

    public $notByline = '%value is a blog post type. Please add a byline';

    public $noImageSource = 'need image source';

}

BlogpostErrorConstraintValidator.php contains:

namespace Drupal\custom_validation\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 * Validates the BlogpostError constraint.
 */
class BlogpostErrorConstraintValidator extends ConstraintValidator {

  /**
   * {@inheritdoc}
   */
  public function validate($items, Constraint $constraint) {

    if (!isset($items)) {
      return;
    }

    // limit this to 'blog entries' content type
    if ($items->bundle() == 'blog_entry') {

      // now loop through each field...
      foreach ($items as $delta => $item) {
        // an array of phrases we don't want in the field
        $bad_bylines = [];
        array_push($bad_bylines,"Value one","value two","abc123");

        // adding validation...
        //byline field
        if (in_array($item['field_byline'], $bad_bylines)) {
           // not sure of syntax here
           $this->context->addViolation($constraint->notByline, ['%value' => $item->value]);
        }

        //main image source field...
        if ($item['field_main_image_source'] == '') {
           $this->context->addViolation($constraint->noImageSource, ['%value' => $item->value]);
        }
      }

    }

  }

}

Turns out I was trying too hard. Typical beginner mistake. :)  I threw out the code above, and started from scratch. I replaced everything with the code examples in this tutorial: https://www.drupal.org/docs/8/api/entity-validation-api/providing-a-custom-validation-constraint

Within the validator, I replaced if (!is_int($item->value)) with  if ($item->value == "Value one" || "value two"), to get what I needed to validate on. Then I modified the variable names, field names and error messages to suit my needs. It only handles one field, but gets me closer to what I need.


Unable to login into website after installing and setting up itweak_login After installing and tweaking itweak_login I got this error when I tried to re login into the site.

Any body have any ideas, how I can log in into the site. Sorry, unrecognized username or password.

Notice Message:

  Notice: Undefined variable: form_values in _itweak_login_user_login_final_validate() (line 266 of C:\Inetpub\websites\web.etfotvots.com\sites\all\modules\itweak_login\itweak_login.module).

After reviewing that module's code, I have to agree with @Aboodred1 in his comment you can disable the module from the database for several reasons (which I'll address on the module's drupal.org page rather than this site because I don't think this site is the appropriate place to do so). This is not the preferred or recommended way to do things, but it seems like you might have no other choice if you've already installed it.

Method 1

BACK UP YOUR DATABASE
If you don't feel comfortable directly accessing your database, you should be able to log in to your web server and delete the itweak_login module directory (usually located inside sites/all/modules) and everything inside it. This should at least give you access back into your site. If that doesn't work, or if you do feel comfortable accessing/modifying your database directly, here's an elaboration on the aforementioned comment:

Method 2

BACK UP YOUR DATABASE
Log in to your web server and open the settings.php file for your Drupal installation (usually located at sites/default/settings.php)
Find the line that looks like this:

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'mydrupal7database',
      'username' => 'mydatabaseusername',
      'password' => 'mydatabasepassword',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

If the prefix line is empty (as it is in the example above), continue on to number 5

If it's not empty, e.g. if it looks something like this: 'prefix' => 'drupal7_', then replace the word system in step 7 with drupal7_system (in other words, add the prefix to the the word system)

Log in to your database if you're not already there
Select the database used for this particular Drupal installation (using the example above, you'd select the database called mydrupal7database)
Run the following SQL statement:

UPDATE `system` SET `status` = 0 WHERE `name` = 'itweak_login';

Note: after you disable the module in the database, you should be able to access your site again. At this point, I'd highly recommend uninstalling it by visiting the module uninstall page (admin/modules/uninstall), and then after it has been uninstalled, remove it from your server altogether (using Method 1 above).

Hope that helps...

:)


how can I change all price view in drupal commerce I want to change default drupal view of price in all of my field,
as a example I want to remove '00' and add my custom postfix to it,

I found hook_commerce_price_field_formatter_prepare_view but when I implement it in my module it not called,really I am not sure this hook is suitable and ca  achieve my need??

I just want the all price fields changes to my desire only  in front-end view (only in view, because my payment method is according to main currency)

You can do this using the Commerce Currency API

Implement hook_commerce_currency_info_alter and add your own commerce_currency_format handler

e.g:

/**
 * hook_commerce_currency_info_alter
 *
 * Add custom currency format to selected currencies
 */
function MY_MODULE_commerce_currency_info_alter(&$currencies){
  $currencies['IRR']['format_callback'] = 'MY_MODULE_commerce_currency_format';
}

/**
 * Currency format callback
 *
 * Remove decimal places from output
 * while keeping commerce_amount_to_decimal formatting the same
 *
 * See: commerce_currency_format
 */
function MY_MODULE_commerce_currency_format($amount, $currency, $object = NULL, $convert = TRUE) {

  // Format the price as a number.
  // In our case, we remove decimal places
  $price = number_format(commerce_currency_round(abs($amount), $currency), 0, $currency['decimal_separator'], $currency['thousands_separator']);

  // Establish the replacement values to format this price for its currency.
  $replacements = array(
    '@code_before' => $currency['code_placement'] == 'before' ? $currency['code'] : '',
    '@symbol_before' => $currency['symbol_placement'] == 'before' ? $currency['symbol'] : '',
    '@price' => $price,
    '@symbol_after' => $currency['symbol_placement'] == 'after' ? $currency['symbol'] : '',
    '@code_after' => $currency['code_placement'] == 'after' ? $currency['code'] : '',
    '@negative' => $amount < 0 ? '-' : '',
    '@symbol_spacer' => $currency['symbol_spacer'],
    '@code_spacer' => $currency['code_spacer'],
  );

  return trim(t('@code_before@code_spacer@negative@symbol_before@price@symbol_spacer@symbol_after@code_spacer@code_after', $replacements));
}


How to Change "USER has no blog entries" Text When you click on a user's blogs link and there are none he message "USER has no blog entries." comes up. I want to change that. I have tried using string overrides within settings.php but it does not seem to work. I used !username for the user as it is a link but nothing.

You have to isolate first exactly where this text is coming from. From your description, it sounds like you're using the core blog module which has this line here:

https://api.drupal.org/api/drupal/modules%21blog%21blog.pages.inc/function/blog_page_user/7

else {
  drupal_set_message(t('!author has not created any blog entries.', array('!author' => theme('username', array('account' => $account)))));
}

So the correct string you want to use (and what your string override in settings.php will be looking for) is

!author has not created any blog entries.

Using the string overrides module or your settings file, its easy then to change this text to whatever your like


"Node: Created day" mismatched, not reflecting the actual created day Views Version: 7.x-3.0-alpha1

I was trying to create a blog archive view, like blog/yyyy/mm/dd, where blog/2011/03/10 is  supposed to display all posts created on 2011, March 10th. However, the page blog/2011/03/10 actually displays all posts created on 2011, March, 11th, one day advanced to the supplied day argument.

How to reproduce the bug:

clean install, enable modules.
create blog content type, generate dummy contents.
create a view:

  * Arguments:
        o Node: Created year
        o Node: Created month
        o Node: Created day

  * Path: blog

  * Filters
        o Node: Published Yes
        o Node: Type = blog

The year, month arguments show correctly, just the day is wrong, always one day prior to the day argument.

Can anyone point me to what went wrong?

Actually had this bug, but with views 2 on drupal 6, and instead of going forward a day, our view was going backward a day.

Have you tried updating to --dev to see if the issue still exists? I know a lot of patches have been committed since that alpha was released.


Change URL on ajax link I've got a custom AJAX link on my site, which does it's current job fine, but what I'd like to do is make it change the href attribute of an element on the page as well. I'm not brilliant at jQuery, so I'm not sure how I'd use the Drupal AJAX commands to do something like this, if it can even be done.

Basic info of my existing setup

HTML

Add

Module

/**
 * Implements hook_menu().
 */
function mymodule_menu() {
    // Creates a page to listen for a new slide being added
    $items['ajax/mymodule/slide/%node'] = array(
        'page callback' => 'mymodule_append_slide_to_deck',
        'page arguments' => array(3),
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK,
    );

  return $items;
}

function mymodule_append_slide_to_deck($node) {
    if (!empty($node)) {
        if ($node->field_image) {
            // CODE TO GET HTML OF THUMBNAIL FROM THE NODE REFERENCED, ADDED TO VAR $thumbnail

            // Prepare an ajax command to insert the node html into our ajax wrapper.
            $commands = array();
            $commands[] = ajax_command_append('#deck .deck-creator', $thumbnail);

            // Render the commands into JSON and print them.
            print ajax_render($commands);
            exit;
        }
    }
}

All this part works fine, does it's job. However I have another button on the page, and I'd like to pass this Node ID of the node I've referenced (in this case 15) to the end of the href property. Can this be done? or is the simplest thing to replace the HTML entirely using ajax_command_replace();?

Found the best way of doing this was using ajax_command_invoke() instead.

By using this you can make a call to a custom jQuery function, in which you can then do what you want.

    ...
    // Prepare an ajax command to insert the node html into our ajax wrapper.
    $commands = array();
    $commands[] = ajax_command_html('#deck .deck-creator', $thumbnails);
    $commands[] = ajax_command_invoke(NULL, array('customAction'));

in a jQuery file

(function($) {
    $.fn.customAction = function() {
        // do my code
    }
})(jQuery);


How to delete a comment via an HTTP GET link in an email On my site, moderators are notified of comments via email whenever a new comment is posted. I would like to offer them a one-click approve/delete feature directly from the email.

There is an approve comment link, so I can easily put that link into the email for them to approve the comment directly.

However comments are deleted via a form - an HTTP post - so I can't do that from a link in an email as far as I know. At least that's how it is on my site - not sure whether the form behaviour is normal or is because I have Mollom installed.

Is there a way to delete a comment directly from a link in an email?

This will do it.

Obviously you don't want to allow just anyone to delete any comment.

The authentication step is to require the user to be logged in with "administer comments" permission.

Alternatively, you could perhaps use a token in the querystring to check access to delete the comment.

/**
 * Implements hook_menu
 */
function MY_MODULE_menu() {

  $items['action/comment/%/delete'] = array(
    'title' => 'Delete comment',
    'page callback' => 'MY_MODULE_action_comment_delete',
    'page arguments' => array(2),
    'access arguments' => array('administer comments'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

/**
 * Menu callback
 * Delete comment via GET request
 */
function MY_MODULE_action_comment_delete($cid){

  try{
    // Delete the comment
    comment_delete($cid);
    drupal_set_message(t('The comment and all its replies have been deleted.'));
    watchdog('MY_MODULE', 'Deleted comment @cid and its replies.', array('@cid' => $cid));
    // Clear the cache so an anonymous user sees that his comment was deleted.
    cache_clear_all();
  }catch(Exception $e){
    drupal_set_message(t('There was a problem deleting the comment.'));
    watchdog_exception('MY_MODULE', $e);
  }

}

The path to delete a comment would then be:

http://www.example.com/action/comment/12/delete

Where "12" is the comment cid.


Set the permission to view taxonomy term pages basing on the vocabulary I'd like to completely disable taxonomy term pages based on the vocabulary. I want to use the taxonomy terms to organize nodes, and even let people use them, but users should not view the normal taxonomy pages.

Basically, I need to set the permission to view the taxonomy pages basing on the vocabulary.
Does a module like this exist?

Things like Taxonomy Access Control come to mind, but those are intended to hide content based on how it has been tagged; perhaps one of those modules does what I'm looking for.

Use hook_menu_alter() to customize the access_callback on $callback['taxonomy/term/%'].


Generate file path for created file so it can be downloaded I'm writing a module based on this Jeff Geerling post that will allow the user to use a form to select some data, and then use the Batch API to generate a large .csv file with the desired data and download it from the browser. I have the form and batch processing working fine, but I can't figure out how to determine the path for the created file, as referenced in this code snippet:

/**
 * Interim download step for downloading CSV file.
 */
function MYMODULE_download_csv_file_interim($list_id) {
  global $base_url;

  if (empty($_SESSION['csv_download_filename']) || empty($_SESSION['csv_download_file'])) {
    return t('Please visit your list subscribers page to begin a list download.');
  }

  $list = node_load($list_id);

  // Redirect to the download file.
  $redirect = base_path() . 'path/to/download/csv/' . $list_id;
  drupal_add_js('setTimeout(function() { window.location.href = "' . $redirect . '"; }, 2000);', 'inline');

  $download_link = l(t('click here to download the file'), 'path/to/download/csv/' . $list_id);
  $output = '
' . t('Your subscriber list is now ready for download. The download should begin automatically. If it does not begin downloading within 5 seconds, please !download_link.', array('!download_link' => $download_link)) . '
';
  $output .= '
' . l(t("&#8592; Back to %list subscribers", array('%list' => $list->title)), 'node/' . $list_id . '/subscribers', array('html' => TRUE)) . '
';
  return $output;
}

At this point in the code, $_SESSION['csv_download_file'] is tmp/my_file.csv. I've tried to figure how to make this a valid url for downloading the file, but can't. For instance, I've tried using file_create_url(), but it just returns the same path.

What do I need to use to make this a valid URL to pass to the browser?

/tmp is outside of webroot so apache (or whatever) can't serve files from there.

You have 2 options:

Move the file from /tmp to your public files directory. This will mean anyone will have access to it (if they know the url). See file_unmanaged_move().

Eg.

$source = '/tmp/my_file.csv';
$destination = 'public://csv/my_file.csv';
file_unmanaged_move($source, $destination);

Stream the file to the browser via php. This means only people who can access your php script can get access to the file.

Eg.

header('Content-type: text/csv');
header('Content-disposition: attachment;filename=my_file.csv');
return readfile('/tmp/my_file.csv');


Blogs view for users I have a drupal page with the blog module. Every user has his own Blog, reachable by site.name/en/blogs/user.name but on the blog entry i have added an new field where i can list all Authors. I need now a view which reads this information out of this and show all blog entries of this Author in his blog. Because now, there is the entry only on the blog of his owner. thanks (drupal 7)

I have a solution. Install the Module Entity Reference, then create an multiple field wich is linked to the user Profile, at least you have to add a view to blogs/% and there you have to add an context filter wich filters to the field which refers to the Username.


Load nodes partially? Is there a way to partially load nodes based on the view mode? Say I've got a lot of fields, but for the list view I need only 3 of them ... node_load fetches them all, which doesn't make sense. Or does it? I think about using computed_fields, but when it comes to larger lists I'm a little concerned about performance.

Check out field_get_items(), or to go a bit more advanced (and more 'meta'), use EntityFieldQuery (see examples here).

But, if you're doing this outside of a loop or something, it's often easiest to do a full node_load(), as you can just grab more fields out of there when you need to (in the future) without having to add a bit more code.

My rule of thumb is this: if I only need to load one or two nodes for a particular operation, and the node doesn't contain more than 10-15 fields, I'll just do node_load(). Much more convenient when you don't need to worry about the extra 50ms or so... (for smaller node objects, of course. It's different if you have a node with 25 fields attached!).

[Edit: Just realized field_get_items() still requires the node object itself... which defeats the purpose.]


Overriding theme_item_list in a context I am using Views Tree plugin to render a taxonomy. I need to get rid of the surrounding

 wrappers. While I could simply override the theme_item_list function in my template, I would like the override to only take place within a view. Otherwise the wrapper is just fine. What kind of 'if' should I use around it to apply a Views context?

You can to get rid of the surrounding  wrappers by overriding theme_item_list($variables) function in you template.php or module and comment hardcoded lines:

    $output = '
';

and

    $output = '
';

See details on http://api.drupal.org/api/drupal/includes!theme.inc/function/theme_item_list/7


Lightbox2 module does not allow hover? I am using the Lightbox2 module in Views to make a image larger on click. This works great, but I also want to show a preview of the image on mouse_over. I also use hover_preview module, but I can't seem to use both module with a single view.

Here's a example of what I want:http://gochicorgohome.com/shop/15975,242,49668 (this link is ironic because its Hover_Preview module's example and shows what Lightbox does as well).

So   How do I get/find a module that will enlarge image on click AND preview and image on mouse_over like link above.

EDIT. I am using the REWRITE OUTPUT option in order for my image view to show the lightbox formatter effect.

UPDATE:
Ok I figured it out: Rewrite   However this outputs two images, no link, and "> after the image. I'm guessing my syntax is wrong?

I would install both module, set the Lightbox field format in your view, and then try to replicate the output used by the hover_preview module. If you use the browser inspector you will notice that you need two images in top of each other and some classes assigned to them in order to work.

In your view, add those images fields and rewrite the results. See image attached. I hope it helps.


Webform i18n doesn't work We have installed and enabled:

Webform 7.x-4.0-alpha6
Webform Localization 7.x-4.x-dev
Internationalization 7.x-1.7

We have created several webforms (in English).

When I look admin/config/regional/translate/translate and select "Limit search to" to "Webform Localization", I see an empty list of strings to be translated.

This way we are unable to translate our webforms. Please help.

Need to refresh in admin/config/regional/translate/i18n_string.


Token [commerce-order:payment-method-information] does not display anything I 've tried adding a token [commerce-order:payment-method-information] for emails , but the token does not work or does not display anything in the email sent . Please help

A couple of things.

Have you updated removed the text in the Information field on the payment's configuration page:

Do you have a filtered_html text-format? Is it configured correctly?
If you're not using this in tandem with Commerce Message, you'll need to be using it.


Site Time Zone = field time zone but != database time zone My site time zone setting under Admin>config>regional... is set to Chicago time.

My field date setting is set to use my site time zone.

My user account is set to Chicago, but when I look at the database, it is recording my time as a totally different time zone.

What am I missing? I really need to resolve an issue with Drupal resource-conflict module and the fact that my all-day events don't conflict with my hourly events. There is a topic here - https://www.drupal.org/node/2270533, but I can't seem to get my dates straitened out to even try it. Anyone offer some advice?

When entering data into the field, the data entered is assumed to be in the site's time zone. When the data is saved to the database, it is converted to UTC. When retrieved from the database, the data is converted to the Site's time zone for anonymous users or the User's time zone for logged in users when User-configurable time zones is enabled.
More info https://www.drupal.org/node/767182


How to stop users from flagging other users if they have a custom taxonomy term? I'm working on a project where users vote other users using the Flag module. Each user has a department term reference field. I would like to stop a user from flagging another user if they have the same department. Is it possible? Please help! Thanks in advanced!

Finally I managed to solve my problem by creating a Rule.
Here are the steps you can follow to achieve this:

Create a new Rule and select as the Event "A user has been flagged, under 'your flag'";
Add a condition "Entity has field" and select "flagging-user" as the entity and your field as the "Field";
Add a new condition "List contains item" and select as a list your created field but it must be like this "flagging-user:field-your-field";
Now at the same condition select as the item one of your field value;
Add a AND condition;
Add two more conditions exactly like you did at step 2, 3 and 4 but change "flagging-user" to "flagged-user".
Finally, add an action with "Unflag a User" and select your flag first, then at the User select "flagged-user", at the "User on whose behalf to flag" select "flagging-user" and at "Skip permission check" check "True".

That's it. Hope I helped someone else.

As requested here's an exported code of the actual Rule:

{ "rules_nu_poate_vota_manager" : {
"LABEL" : "Nu poate vota manager",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "flag" ],
"ON" : { "flag_flagged_apreciere" : [] },
"IF" : [
  { "entity_has_field" : { "entity" : [ "flagging-user" ], "field" : "field_raion" } },
  { "list_contains" : { "list" : [ "flagging-user:field-raion" ], "item" : "18" } },
  { "AND" : [] },
  { "entity_has_field" : { "entity" : [ "flagged-user" ], "field" : "field_raion" } },
  { "list_contains" : { "list" : [ "flagged-user:field-raion" ], "item" : "18" } }
],
"DO" : [
  { "flag_unflaguser" : {
      "flag" : "apreciere",
      "user" : [ "flagged-user" ],
      "flagging_user" : [ "flagging_user" ],
      "permission_check" : "1"
    }
  },
  { "drupal_message" : {
      "message" : "Nu po\u0163i aprecia colegii de echip\u0103!",
      "type" : "warning"
    }
  }
]

}
}


Banned IP address is still able to access the site I've blocked the IP address at admin/config/people/ip-blocking and I can see it also in the flood control logs as a blocked IP, but the IP is still accessing the site and I can see errors in the watchdog with their IP address after the block...

I'm at a complete loss as to how this could be... google and SE search has brought nothing. Why isn't Drupal blocking this IP?

Edit: I tested it with a firend's IP and it's not blocking him either, so I guess my IP blocking is not working at all...

Turns out my host has me on a load balancer so the IP was masked by the load balancer. I had to look at the values inside the $_SERVER['HTTP_X_FORWARDED_FOR'] variable instead of $_SERVER['REMOTE_ADDR']

See more info here too: https://www.drupal.org/project/smart_ip/issues/1820048


Dashboard display two blocks pagination I have two block views in my Drupal 7 site dashboard: One is a custom module and one is a normal views block. Both are assigned to the dashboard.

The custom module has a table in the block_view hook. It also has a pagination in it. The second one is generated via the Views module, and also has a table with pagination.

When I go to the second page or to any page of the first table, the second table is updated too.

I made the view based table's pagination AJAX based, but I suppose it is not to right way.

How do I solve this problem?

You have to change the ID of one of the pagers. For the Views module is under Pager setting, Field pager ID.

The description for that field says:

  Unless you're experiencing problems with pagers related to this view, you should leave this at 0. If using multiple pagers on one page you may need to set this number to a higher value so as not to conflict within the ?page= array. Large values will add a lot of commas to your URLs, so avoid if possible.


Append Nodes To Top of View Result I have a view with multiple taxonomy filters.  I need to have it set up so that when a certain term is chosen I need certain nodes to show up on top. Because of this I can't just simply use Sticky!

I'm thinking I will need to write something custom or perhaps use in addition to EntityQueue.

I ended up creating a Flag and sorting by flag and using hook_views_query_alter() to remove the sort condidtion if the filters were not set in the views.


How can I compare a view token with a string? I have a view token
{{ field_category }} == Content: Category
I need a condition like
if field category == "Foo & Bar"
do something
else
do something
I wrote code
         {% if field_category == "Foo & Bar" %}

             string1
         {% else %}

            string 2

        {% endif %}

But it always goes for the else part even if the token value is "Foo & Bar"
Please help to find a solution

But it always goes for the else part even if the token value is "Foo &
Bar"

This is because by default Views adds classes to your field:

Which means field_category is actually equal to
Foo & Bar

and since
Foo & Bar
 is not equal to Foo & Bar your conditional always goes to the else.
If you uncheck the "Add default classes" in your category field settings, your conditional should work now. Unless... your field is linking to something so it would still be Foo & Bar and not equal.
As 4k4 commented, you can instead use field_category__value to get the raw value and not have to uncheck the "Add default classes".


How to obtain foreign field values? I am really new to drupal and struggle to find good tutorials
for the issues I have. One of those issues is as follows:

How do I obtain values from foreign nodes.
Specifically nodes that were created in a feature bundle.

As a concrete example I would like to load all Jobs from the Recruiter
distribution and then extract the field information from them.

After reading through the Book Pro Drupal 7 Development and
many online resource I still struggle to grasp how I am supposed
to do this other than to do direct Database Queries.

There are a few options you have when it comes to exporting data from Drupal 7. A few have been mentioned in this post. Hope this helps!

How to export/import all nodes of a specific content type?


Whenever I edit/update a node all the page caches for anonymous user are lost I have the following cache settings on the performance page

I have visited a few pages as anonymous user and made sure that they are being cached. Now I log in as admin in a different browser and edit a node. The moment I do this I see that Anonymous Page Cache for all the pages are cleared.

This seems counter intuitive and render caching useless for sites with high content editions.

Whenever I edit a node all my page caches are cleared.

As per the design : This behavior is intended behavior and works as per the design. If you look at the node_form_submit() node submit handler function within the node module you will notice that there is a cache_clear_all() As the comment in the line above the function call reads it clears the page and blocks cache as expected.

Reason for clearing all the caches: When a node is created/updated there can be many pages in the site which are dependent on the current node in question. It is next to impossible/very difficult identify all the dependencies and clear the caches only for those pages. For this particular reason, to make sure that no stale data is served to the end user drupal by default clears all the caches.

Work Around :

Approach 1 : Since node_form_submit is form submit handler you could just implement a hook_form_alter() and change the submit handler to your own function which can omit cache_clear_all() function call.

Approach 2 : Set Minimum Cache Life Time to a high value. (By doing this you are asking Drupal not to clear caches if they are not older than the specified Minimum Cache Life time. So now if you edit a node, the changes will not be visible immediately. Your changes will only be visible when time elapsed is greater than Minimum Cache Life time and next general cache wipe has occured.)

Once you have set the Minimum Cache Life Time you can use Expire module to implement your custom logic for Invalidating a cache. You can have settings such that whenever a node is edited drupal can clear the cache for that particular page and all the listing pages.

EDIT(After @MPDs comment) : If you are using a reverse proxy server then you might need to consider setting the Expiration of cached pages to an appropriate value and probably consider using purge module.

Futher Reading : Difference between Minimum Cache Lifetime and Expiration of Cached Pages value.


How can I use 'format_type' => 'custom' for a datetime field? I have a custom entity with (among others) a field defined this way:

$fields['duedate'] = BaseFieldDefinition::create('datetime')
  ->setLabel(t('Due Date'))
  ->setSetting('datetime_type', 'date')
  ->setDefaultValue(array(0 => array(
    'default_date_type' => 'now',
    'default_date' => '2050-12-31',
  )))
  ->setDisplayOptions('view', [
  'type' => 'datetime_default',
  'settings' => [
    'format_type' => 'date_courte',
  ],
    'weight' => 5,
  ])
  ->setDisplayOptions('form', array(
    'weight' => 5,
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

'date_courte' is a custom date format I created to display date as 'dd/mm/yyyy'. And it works!
I'd like to have the same result without using 'date_courte' so I tried

  'settings' => [
    'format_type' => 'custom',
    'format' => 'd/m/Y',
  ],

instead of

  'settings' => [
    'format_type' => 'date_courte',
  ],

And it doesn't work!

I'm pretty sure of 'format_type' => 'custom'.
I think the problem comes from 'format' in 'format' => 'd/m/Y'.

What should be the correct syntax?

I'm pretty sure you need to use the datetime_custom display type vs datetime_default. You won't need to pass the format_type parameter in your settings array. You will end up with something like:

...
->setDisplayOptions('view', [
  'type' => 'datetime_custom',
  'settings' => [
    'date_format' => 'd/m/Y',
  ],
...

That should work how you'd like. The datetime_custom formatter is defined in core's datetime module.


How to restrict node access based on viewer use role and node author user role? I have two Profile2 profile types, and each one automatically applies a specific user role to the user account:

Man
Woman

All users have the ability to add a specific type of node... let's call it "Event".

Man users should never see other Man-user-created events. They should only see Woman-user-created events

Woman users should never see other Woman-user-created events. They should only see Man-user-created events.

I already have the permissions set up where Man users cannot view other Man user profile pages, and likewise for Woman users. How can I apply that same logic/permission restriction to the content those user types create?

Just tried this in my sandbox.
You can do this by using Content Access together with Rules.
The configuration would go like this:

Activate the following modules: Rules, Content Access and Content Access Rules Integrations (a submodule of Content Access)
On your content type - Event - under Access Control, activate "Enable per content node access control settings"
Create two new Rules:

For content created by a member of the Men role:

Event: After saving new content of type Event
Condition:  User has role(s), Parameter: User: [node:author], Roles: men
Action: Revokes Access to the newly created node for the role men. To do that check all but "women" in the "Role-based access control settings" > "View any content" acl group

For content created by a member of the Women role:

Event: After saving new content of type Event
Condition:  User has role(s), Parameter: User: [node:author], Roles: women
Action: Revokes Access to the newly created node for the role women. To do that check all but "men" in the "Role-based access control settings" > "View any content" acl group

Once these Rules are in place, any new content of type Event will have an ACL configuration (per node) that will block members of the same role and allow members of the opposite role to view it. You would probably need to tweak this more to match your goals but this should get you going.

Hope it helps!


adding a grid with specific class in adaptivetheme I'm trying omega and adaptivetheme to use responsive webdesign.
On omega that uses 960grid, I can add a "grid-X" class to an html element to display it in the grid, with the right width etc.
Is there a way to do the same thing with adaptivetheme?

AT does not use Grid classes embedded in markup (it does not use grid classes at all).

If you are asking this I assume you do not really understand how this theme works - you use the layout system (in theme settings, for the main container/page and panels layouts) and write content/element specific CSS yourself, aka use a semantic grid approach.

Grid classes in markup are a huge limitation - what seems so easy now, turns quickly into a massive roadblock later on.

answer by author of adaptivetheme http://drupal.org/node/1861948


How to control metatag module's tags from a page callback? I have some pages which are created by page callback functions. I'm using the metatag module. I'm on D7

I need to control the metatags output (specifically the description/og:description).

This documentation looks like it would have been useful, but is empty:
https://www.drupal.org/docs/7/modules/metatag/howto-assign-meta-tags-to-specific-non-entity-pages-d7

Thanks.

There's a hook for that. Here's my implementation.
<?php

function mymodule_some_page_callback() {
  global $metatagOverrides;
  // ... generate your page ...

  $metatagOverrides = [
    'og:image' => 'https://example.org/the-image.jpg',
    'og:description' => 'Some description',
    ...
  ];

  return $thePage;
}

function mymodule_metatag_metatags_view_alter(&$output, $instance, $options) {
if (!empty($metatagOverrides)) {
  foreach ($metatagOverrides as $tagname => $value) {
    if (array_key_exists($tagname, $output)) {
      $output[$tagname]["#attached"]["drupal_add_html_head"][0][0]["#value"] = $value;
    }
    else {
      $output[$tagname] = [
        '#attached' => [
          'drupal_add_html_head' => [
            [
              [
                '#theme' => 'metatag_property',
                '#tag' => 'meta',
                '#id' => "{$tagname}_0",
                '#name' => $tagname,
                '#value' => $value,
                '#weight' => 100,
              ],
              "{$tagname}_0",
            ]
          ]
        ]
      ];
    }
  }
}


How to remove custom module provided entity instances by the time the module being uninstalled? I have the following use case:

I have a custom module, which defines a custom entity type.
The custom entity type has some content in the database.
Module needs to be uninstalled now, but it can't, since "There is content for the entity type" (which is true, there is content)
How to extend the uninstall process of the module to first remove all the content instances and then do the rest?

I tried hook_uninstall, but that didn't help. Any ideas?
Content can't be uninstalled by hand! (bigger project issue)

A potential duplicate.

The short answer (as I can see), you CAN'T right now remove content by the time you uninstalling the module. That makes you (us) to do it in two steps:

Write a update_hook where you remove all the content of the custom entity
You uninstall the module.
(drush cex, which removes the module from
    core.extension.yml)


Problem configuring the Calendar module I'm having trouble with Drupal 7 and the calendar (version 7.x-1.0-alpha3) module. The default view is working. It is showing the nodes based on the time they were updated.

I added a date field called time1 to a basic page node type. I added some basic pages with date set for the current date.

I don't know how to make the calendar show the nodes based on the value of time1. I've tried to change the argument as in the picture.

The README.txt of the module says that look the documentation on the project page. However, there is no documentation that applies to Drupal 7 in here http://drupal.org/node/262062

Has someone drupal 7 and the calendar working? What am I doing wrong here?

I don't know could this be related to http://drupal.org/node/1096224
For me none of the month, week or day views are working.

Views 3 has been completely changed; the API has been rewritten. Make sure Calendar is compatible with that version of Views.
Check the Calendar issue queue to see if there are reported issue.


Validate new user email name matching a pattern on registration Upon new user registration, how could I validate that the email address has a ".edu" extension? Basically, I need to ensure that users are using only their ".edu" email addresses to register for accounts.

Try something like this, add a validate to user_registration_form and then in validate check email with your pattern and if not match use form_set_error. something like below

function registration_check_form_user_register_alter(&$form, &$form_state)
{
    $form['#validate'][] = 'registration_check_user_register_validate';
}
function registration_check_user_register_validate($form, &$form_state)
{
        $email=$form_state['values']['email']['und'][0];
        if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)\.edu/i",$email))
                {
                form_set_error('mail', t('Email NOT VALID,TRY EMAIL WITH .EDU'));
            }
}


How do I compare a shipping address with a profile address field? Does anyone know if its possible to set up a rule that would compare the users core account shipping address field (not a commerce profile) to the shipping address field used on the check-out form during check-out?
I have the site configured to auto-populate the billing and shipping address fields during check-out using the core account shipping address field (which uses the "Address" module), not commerce shipping profile so that my client can control a list of registered shipping addresses for a B2B site. The customers need to be able to either use their registered shipping addresses, or enter a unique shipping address and pay $3.00.
What I need to do is determine if the user over-wrote the auto-populated shipping address value with a custom address (which implies they are attempting to drop-ship their order to a residential location, and therefore adds $3.00 to the order total) by comparing the value in the shipping address field used during check-out to the value in the core account shipping address field. And if they DO NOT match, add three dollars to the order.

You could make a custom module and add in there a custom rules condition that checks exactly what you need
The tiny book of rules contains great examples how to implement custom conditions www.drupal.org/files/tiny-book-of-rules.pdf

Also you could try do the same thing with the default rules condition (e.g. entity has field and entity field has value) but i think is much more hard to get relationships this way

If you choose to go with a custom condition function I suggest you set the default argument as an order type and the use functions like this one http://www.drupalcontrib.org/api/drupal/contributions!commerce!modules!customer!commerce_customer.module/function/commerce_customer_profile_load_multiple/7 to get the shipping profile and then the address you want to compare. You may load the current user simply by using global $user; . The devel module and the dpm() function is a great help to see what is available during development in an object.


log publish/unpublish actions For certain node types I want to log/track each time the publish status changes from published to unpublised and from unpublished to published. I am aware I could do this with rules and write log entries into the standard log, but I don't think this is a good solution.
I prefer to have a specific logtable for that, so that I can export it and that I can also show the history in a special tab of the node.

I was doing now some research, but could not find anything in this direction.

Is there a module I have not seen and which would be the solution?

If not, what would be the best approach?
Thanks

The only module I can think of is Workbench Moderation. It may be much too large and complex for your needs, but within the node's "Moderate" tab, it provides a list of all editing actions including the change of the node's status.

Screenshot


D7 Unique page/profile per user I am working a lot with views and panels to figure this out but i cant.

When user register account i want for him to be able to make his own profile visible to everyone.
Profile is 1 page user can create with custom content type (maybe there is something better to use?) with info from taxonomy vocabulary, random text, a gallery and a calendar.
Since there is lot of info to write in i want to separate this in few steps.
So i would like to divide page in few regions that look same for all users. Gallery on left side, taxonomy terms and random text in middle, calendar on right side or in block. Each region editable by user who made it. All info on that specific page must be only from user that created it (only userA pictures, userA calendar, userA random text on. All on 1 page).

I worked a lot with panels and views but i have no idea how to make all of this in a way that all info created by 1 user is on 1 page, viewable by everyone on that page.

I managed to use views to collect info from all users in 1 field/block/page so i know some basics. Also used panel to divide for example /home in more regions to.

Cheers!

This should really be pretty simple if you have created the Views properly.

You need to make the views select only the content that the user provided through an argument, fx uid = 5 would should show content user with uid 5 created.

Then it's just a matter of creating a panel page that has the uid in the url, fx user/[uid]/profile and pass the uid to the views when you insert them on the page, which then will display the correct content.


Remove width and height from img tag in Drupal output (for certain content type) I want to remove width and height properties from img tags in certain content type

Currently it show's like this

but I want

function mytheme_preprocess_image(&$variables) {
  foreach (array('width', 'height') as $key) {
    unset($variables[$key]);
  }
}

copy this on template.php (replace "mytheme" to ur theme name) but you need to control over this because it will remove dimensions of all images in your theme.


Is there an easy way to include a Facebook remarketing tag in my D7 site? Adding Google Remarketing Script tags to Drupal 7 website shows how to add a Google remarketing tag using a module. Is there a similar solution for adding a Facebook remarketing tag easily?

I would use the drupal_add_js hook if that were so easy, but the issue is that the remarketing tag also includes an <img/> element (the pixel) in a <noscript> tag, so I can't include that easily in the same hook.

Turned out to be very simple. All I had to do was paste the code into the <head> part of html.tpl.php from within the /templates/ folder.


Why are URLs with non-existing subdomains not triggering an error 404? One of my websites ignores random subdomains. The site doesn't have any subdomains but it will happily accept URLs such as fjiddifjdskdjf.example.com or dsfkljsdflsdjfds.example.com.
In both cases, it will display the home page. Similarly, I can log in at sfkjsdidisfdj.example.com/user.

At first, I suspected the problem was with a .htaccess file I put in the root directory. The file is used to redirect URLs that changed when I redesigned the website. It's got entries like this.

RedirectMatch 301 ^/2012/06/$ /blog/201206

However, after renaming the file, it's still accepting these odd, random subdomains.

I've also checked another Drupal site I maintain. On that site, entering a non-existent subdomain results in an 404 error. I've compared both sites' standard .htaccess files and they're identical. Both sites use the same (shared) hosting package, which should rule out differences in how the server has been configured.

Why URLs with non-existing subdomains don't trigger an error? How can I correct this behaviour?

While you have stated that hosting is the same for both your sites it is most probably that this is either a server configuration issue or a DNS configuration issue rather than a Drupal setting issue.
In .htaccess the following catches 'wildcard' subdomains

RewriteCond %{HTTP_HOST} ^[^.]+\.example\.com$ [NC]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://example.com%{REQUEST_URI} [L,R=301]

In Apache configuration the following catches 'wildcard' subdomains

<VirtualHost *:80>
        ServerAlias *.example.com
        Redirect 301 / http://www.example.com
</VirtualHost>

In Nginx confiuration the following catches 'wildcard' subdomains
(as you are using .htaccess you are obviously not using Nginx but for completeness..)

server {
  server_name *.example.com;
  return 301 $scheme://example.com$request_uri;
}

server {
  server_name www.example.com;

  #add in further directives to serve your content
}

These are the most common configurations that will catch wildcard sub-domains on the server.

It is possible to do redirects in settings.php also but not for wildcard.

The other possibility is that the issue is at the DNS entry. You may have set up a wildcard sub-domain which may also be known as a catch-all-subdomain.

The layout of this will be determined by your DNS provider.
This Drupal guide illustrates how it would be acheived on cPanel: https://www.drupal.org/node/1068894


How to position an element using jQuery UI .position method? I'm going on about 20 hours trying to get jQuery UI to work, and fortunately, I'm still not frustrated. I just really want it to work. I would like to use the .position method to position an element in the top right corner relative to #page, (http://api.jqueryui.com/position/).

I'm not sure which version of jQuery this method requires, so I'm using the newest version, 1.10.2. It wasn't so hard to implement. I'm using the jQuery Multi module, and my script uses the alias as per instructions. (I tried using the jQuery Update module, but that just seemed to break everything, so I found jQuery Multi).

This part seems to be working. The file, jquery-1.10.2.min.js, shows up in the head of my HTML parallel to Drupal 7's 1.4.4 version. I'm getting an alert message when I write a test alert so it seems to be finding the function. If I delete the jquery-1.10.2.min.js file, the alert quits working and when I add it back it works again, (after clearing caches).

I've added the jquery.ui.core and jquery.ui.position libraries from Drupal core (both versions are 1.8.7) using drupal_add_library() in a preprocess page function. Like this...

function marigold_zen_preprocess_page(&$variables, $hook) {
  /* Add jQuery UI libraries - http://jqueryui.com/ */
  drupal_add_library('system', 'ui');
  drupal_add_library('system', 'ui.position');
}

Both of these files show up in the head of my HTML also.

Now I add the code to test out positioning the submit button in the top right corner of the page...

(function ($, Drupal, window, document, undefined) {
  $(document).ready(function() {
  //  alert("This is working");
    $( "#edit-submit" ).position({
      my: "right top",
      at: "right top",
      of: "#page"
    });
   });

})(jq1102, Drupal, this, this.document);

Nothing happens, and I get no errors in the console. Nothing is positioned differently. Again, if I uncomment the alert, it shows when I refresh the page, so I think that means that it's reading the function, yes?

If anyone can help me out here, I'd be so incredibly grateful. I was up till past 4am yesterday, woke up about 8am, and I've been at it all day again today. It's nearly dinner time, and I'm still stuck.

P.S. - Drupal 7.24

I think the problem is that you need to also load the UI libraries using the newer jQuery version. jQuery UI is a jQuery plugin, so it attaches to jQuery itself. Within your function $ refers to jQuery 10, while the UI plugin is loaded for Drupal's jQuery.

To fix this you have to use jQuery Multi to also load the libraries with the newer jQuery. You can use hook_jqmulti_files():

function mymodule_jqmulti_files() {
  return array(
   'path/to/file.js',
   'another/full/file/path.js',
  );
}

You'll need to specify the file paths, which you can put together using drupal_get_path() or get using drupal_get_library(). Once you do that jQuery Multi will automatically load those files in the newer jQuery context and then .position should be available to you in your function.


Customising the views content template This is all fairly new to me so I hope i've worded the question correctly.

So I have created a view which outputs a list of news posts, which you can then click on a news post and view the contents of that post. However I've modified the styling of the listings page using the different fields etc. Now I would like to modify the content of the selected news post.

I've created a new template in my templates directory called 'views-views.tpl.php' but that seems to override the content for the listing view landing page as well as the content.

Do I need to use a different template?

If someone could point me in the right direction it would be mostly appreciated.

Thanks.

Step:1 : You have to choose the format
 Step:1 For this Image

Step:2: Click the Advanced link and go to theme:information
 Step:2 For this Image

Step:3 Choose the style output templete like : Step:3 For this Image

Step:4 Add tpl file and write your css and all. Rescan the templete files and save it..

I choose the style format like HTML List. So I Can wrote codings like this format:Codings


Can I still start a "stable" D8 project now that D9 is stable? Trying to start a new Drupal 8 project today:

$ composer create-project --no-install drupal/recommended-project my-recommended-project

But this now installs Drupal 9.0.0 instead! :mindblown:

So I tried to manually require 8.9:

$ composer create-project --no-install drupal/recommended-project^8.9 my-recommended-project

But:

Could not find package drupal/recommended-project^8.9 with stability stable.

So it seems like I will need to install ^8.9@dev

But then the whole project will be ... unstable?

What do you recommend?

You are missing a :

This works:
composer create-project --no-install drupal/recommended-project:^8.9 my-recommended-project


how can add external php function or class to theme file? As I asked above, is it possible to add or include externally written classes or functions files to drupal theme files e.g 'theme_name.theme' file?

A .theme file is processed as PHP - anything you can do in a PHP file, you can do in your theme's .theme file.

So if you want a service:

$some_service = \Drupal::service('foo');

Or a function from a module file:

module_load_include('inc', 'foo_module');

And so on.


Drupal 7 - how to use jw player using videos located on a CDN We are currently using Drupal 6 and are in the process of upgrading to D7.

When I went to see if the module created by LongTail had a version compatible with D7 I found out that they don't have one, but they recommended to use this one:

http://drupal.org/project/jwplayermodule

The problem I'm currently facing is that I can't figure out how to use this module with videos that we already have in our CDN.

Any way to do this without having to upload my videos to the site?

Thank you,

Onema.

I did something similar for flowplayer. I had nodes created for legacy videos stored in Amazon S3 and added this code to the node--video.tpl.php:

 $mediaid = $content['field_mediaid']['#items'][0]['value'];
  if ($mediaid != '') {
      $video2 = '';
              flowplayer_add('#player', array(
                'clip' => array(
                  'autoPlay' => TRUE
                ),
              ));

        print '

';
        print $video2;

There are other player options available as well, video.js seems to be more modern.


How does form API work for CCK (and other #after_build processes)? When you want to hook into a CCK form and alter something, you are usually required to call a custom function from $form['#after_build'] (right?).

When doing so, I have noticed I can't write $form['field_name']['#disabled'] = TRUE; but instead I have to use the #attributes approach.

Why? Am I doing something wrong?

The form API is usually doing that for you, but it probably does that before calling the after_build functions.

The #after_build functions are called in form_builder(), #disabled handling is in _form_builder_handle_input_element(), which is called earlier in form_builder().


some css of same file getting processed some not In my custom theme I have two stylesheets; style.css and nice-menu-custom.css.

If I would change some silly old css for testing - like body{color:lime;} it would affect the site as normal. However, some other css changes to the same file that get uploaded just simply don't affect the site. None of the width or float properties are working I have the impression.

You would think I'm just not writing proper css, but the thing is if I make the same changes in firebug, it works fine. for instance body{width:50%;} does it's job when using firebug, not when uploading that same code from my stylesheet (i.e. the same stylesheet as from which I upload the changes that DO work) on the server.

I verified if the new changes actually uploaded by trying to upload the changes, shutting down the FTP program and then starting a different ftp program to see if these changes would be stored on the server. And they were.

Made sure:
Caches were cleared often
CSS Compression turned off

So in short: if I go and see in chrome developer tools, to read my stylesheet from the server, under the 'resources' tab -second from left, I can see the changes to my stylesheet that I uploaded and should work. Yet when you look at the site the changes aren't made. Plus if I made the same changes using the developer tools themselves, under the first tab 'elements', the changes would actually take effect. I just don't understand.

It was a syntax error after all...forget one curly bracket somewhere in my stylesheet.
I never expected a syntax error in css to cause this kind of difficulties. I.o.w. I unconsciously assumed it couldn't be syntax and therefore it never crossed my mind. Lesson learned: never assume even when you don't realise you're assuming!


How do I know which products have seen other customers when they took a look at the product that I am currently looking? I am developing a website with the Drupal Commerce module, and my customer wants me to implement a functionality to allow the purchaser to know which products have seen other purchasers/customers when they saw the same product he is currently watching.

Do you know if any specific module for Drupal Commerce is available, or can I use a combination of modules that have nothing to do with the Drupal Commerce module?

Yes the feature you are asking after is this module.
Commerce Recommender

:: Updated, Here is a tutorial on how you can achieve what you are looking for

Drupal Commerce recommender tutorial


how to compare two content type fields and filter the output by drupal views? I have two content types.

*content_type1
*content_type2 [set as content profile]

In content_type1, I have a taxonomy term [user has to choose any one of term] and content_type2 has cck select list field with same terms as content_type2.

I created two roles:

*role1 users can create content_type1
*role2 users can create content_type2

Now I want to display list of content_type1s in user role2 profile page whose "select field  Value" is as same as the "taxonomy term " of content_type1.

How can I implement this using drupal views?

Seems to me that you're going to need this:

views_embed_view()  inside of the user_profile.tpl.php

more specifically:

First set up a view to return content type 1 nodes, that takes an argument of taxonomy term id.

Then, assuming you can get the content type 2 node into user_profile.tpl.php, grab the select list value like so:

<?php
    $selected_value = $content_type2_node->field_selectlistname[0]['value'];
    $term_id = taxonomy_get_term_by_name($selected_value);

?>

note use of taxonomy_get_term_by_name()

and use of a cck select list field named is field_selectlistname, update that to your field name.

then you can use this:

<?php
   print views_embed_view("view_name","block_1",$term_id);
?>

to print out your view.

Note that the first two arguments are the view name of your view, and the display id, which is going to be something like 'block_1', 'default' or 'page_1'

I'm assuming here you know how to set up the view, and know how to get that user_profile.tpl.php to work for your role.. (if isset($account->roles[ role id ])... )

good luck!


Use an exposed filter as contextual filter on another view The question is a pretty simple one, I've created a page-view with an exposed filter. The page-view itself contains a block-view. I was wondering if the value of the exposed filter (which is in the url) could be used as a contextual filter in the block-view.

So far I've tried 'get content ID from url' and  'get raw value'  but neither seem to work as the block-view returns no results.

Please follow below steps to achieve functionality that you are looking for.

Disable AJAX feature for view.
In the block view add a contextual filter and select type as Provide default value >> Type as php code.
In the php code read the exposed filter value using $_GET[]
Return the value you got from $_GET to contextual filter.

In that way you can able to pass exposed filter value to the contextual filter.


Main menu links not operational on front page when anonymous I have two links to 'published content' in main menu. This menu is displayed on all pages, including front page.

When I am logged in as admin, those links work well, but when I am logged out (=anonymous), those links are displayed, but not operational. It is as if they were plain text only.

Yet, when I access content directly with the proper URL as anonymous, those links do work properly in the corresponding page.

So, why don't they work on the front page when using anonymous mode? I have checked page source and the code is the same. I have checked permission and View published content is allowed for anonymous users.

Want could be the cause of this issue?

Update

For the records, I have also asked a question here. I tried to solve this issue with a Drupal Navigation Menu, but only the Home link works, not the other link.

To solve this issue, I have created my own menu manually. It works, but...

Update II

I am using a simple plain vanilla system with panels everywhere. The theme is Versatile. I have header, footer, left, right mini-panels + central content in a default page variant. The right mini-panel just displays an instance of Main Menu. In fact, I have not created users. The site is meant to be used by anonymous people.

Update III

The issue only happens when the following CSS is applied:

.NCK_Menu {

    font-size: 103%;
    height: 240px;
    width: 120px;
    background-color: #5E88D0;
    margin: 10px 9px 10px 7px;
    padding: 7px;
    border:none;
    -webkit-border-radius: 1px;
    -moz-border-radius: 1px;
    border-radius: 1px;

}

It does not make sense !!!

The most often reason when you can`t see any kind of links in menu - are permissions for users. So please double check whether all of ones connected to your links (maybe modules/content types or whatever) are enabled for anonymous user.


Custom layout for a field in Drupal 7 with using a term id and term name I have a content type that has term reference fields. One is a select one and one is a select many. What i'm trying to achieve is to overwrite the output for these fields.

I want the output of these 2 fields to be {artistName} and {locationName}, {locationName}

These links will point to a page with an isotope grid layout on it, and will prepopulate the filters with what is in the querystring.

I have found how to update the output of the field, but I have no idea on how to get the terms ID and terms name.

function TEMPLATENAME_preprocess_field(&$variables) {
  if($variables['element']['#field_name'] == 'field_artist') {
      $variables['items']['0']['#markup'] = 'View Map';
    }
  }
}

Thanks.

After looking at https://www.digett.com/insights/change-output-single-field-drupal-7-node I realised that you can use $variables['element']['#items']

term id
$variables['element']['#items']['0']['tid']

term name
$variables['element']['#items']['0']['taxonomy_term']->name


Datepicker and form_state with different formats I'm using custom form for getting results from a web service.

This is a part of my form

<?php

$form['starting_date'] = array(
   '#type' => 'date_popup',
   '#title' => 'Starting date',
   '#date_format' => 'd.m.Y',
)

As you can see I'm using the date_popup from the Date module.

It's displaying correct with this format d.m.Y. but after submitting the form, I've got error from a web service, because the string I'm passing . form_state['values']['starting_date'] . on print, the values are with different format.

Lets say a user selects 10.02.2014 (today), the form_state displays as 2014-10-02.

How can I fix that? The web service has to receive only with this format d.m.Y to display the results, otherwise it doesn't work.

1.Add a js file to the module and
2.In the js add the following code using the id of date field
to change the date format of the date picker
3.check the link for reference

$( ".selector" ).datepicker({ dateFormat: "yy-mm-dd" });


How to share Drupal code across multisites that are each in subdirectories? I have two websites on my own server (I have full control of the Apache config, etc.)

I want to install Drupal 'into' each of them, in a subdirectory of the site root.

I'd like to share a Drupal codebase between the two.

And, I'd like to have the URLs appear without the subdirectory.

My problem is I can't figure out how to do all at once.

I can get to this easily,

/src/www
  /website1
    /drupal1
       ...
       sites/website1.com/themes/website1.com
       ...
    /other_stuff_1a
    /other_stuff_1b
  /website2
    /drupal2
       ...
       sites/website2.com/themes/website2.com
       ...
    /other_stuff_2a
    /other_stuff_2b

But I'm not sure how to share the Drupal7 code in this case.  Do I have to use symlinks or something?

I'd appreciate any help or ideas.

Frank

Drupal come with already a multi site feature, you ca read more about it here.

After, if for some reasons you don't want install Drupal with multi-site and keep the both separate in your server, you can still use Git or SVN and co.

The idea is simple, you've the same codebase for development and multiple clone or checkout in your server. For example, in your case it will be drupal1 and drupal2.


how to Search profile type in drupal 7 I created a profile type for users to upload their data using fields and I want other users (registered or anonymous) to have access to a search form and they can search for anything on any user's profile (name, jobtype, gender, etc)
if a another user searches for a string in job search, the entire information should be accessible?

I have an idea. This can be done by "Webform". Use a form as user profile, and set limit 1 form per user in "Form settings". Then use "Permission per webform" to make this form access webform results for all user. To display in search, it can simply be done by Views.

Update: another idea I found is to use "View profiles permissions". This module provides permission to view user profiles depending on what roles the profile requested to be viewed.


Webform submission via URL supplied data Is it possible to submit data to a webform by providing the data in the URL of the webform page - or some other means of remotely providing data?

I have no idea if anything like this is possible but I am trying to keep email records within Drupal rather than use a simple script.

Webform MySQL Views

  These views may be useful when you need to access this data from an
  external application in an automated fashion without exporting,
  importing, or the use of a web-based API.

View will be automatically updated whenever you add, remove, or reorder the components for that Webform.


How do I use node_load() with an array as first parameter? In Drupal 6, I would use the following code.

$nodes = node_load(array('title' => $vcenter_name, 'type' => 'vcenter'));

What is the equivalent code for Drupal 8? I could use node_load($nid), but not node_load(array('title' => $vcenter_name, 'type' => 'vcenter')).

UPDATE

As per the answer , am getting the the $nodes array as

Array
(
    [1147] => Drupal\node\Entity\Node Object
        (
            [in_preview] =>
            [values:protected] => Array
                (
                    [vid] => Array
                        (
                            [x-default] => 9272
                        )

                    [langcode] => Array
                        (
                            [x-default] => und
                        )

                    [revision_timestamp] => Array
                        (
                            [x-default] => 1452106357
                        )

                    [revision_uid] => Array
                        (
                            [x-default] => 0
                        )

                    [revision_log] => Array
                        (
                            [x-default] =>
                        )

                    [nid] => Array
                        (
                            [x-default] => 1147
                        )

and i can't access the fields like $nodes->field_name[0]->value;

But how i get like this :

Drupal\node\Entity\Node Object
(
    [in_preview] =>
    [values:protected] => Array
        (
            [vid] => Array
                (
                    [x-default] => 9173
                )

            [langcode] => Array
                (
                    [x-default] => und
                )

            [revision_timestamp] => Array
                (
                    [x-default] => 1448312269
                )

            [revision_uid] => Array
                (
                    [x-default] => 0
                )

            [revision_log] => Array
                (
                    [x-default] =>
                )

            [nid] => Array
                (
                    [x-default] => 1107
                )

The equivalent of $values = array('title' => $vcenter_name, 'type' => 'vcenter'); $nodes = node_load($values); for Drupal 8 is entity_load_multiple_by_properties(), whose first parameter is the entity type, differently from node_load().

Since entity_load_multiple_by_properties($entity_type, array $values) is deprecated, you should use the following code.

$nodes = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->loadByProperties($values);