How to add more data to a field I'm trying to find the best way to extend a field's data set (not even sure of the right terminology).

What I want, is to attach some other information to an existing field. Let's take a file field, called "my_file", and attach some "other" information to it.

The end result should be, when using node_load and entity_metadata_wrapper, I can get the "other" value.

So these code snippets should give me the value:

$node = node_load($nid);
return $node->field_my_file['und'][0]['other'];
// And this should work:
$wrapper = entity_metadata_wrapper('node', $node);
return $wrapper->field_my_file->other();

I'm not that familiar with the Field API, so if you can point me in the right direction that'd be good.

Hm, if I understand you correctly you want to extend a fields schema. As far as I know, there is no easy way of doing this, e.g. there is no hook_field_schema_alter(). And the way that comes into my mind to achieve this is rather complicated and involves a lot of different hooks and logic that seems just bloated and error prone.

Instead I would recommend to create a new field type module based on the one that you want to extend, then alter this so that it suits your needs. Obviously this should only be done if you are still in the development phase of your site. If there is already any content this could do more harm than good, because you would need to migrate the content.

Another way, little elegant, but certainly possible is to create your proper storage solution for the information that you want to attach to the field(s) in question, meaning providing custom database tables and implementing the hooks described in field.api.php that you need for your use case.


Content types & ubercart I have another question about ubercart. I have a content Type hotel & a content type tript (city trips etc) that people can buy, (just one price). I really don't know if it is possible to add my content type to ubercart so i do not have to add this all again manually.
I hope this question is clear.

Thanks

I'm pretty sure that if you go to admin/store/products/classes and add a class where the Class ID is the same as the machine name of the content type that Ubercart will pick it up as a product type.


Exposed filters in views with Ajax turned on doesn't generate url When using an exposed filter in a view while turning on Ajax doesn't generate a unique url.

Page with Ajax off

  nl/finder?product%5B284%5D=284&industry%5B269%5D=269&country%5B288%5D=288&country%5B290%5D=290

Page with Ajax on

  nl/finder#

Is this normal behavior of drupal or is there some setting i'm missing? I need to link to the page with some filters preset.

Use Views Ajax history to accomplish what you are asking. There are a couple of bugs when using supporting modules such as Views Infinite Scroll, but for the most part this allows you to keep browser history as you add filters and change pages, allowing your user to use the forward and back buttons in their browser.


How can I override apache solr's default search result sorting? According to this, search results are ordered by relevance score. How can I override this? I want our results sorted by created date. I'm not talking about allowing users to sort by different fields, just the default order of results returned by apache solr.

This requires a custom modules where you implement a hook provided by apachesolr. There are several options but hook_apachesolr_modify_query(&$query, &$params, $caller) works as well as any.

You can modify the $query:

$query->set_solrsort($field_name, $direction);

Or you can modify the $params:

$params['sort'] = "$field_name $direction";


Install Vanilla Wordpress to Drupal to use Vanilla Forum any one knows how to install vanilla forum to drupal. I try to search a good article but could not success.I need step by step to do this.

You might need to install Orchid. Only by using this module you can integrate Drupal with Vannila Forum.


How do you edit the link count on /poll index page? In Drupal 7 how do you increase the number of polls listed on domain.com/poll ?

The current limit appears to be 15 polls per page and then there is pagination at the bottom. I would much rather have all my polls listed without pagination.

Is there anyway to increase the number of polls listed?

It's hard coded in poll module poll.pages.inc file...

function poll_page() {
  $polls_per_page = 15;

  $count_select = db_select('node', 'n');
  $count_select->addExpression('COUNT(*)', 'expression');
  $count_select->join('poll', 'p', 'p.nid = n.nid');
  $count_select->condition('n.status', 1);

  // List all polls.
  $select = db_select('node', 'n');
  $select->join('poll', 'p', 'p.nid = n.nid');
  $select->join('poll_choice', 'c', 'c.nid = n.nid');
  $select->addExpression('SUM(c.chvotes)', 'votes');
  $select = $select->fields('n', array('nid', 'title', 'created'))
    ->fields('p', array('active'))
    ->condition('n.status', 1)
    ->orderBy('n.created', 'DESC')
    ->groupBy('n.nid')
    ->groupBy('n.title')
    ->groupBy('p.active')
    ->groupBy('n.created')
    ->extend('PagerDefault')
    ->limit($polls_per_page)
    ->addTag('node_access');
  $select->setCountQuery($count_select);
  $queried_nodes = $select->execute()
    ->fetchAllAssoc('nid');

  $output = '
';
  foreach ($queried_nodes as $node) {
    $output .= '
' . l($node->title, "node/$node->nid") . ' - ' . format_plural($node->votes, '1 vote', '@count votes') . ' - ' . ($node->active ? t('open') : t('closed')) . '
';
  }
  $output .= '
';
  $output .= theme('pager');
  return $output;
}

Override the menu item using hook_menu_alter and change the callback as well as setting which you can see in first line of above function using a custom module.. Otherwise use views to build your own page which will display polls...


Admin user can't administer the site When I sign with admin user (or any other user), I can edit the contents, I can edit user, I can´t create user, I can`t Edit nodes, I can´t install upgrades, I can´t install modules, I can´t save anything.

Thanks.

If you can't do all that with the superuser (typically admin, user ID 1), checking permissions won't help, since that account has a "pass all permissions" check on nodes, modules, users, etc.

To figure this out, you can try a few things:

Go into the database and check if your admin user really has uid 1 (in the users table)
Check modules (custom modules, specifically) to see if any of them deny access to any admin pages


How to approach scheduled rules to real deathline? Hello Im facing a problem, I made an app that makes use of a lot of scheduled rules, I could notice that those rules are not executed exactly in the time that is indicated in the schedule, those rules executes with the CRON, so for example if the rule reaches the deathline it only is executed after run of CRON.

So I had to set the CRON to run more frequently but is there another way of make the rule executes exactly in the set deathline?

my app needs to be very accurate in the execution of those scheduled rules so that's why...

Thank you

Rule scheduler works with CRON only so you have to run CRON frequently, but you can use Elysia Cron module, where you can specify different schedule for different hook_cron(), so if you want your rules scheduler to run frequently then configure rules_scheduler_cron() to run say every five minutes and  configure other hook_cron() to run every two hours.

In that way you run reduce the load.


Find the total amount of multiple products of the same type - Commerce I've created a rule that sends a thank you email to anyone who donates less-than-or-equal-to a certain amount (which works perfectly), but I cannot figure out how to pull out the total $ amount of all donations on the order and include it in the email.

If it were guaranteed there would only ever be a single donation line item the issue would be simple.  However, there is no guarantee there won't be more than one on a single order, and there will usually be at least one other line item of a different product type included in the order.  I've searched, but cannot figure out how to, for example, calculate the total donation amount for an order that has 2 donation line items of $10 & $20, plus one or more other line items of a different product type, then put the donation total into the thank you email that gets sent out.

Any / all help will be much appreciated!

Use commerce_donate module to get donation then this field use in your rules

Create a rule add events in Rule
Add condition entity has a field (your donation field)
Add variables in this you can use php field to get total amount of donation.
Add action in email section use token of variables

I am not already try this but hopefully this may work.


Webform-CiviCRM integration: autocomplete employer I set up a Webform for a Membership Application. I followed the instructions on this page for setting up an Autocomplete for the Organization the new Member belongs to:

http://wiki.civicrm.org/confluence/display/CRMDOC/Webform+CiviCRM+Integration#WebformCiviCRMIntegration-CurrentEmployer

This works fine when I am logged in (as an administrator), and it auto completes the organization name with options from the database.

But when I test the form when I'm logged out, it doesn't recognize any organization names that I know are in the CiviCRM. Furthermore, when I try to add a new organization it doesn't get added to the database.

Any ideas why this might be happening?

The anonymous user does not have permission to view contacts in your database. Be thankful for this default, it can save you from accidentally exposing your entire database to the world!

You can override this default by editing the "existing contact" field (from the webform tab) and unticking "Enforce Permissions". Typically you would also set one or more filters on that form (e.g. pick a group) to limit the autocomplete to just the organizations you want to expose.


Version of Drupal is no longer supported [Using the latest 7.42 release]. After automatic update I use Drupal with Commerce Kickstarter profile installed. After automatic update from Installatron in my Direct Panel i get an error of unsupported Drupal Core version:

There's no way to make update using Drush or Installatron from that state.

The only way to make it work, that I have found, is to revert to the backup before update. Can anyone help me to understand what's happening, and why  Installatron updates to the 7.42 version (7.41 -> 7.42) while Drupal Report state of 7.41 v. states that it is up-to-date?

You updated Drupal core outside of updating the entire distribution. You're seeing this message because of the Distribution Update module and having upgraded outside of the distribution.

On that note, CK 2.32 uses Drupal 7.41. I will roll CK 2.33 with 7.42


After saving a new comment How to fetch all comments for a given node? Is it possible to fetch a list of comments for a given node by using the rule After saving a new comment? After this I would like to change a taxonomy term for a certain comment having a certain term.

If your rule reacts on event "After saving a new comment",
add a Loop in actions section and select comment:node:comments as a selector.

The loop will go through an array of comments from commented node. There you can specify additional actions/conditions that you wish to perform on each comment.

PS: You will run in the issue of not being able to modify comment fields via Rules

  "Unable to modify data "field-taxonomy-term": Entity property
  comments doesn't support writing."

Here is more information about the issue:

"The selected data property doesn't support writing." when Action: Set a data value is applied to a taxonomy field:tid
How to fix entity property X doesn't support writing, when setting content type field values?


How can i add a span element within the search form using hook_form_alter? I’m trying to customize a search box that appears in the global header, using hook_form_alter. I’ve succeeded in changing the submit button to an image but still need to do the following 2 things:

add placeholder text that reads ‘Enter search terms here….’
and then add a

within the form itself. This is for future use, i’ll be coding the field to hide/show when mousing over a search icon.

my hook_form_alter code is as follows:

function mytheme_form_alter(&$form, &$form_state, $form_id){
  if($form_id == 'search_block_form'){
  //dsm($form);
  $form[actions][submit]['#type'] = 'image_button';
  $form[actions][submit]['#src'] = drupal_get_path('theme', ‘mytheme’). '/images/search_trans.png';
  }
}

For the placeholder just add this line to the hook_form_alter

$form['FIELD_I_WANT_TO_ALTER']['#attributes']['placeholder'] = 'placeholder text';

The span can be done in a few ways but the shortest is

$form['hover_toggle']['#markup'] = '';


How to add HTML class to main menu list? Theme Developer shows me that I need to use theme_links()

I can use this function, but I want to alter markup for main menu only.

I've tried funtion names: mytheme_links__menu_main_menu or mytheme_links__system_main_menu

but it seems that these function aren't invoked.

One way to achieve this to create a theme key in your template file like this:

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

    $items['custom_main_menu'] = array(
      'variables' => array('links' => array()),
  );

  return $items;
}

And then use the function below

function THEMENAME_custom_main_menu($menu){
  $menu['links'][367]['#below'][526]['#attributes']['id'] = "news_ma_international";
  // this will add id to link # 367
}

Now to print the main menu in your page.tpl.php use something like this

 <?php $main_menu_tree = menu_tree(variable_get('menu_main_links_source', 'main-menu')); ?>
                <?php print theme('custom_main_menu', array(
                  'links' => $main_menu_tree,
                  'attributes' => array(
                    'id' => 'main-menu-links',
                    'class' => array('links', 'clearfix'),
                  ),
                  'heading' => array(
                    'text' => t('Main menu'),
                    'level' => 'h2',
                    'class' => array('element-invisible'),
                  ),
                )); ?>

I hope this will help!


How do I make a twitter scheduler on drupal 7? I basically want to make a twitter scheduler. What it does is ,it fetches the old tweets from my twitter account and queues them so that I can schedule them to be sent at a later time.
So the three main jobs of this would be --

Fetch tweets from my account.
Queue them
Schedule them to be tweeted as per the user.

Could someone please tell me what all modules Id require for the same?

Thanks
Appreciate it.

Create a node type ‘Tweet’
Create a Feed Importer
Add JSON mappings
Add the Import URL
Use some custom code or perhaps Rules in combination with Tweet module api to schedule and send tweets

Modules:

Feeds
Tweet
JSONPath Parser
Rules

Credits: http://www.bariswanschers.com/blog/easily-import-tweets-drupal-using-json-and-feeds


(How) can I implement a points system to track club member attendance/participation? I run a Drupal 7 site for one of my clubs at school. My eventual goal is to create a system where club officers can manage all sorts of information about our members through this site (such as contact information, which I've already got working). I want to have a system where perhaps a content type like "Club Event" (doesn't have to be an actual event like that found in the Date module) or "Club Meeting" is created and there is some field where club officers can essentially get a checklist of members and check off who attended that event. This content type would then also have a field where a certain point value is assigned to that node and whoever is checked off on the list will get a certain number of points added to their account.

Finally there should be some sort of view where officers can view a list of all members and the number of points they've earned/events they attended.

Does this sound like something realistic to do within the Drupal framework? If so, any suggestions as to what modules might be necessary? Would this be something the User Points module can be used for?

I've never written any modules for Drupal before, but I'm not opposed to getting my hands a bit dirty if necessary.

If it were me, I would first create a role for members. I would have each member register and then have an officer assign them the role member.

I would then use the views module to display a list of members by using a filter by role. That would allow a list of members to be shown.

Then, I would create an attendance table and a meeting table in the database. (You can do this through the next step if you want to learn how to create drupal db schema. I would probably have the fields:

meetingId
meetingDate
meetingDescription

The attendance table would have:

meetingId
userId

When a user attends, you create a reference to the meetingId from the meeting table and create an enter with the drupal user id. When you want to know who selected a given meeting, you select all userId's from the attendance table matching the meetingId.

I would then write a simple module that uses the forms api to create a meeting. Then, you would have another page that lists all of the users by selecting all the ones with the member role and again using the forms api you would add an entry for the attendance table for each person that was there.

So there would be one link and two coded pages now... one link to "view meetings" which would show all of the meetings. If you click on a meeting, you would be taken to the page which displays users. If the meeting was in the past (meaning some historical data exists), it should have historical attendance data. You can handle that in one of two ways... either show them the historical data and do not allow edits, or you show your original form but  populate the check boxes of people that attended. Otherwise, it is a new meeting and should just display the form. If it were me, I would allow edits and it simplifies the page because it is the same form, just populated with check-boxes if there is any data.

This is an excellent opportunity to learn how to write a module. It is very simple yet complex enough to show you the ins an outs of creating a Drupal module. Also, it has a clear and definable end result which will either work or won't.

You can check out the schema module for help creating the database tables through the module. This is a good thing to learn.

If you want to go one step further, you can expose your tables to views and use the views module to create the display portions of your data. Although you will still need to create the forms on your own.

Update: Thought, you could also add a notes column to the meetings so people could enter and save notes. Also, your imagination is the limit here. All sorts of other things could be done. However, I would keep it as simple as you can stand for your first module.


How to style checkboxes in Drupal? I use the Better Exposed Filters module. I need to style the checkboxes (change the background of the checkbox).

I tried to do with CSS, but it doesn't work. I use jQuery to add a class to the input of the checkbox, and then apply style for this class, but this doesn't work.

Does anyone know how to do this?

You simply can’t style a checkbox (+ radio + select) via CSS. You’ll have to include another jQuery plug-in to achieve your goal. Something like uniformjs. Hope this helps and answers your question.


How to create a script file I want to create a script file that I can call using a form on submit. For example I can use:

action="action.php?uid=1&method=deleteuser"

This would trigger the script to result in the function deleteuser in file action.php deleting uid 1. However, when I tried to create this file and put it in the home scripts folder it couldn't call basic drupal commands such as db_query. Where and how can I generate such a script file so that I can access drupals core functions?

You can make your script file with following statements:

<?php
define('DRUPAL_ROOT', $_SERVER['DOCUMENT_ROOT']); // Define the DRUPAL_ROOT constant which is used in many places.
$base_url = 'http://'.$_SERVER['HTTP_HOST']; // Again, this is used in many places.
require_once DRUPAL_ROOT . '/includes/bootstrap.inc'; // Include the boostrap file.
drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION); // Start things up to whatever level you need.
//drupal_set_message('custom script');
print db_query("SELECT title FROM {node} WHERE nid = :nid", array(':nid' => 1))->fetchColumn();
?>

But it is not a good practice to handle form submit or whatever.


Get currently active 'simpletest' user during test How do you retrieve the current 'simpletest' user during a simpletest.

During a simpletest is the $user GLOBAL from the test environment or the live environment?

Inside the test method?

No idea what in $GLOBALS['user'] is, but you certainly can't rely on it. You are never "logged in" in that context, you are only logged in when doing requests with drupalGet()/drupalPost().

If you used drupalLogin(), you can look for $this->loggedInUser. If not, then it's not possible, other than maybe doing a GET to /user and then trying to get the username from title.

Inside a page callback, $GLOBALS['user'] is the current user, just like you'd expect.


How to make a "title" a link Building a content type "news headlines." I want the title to be the headline and I want that headline to link to a outside URL that has the full story. This node-summary could then appear on the home page and in a view and not link to the node but to the outside story. I can make a link that does that but cannot figure out how to make the title do this.

What you can do is implementing a preprocess function for the node.tpl.php file, and alter the content of $variables['node_url'], which is the variable the template file uses when rendering the title.

  <?php print render($title_prefix); ?>
  <?php if (!$page): ?>
    <h2<?php print $title_attributes; ?>><a href="<?php print $node_url; ?>"><?php print $title; ?>

  <?php endif; ?>
  <?php print render($title_suffix); ?>

You should first verify $variables['page'] is not TRUE, since that means the node is being shown in its own page, which is not what happens, for example, when the node is shown as teaser in the front page or in a view.


Programmatically Add Features for Role assignment in Ubercart Drupal 7 product node I am trying to create a product programmatically and set it features for role assignment, that a user gets a specific role after he purchases, i tried all the ways i can but couldnt get it working. below is the code i used for adding it, but when i edit the feature for role assignment it doesnt hold the values i set in the edit feature form.

function add_product_feature($nid, $sku){
     // Insert new product into the uc_product_features tables
     $desc = "SKU: ".$sku."
Role:
     purchaser
Expiration: Global expiration
      (not overridden)
Shippable: No

      Multiply by quantity: No";
      $nid1 = db_insert('uc_product_features')
      ->fields(array('nid' => $nid,'fid' => 'role','description' =>
      $desc,
      ))
      ->execute();
}

Don't do that. Inserting into the DB directly can cause you problems down the road; there's already been code written to do what you're trying to do.

Look at the uc_roles functions/documentation and follow how it adds product features via uc_roles_feature_form_submit submission handler and its uc_product_feature_save() call.


How do I use the Drupal 7 API to change ownership of a comment This function function node_assign_owner_action() is provided by the Drupal 7 API to allow modules change node ownership,

I've searched, but not found a similar function that let me change the ownership of comments. Does anyone know how to change ownership of a comment without hacking the {comment} table directly, and without breaking existing incoming links?

I know that I can update the fields {comment}.uid, {comment}.name and {comment}.mail with the appropriate values, but as I understand things, contributed modules should never update tables "owned" by another module directly.

The only method I've found so far is to recreate the comment under new ownership.  This is not a good solutions because it will invalidate all incoming links that used the permalink associated with the original comment.

This changes the comment author details using the core comment API:

$cid = 12; // e.g get from db_select
$comment = comment_load($cid);
$comment->uid = 1;
$comment->name = 'admin';
$comment->mail = 'admin@example.com';
comment_save($comment);

You could also do something similar with a Rules component for use with VBO.


how should i send data form my custom module to a php file after submitting? I have a Drupal form like this:

    function myblock_menu() {
  $items = array();
  $items['my_module/form'] = array(
    'page callback' => 'my_module_form',
    'access arguments' => array('access content'),
    'description' => t('My form'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function my_module_form() {

      return drupal_get_form('my_module_my_form');
 }

 function my_module_my_form($form_state) {
      $form['name']['price'] = array(
        '#type' => 'textfield',
        '#title' => t('price:'),
        '#value' =>t('100'),
        '#size' => 6,
        '#field_suffix' => t('$'),
        '#disabled' => TRUE,
      );
      $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit',
      );
      return $form;
 }

And i have submit function:

function my_module_my_form_submit($form, &$form_state) {

 $form_state['redirect'] = 'result.php';
}

My problem: how can i get $form_state['values']['price'] inside result.php? or in another way: how should i sent my data to a normal php file?
I studied several similar questions but didn't get my answer!
one suggestion was storing data in database which is not proper for my module! another suggestion was using sessions which i couldn't manage it(between module and php file)!

If all you are doing in your submit handler is redirecting to result.php then you should instead make your form submit direct to there, so that all the form post values will be available in the $_POST global variable in result.php.

To do so, in your my_module_my_form() function add this:

$form['#action'] = '/result.php'

Edit:

As Clive has pointed out, you cannot post that field value as you currently have it because it is a disabled field.

To make that field post you either have to make it not disabled, or if you don't want the user to be able to edit it you can use a different field type.

You can use type value to pass a value straight through, however the user won't be able to see it before they submit as it is a type of hidden value.

If you want the user to be able to view the value but not change it you could have 2 fields, one disabled (or just an item field) one that the user can see but doesn't submit, and a second value type field that submits the value.


Enabling XML under PHP in windows - import_html module not working So I'm having a problem with import_html. Basically, when I run the import from the sight, all of the content I wanted (except for xml files) get imported but I get these errors and warnings repeatedly:

Warning: DOMDocument::loadXML(): Opening and ending tag mismatch: link line 7 and head in Entity, line: 9 in parse_in_xml_string() (line 159 of
C:\Bitnami\drupal\apps\drupal\htdocs\sites\all\modules\import_html\coders_php_library\xml-transform.inc).

User warning: Failed to cleanup namespaces and end up with a valid XML file in import_html_cleanup_namespaces() (line 1693 of
C:\Bitnami\drupal\apps\drupal\htdocs\sites\all\modules\import_html\import_html_process.inc).

Notice: Trying to get property of non-object in import_html_process_html_page() (line 875 of
C:\Bitnami\drupal\apps\drupal\htdocs\sites\all\modules\import_html\import_html_process.inc).

Warning: XSLTProcessor::transformToXml() expects parameter 1 to be object, boolean given in xmldoc_plus_xsldoc() (line 211 of
C:\Bitnami\drupal\apps\drupal\htdocs\sites\all\modules\import_html\coders_php_library\xml-transform.inc).

User warning: Nothing useful extracted via XML from that content in import_html_process_html_page() (line 903 of
C:\Bitnami\drupal\apps\drupal\htdocs\sites\all\modules\import_html\import_html_process.inc).

Notice: Undefined variable: tid in import_html_indexes_import_html() (line 27 of
C:\Bitnami\drupal\apps\drupal\htdocs\sites\all\modules\import_html\extras\import_html_indexes\import_html_indexes.module).

Notice: Undefined property: stdClass::$title in node_import_html() (line 81 of
C:\Bitnami\drupal\apps\drupal\htdocs\sites\all\modules\import_html\modules\core.inc).

Notice: Undefined property: stdClass::$import_html_create_menus in menu_import_html_after_save() (line 159 of
C:\Bitnami\drupal\apps\drupal\htdocs\sites\all\modules\import_html\modules\core.inc).

Deprecated function: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in charset_decode_utf_8() (line 2051 of
C:\Bitnami\drupal\apps\drupal\htdocs\sites\all\modules\import_html\import_html_process.inc).

When I run drush import-html,nothing gets imported and I get:

import_html found no XSL library support at all on this server! Need   [warning]
the PHP 'xsl' extension enabled in php.ini xml-transform.inc:31
Sorry, with no XML support there will be no content scanning AT ALL.     [error]
Aborting process. See the import_html_help.htm for info on enabling
XML under PHP. import_html_process.inc:724
WD Import HTML: Failed to process any node out of file                   [error]
'8ab24e480a68476f800648582eaabf43.html'
WD Import HTML:                                                          [error]
Failed to get any results from the attempted analysis of
8ab24e480a68476f800648582eaabf43.html.
The source file path was probably unavailable or not HTML.
WD Import HTML: No results! Failed to extract any new nodes            [warning]
Processing 1 files for import. Using default configuration settings.    [status]

Because I have a windows computer, I followed these directions for enabling xsl in php, and when I did so, I was able to get regular html files imported via the website import-html. But why am I getting these other errors?

The reason why drush was giving me the XSL library support error is because though I fixed the php.ini file in the drupal folder, drush uses a different php.ini file, so I had to modify that one in order to get the imports to work. Now, I get the exact same errors/warning when I import online as when I import via drush. i haven't been able to fix the warnings


Use Pictures For Labels Hello ive been trying to work out how to do this for years and ive a feeling its one of them eureka moments when i go 'oh aye thats how you do it'. I think thats why i have never been able to find anything on it.

Using Views 3 my lists look like this when using total views and total comments-

and i would like to get rid of the label for a wee pic like this-

Could anyone point me in the right direction?

Thanks

You can use CSS background image concept to show images instead of Views & Comments text.

It should be very simple & straightforward ! You just need to identify the unique id or class in the html to apply css to that. Below article should be a good starting point for you !

http://stopdesign.com/archive/2003/03/07/replace-text.html


How to programmatically create a add to cart form with quantity input? I want to programmatically create an add to cart form with quantity input and default as 1. I tried to use the code:

$form_id= commerce_cart_add_to_cart_form_id(array($product_id));
$product = commerce_product_load($product_id);
$line_item = commerce_product_line_item_new($product, 1);
$line_item->data['context']['product_ids'] = array($product_id);
$form = drupal_get_form($form_id, $line_item);

But it just get a hidden field quantity with value 1 and I cannot change the quantity value. How can I get a quantity input instead of the static value?

Interesting. I would have never thought to do this. A quick search in the commerce module produced this example:

<?php
// line 2649 of commerce_cart.module

// Extract the drupal_get_form() arguments array from the element.
$arguments = $element[$key]['#arguments'];

// Add the display path and referencing entity data to the line item.
if (!empty($entity_uri['path'])) {
  $arguments['line_item']->data['context']['display_path'] = $entity_uri['path'];
}

$arguments['line_item']->data['context']['entity'] = array(
  'entity_type' => $context['entity_type'],
  'entity_id' => $entity_id,
  'product_reference_field_name' => $field_name,
);

// Update the product_ids variable to point to the entity data if we're
// referencing multiple products.
if (count($arguments['line_item']->data['context']['product_ids']) > 1) {
  $arguments['line_item']->data['context']['product_ids'] = 'entity';
}

// Replace the array containing the arguments with the return value of
// drupal_get_form(). It will be rendered when the rest of the object is
// rendered for display.
$output[$field_name][$key] = drupal_get_form($arguments['form_id'], $arguments['line_item'], $arguments['show_quantity'], $cart_context);
?>

Which means you could do this:

<?php
$product_id = 1;
$form_id= commerce_cart_add_to_cart_form_id(array($product_id));
$product = commerce_product_load($product_id);
$line_item = commerce_product_line_item_new($product, 1);
$line_item->data['context']['product_ids'] = array($product_id);
$form = drupal_get_form($form_id, $line_item, true);
dpm($form);
?>

And you will see how it affects the quantity (makes it become a proper field). You're also missing the $cart_context that the core module uses to determine what to do with displaying/hiding fields.


Drupal module not getting menu blocks? I have a drupal module creating a new page using a menu hook. And I have menu blocks (menus displayed as blocks) that SHOULD be showing up on the drupal module page. But I cannot seem to get them to display? How can I get these menu blocks to show up? I tried added it to a menu and that did not work.

Create Menu

  $items['gift_cards'] = array(
    'title' => 'SELECT A CARD',
    'page callback' => 'uc_gift_certificate_order_page',
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

This is the function to make the page, it is simply a drupal form.

function uc_gift_certificate_order_form($form_state) {
    // This is the function that generates the required page for ordering the gift card.
    // Load the required datepicker JS/CSS
    drupal_add_css(drupal_get_path("module", "uc_gift_certificate").'/datepicker/css/datepicker.css');
    drupal_add_js(drupal_get_path("module", "uc_gift_certificate").'/datepicker/js/datepicker.js');

    // We already have the block part (gift card rotator)
    // Display the form
    $form['#attributes'] = array('class' => 'gift-card');
    DRUPAL FORM API STUFF
}

Page callback should be drupal_get_form in your hook_menu and form definition handler should be passed as argument.

$items['gift_cards'] = array(
   'title' => 'SELECT A CARD',
   'page callback' => 'drupal_get_form',
   'page arguments' => array('uc_gift_certificate_order_page'),
   'access callback' => 'user_access', // no need to define in case of user_access
   'access arguments' => array('access content'),
   'type' => MENU_CALLBACK,
);


When I try to modify a view, I get a screen full of odd text I have just installed views, and every time I attempt to change a setting (or cancel) I receive a white screen with paragraphs of strange info:

[{"command":"settings","settings":{"basePath":"\/forms\/","pathPrefix":"","ajaxPageState":{"theme":"blogon_responsive_theme","theme_token":"cD6VFX2j18jV0Gu1-xq10ADeBk_yP4V57yKYNYhNnhs"}},"merge":true},{"command":"viewsDismissForm"},{"command":"viewsShowButtons"},{"command":"viewsTriggerPreview"},{"command":"insert","method":"html","selector":"#views-tab-page","data":"\u003Cdiv id=\u0022edit-display-settings-details\u0022\u003E\u003Cdiv id=\u0022edit-display-settings-top\u0022 class=\u0022views-ui-display-tab-actions views-ui-display-tab-bucket clearfix\u0022\u003E\u003Cdiv class=\u0022ctools-no-js ctools-button ctools-dropbutton\u0022\u003E\u003Cdiv class=\u0022ctools-link\u0022\u003E\u003Ca href=\u0022#\u0022 class=\u0022ctools-twisty ctools-

CAn anyone tell me whats wrong and how to fix this?

This is caused by a JQuery AJAX failure.  Several different things could be causing this.  You will probably need to research the current active theme and any modules that you are using in or around that view (especially ones that use AJAX) to see if they have a history of AJAX related failures (and related fixes or patches.)  A few things to try:

Enable, disable or change the settings within the jQuery Update module (some versions of jquery are not compatible with some modules.)
Change the theme used on admin pages to a generic theme (included in the Drupal download)


Custom order processor not being run I have a custom order processor which currently just logs a debug message, so that I know that the order has been processed by it.

For whatever reason, my order processor is never run, I've checked against the docs, looked at how other commerce modules does it (commerce_promotion and commerce_tax), none of them show that I am doing anything wrong.

custom_commerce.services.yml

services:
  custom_commerce.order_tax_processor:
    class: Drupal\custom_commerce\OrderTaxProcessor
    tads:
      - { name: commerce_order.order_processor, priority: 300 }

OrderTaxProcessor.php class

<?php

namespace Drupal\custom_commerce;

use Drupal\commerce_order\Entity\OrderInterface;
use Drupal\commerce_order\OrderProcessorInterface;

/**
 * Provides an order processor that adds tax to order if order has adjustments.
 * It does not affect order items.
 */
class OrderTaxProcessor implements OrderProcessorInterface {

  /**
   * {@inheritdoc}
   */
  public function process(OrderInterface $order) {
    \Drupal::logger('Custom commerce')->debug('Order processed check');
  }
}

Can anyone see what I am doing wrong? Other order processors seem to be running fine, but mine seems to be ignored/not run.

Running Drupal 8.5.3 and Commerce 2.6.0

So I found what caused my problem, a silly typo...

Basically, in my custom_commerce.services.yml I had written tads instead of tags.

I fixed it and it's now running as it should.


Custom Module not showing up Playing around with Drupal 8 and trying to create a custom module with a custom block:

I have a module.info.yaml file:

name: Custom Module
description: Description Here
package: Custom Module
type: module
core: 8.x

dependencies:
  - block

I have a src/Plugin/CustomBlock/CustomBlock.php file:

<?php

/**
 * Provides a 'Custom' Block
 *
 * @Block(
 *   id = "custom_block",
 *   admin_label = @Translation("Custom Block"),
 * )
 */

namespace Drupal\custom_block\Plugin\Block;

use Drupal\Core\Block\BlockBase;

class CustomBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {
    return array(
      '#markup' => $this->t('Hello, World!'),
    );
  }
}

The module is in /modules/custom/module. I have installed contrib modules in /modules/contrib with no issue.

If I go to the Extend page, my module is not listed.

Please let me know what I am missing here?

Typo on the module file name:

module.info.yaml

Should be

module.info.yml


Multiple url aliasses per node in multi language website Hope this is the right place for this question. I'm turning to you guys because I just cannot decide on the best way to go for this issue.

I'm currently developing a multi-language site which is split up in 2 main sections. Section A will be the main section and is available in 2 languages; Dutch and English. Section B will only be available in English.

Section B will have a different Menu, a slightly modified layout and some other blocks will be shown on different pages within the section.

I'd like to achieve the following url structure:

Section A:

/nl/title-of-a-node-in-dutch

/en/title-of-a-node-in-english

Section B:

/en/section-b/title-of-a-node-in-english (If possible, I'd like to drop the language prefix /en/ here)

I've configured Drupal with Entity Translation (+ Title module), so each node has translations on field-level and is not entirely duplicated like it would be the case with Content Translation (i18n).

The problem is that I'm going to have a lot of content (tens of thousands of nodes) for this site and some items should be shown in both Section A and B.
Content that will be shared with both sections should only exist in one node. I definitely do not want to create an extra node with the same content just to make it available for Section B, this would be bad for content management and have a huge impact on the database.

Some of the solutions I've thought of:

Create 2 checkbox fields in the content type to indicate in which section the node should be made available. Create a hook on node insert/update and check which section was selected. If Section B was chosen, create an extra url alias which starts with /section-b/{node-title}. This would make the node content available via this extra alias, but I'm not sure what the implications this method will have, like how to handle breadcrumbs or (multilingual) Menu Structures for Section B
Configure Drupal to use a language fallback with Language Neutral and somehow add Section B as a custom language with the prefix 'section-b'. (is this even possible?)
Use url rewrites /section-b/my-title -> /en/my-title and programatically load the node and show the content via theming/templates
Maybe I can do something with Rules?

Relevant modules I'm using:
pathauto, entity_translation, path_translation, i18n_translation, title

Do you guys have any other suggestions in how to set this up? I hope I'm clear on this issue. Content management is very important in this matter :)

Thnx!

I'm not sure if this article helps, but here it is: https://www.drupal.org/node/1516444

For something more complex, I've actually implemented a hook_url_inbound_alter() to control the redirection of pages and it's worked pretty well for me, but it involves creating the logic yourself. On the other hand, the benefit is that you can completely control when and where you redirect page visits.


Pager disappears when adding "GROUP BY" in the SQL query Drupal pager disappears when I add GROUP BY to the query.

This code works.

$countSql = "SELECT  COUNT(*) FROM journal ";
$sql = "SELECT  * FROM journal";

$result = pager_query($sql, 1, 0, null, $countSql);
theme_pager(NULL, 10)

This code doesn't show the pager.

$countSql = "SELECT  COUNT(*) FROM journal ";
$sql = "SELECT  * FROM journal GROUP BY id";

$result = pager_query($sql, 1, 0, null, $countSql);
theme_pager(NULL, 10)

What is it wrong with the latter code?

Your query with the GROUP BY is incorrect, MySQL is lax enough to let you write this kind of queries but it is by no way recommended. When you use a GROUP BY clause you should group all the columns without an aggregate function.

Also if you put a GROUP BY in your query, you should also include it in your count query. Generally a brutal way to make the count query is to put it this way:

$sql = "SELECT  * FROM journal";
$countSql = "SELECT  COUNT(*) FROM ($sql) ";

Try to modify your queries and amend your question with further precisions.


Boost and system cache I'm using the Drupal-7 system caching and i recently installed the Boost module to improve my site performence;
I'm wondering if there's no conflict between the two system caching because i didn't feel any increasing of my site rapidity .
Thank you very much

I use Boost for my company website, and have been pleased with the results.

Did you disable "Cache pages for anonymous users" in the performance settings? Did you add the extra settings required by boost in your .htaccess file? Are you only viewing the site as an anonymous user? Have you made sure the /[drupal-base]/cache is readable by Apache, and /[drupal-base]/cache/normal is readable and writable by Apache?

If yes to all the above, you likely have other issues slowing down your site, such as too little overall RAM (or too much RAM allocated in the allowed_memory setting).


Define image cropping in new image style When creating a new image style, is there a module which can let you define where to start the cropping? I think Drupal only crops from the very center. What if for this specific image I want the cropping to being from the top left? Or better yet, provide some gui which can let me crop the area manually like in fb.

There are many options to choose from in Drupal for image cropping. Here is a quick comparison.

EPSA Crop

Allows a user to choose coordinates for different presets on an image. If a user defines coordinates EPSACrop will override the Imagecache process and will set new coordinates.
Image Javascript Crop

With this one you define one or more presets in imagecache using the 'javascript crop" action, a new 'javascript crop' link appears underneath the image on the node edit screen, and the resulting popup window will display those presets. This screen shows the original image and initially applies the initial crop settings defined in the preset you select, e.g.: crop 50%-50%, center-center. However, you can then choose a different area of the original picture you want to crop, dragging an overlay box over the image, altering the size etc.
Imagefield Crop

When the user uploads an image, the image is presented inside a cropping area. A cropping box is shown inside, and the user can resize and move it. Upon clicking 'preview' or 'submit', the image is cropped and the result is saved instead of the original image.
Imagefield Focus

This module allows to scale and crop images focusing on their important portions.
Image Editor

Bring Photoshop-like functionality into your Drupal website! Create/edit any images online in the powerful and feature-rich image editors and save resulted images back to your site! This project integrates several popular online image editing services into Drupal:Pixlr editors: Pixlr Editor and Pixlr Express, Picnik, Simple HTML5 editor from Aviary: Aviary Feather, Advanced Aviary editors: Aviary Phoenix; Aviary Raven (vector editor - not working yet); Aviary Peacock; Aviary Falcon, Sumo Paint, FotoFlexer and Open-source HTML5 PaintWeb editor.

On a side note, (this is not what you were really asking, but) anyone coming to read this post looking for similar functionality directly in IMCE can use the IMCE Crop module which adds image cropping functionality to IMCE through its UI. And for kicks, if your looking for the ability for users to be able to do manual cropping on their avatars, use Avatar Crop. Or just to force Image presets on Avatars, use Image Cache Profiles.
Manual Crop


Can we use math expression in Field collection I have two fields in field collection i.e total_amount and installment_value. I want to divide total_amount with installment_value and display result in Result field. Can somebody resolve this issue for me as I tried with computed and math expression but unable to resolve the issue. Thanks

First off, would this be for D7 or D8? I'm assuming you're using the node entity. I would think a good approach is to have the result field as a field on your node, make the calculation, and set the value in a hook_node_presave() (for D7, hook_entity_presave() for D8). At this point, the values are about to be stored to your DB, so you'd have access to your total_amount and installment_value values, and you can set your third "result" field to this computed value. You'd probably want to set the "result" field to not be visible to the end user, by setting it's #access to false in a hook_form_alter(), since anything they input would be overridden by your calculation anyway. I could provide you a more detailed answer if you can clarify which version you're on, or hopefully this can get you going in the right direction!


update 8.2.7 to 8.3.0 with composer I want to update with composer (running the drupal composer drupal project), and already succesfully updated 8.2.6 - 8.2.7, but now it doesnt update to 8.3.0

$ composer update drupal/core --with-dependencies
Package "drupal/core" listed for update is not installed. Ignoring.
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Generating autoload files

Taken from: here

You need to make sure that drupal/core is in the require part of your composer.json and not the replace part, it won't work otherwise.

Haven't tested it yet, but it explains the Package "drupal/core" listed for update is not installed. Ignoring. message.

In case someone's looking for the way to upgrade using drush:

drush up drupal


Views_embed_view fatal error in views.inc I'm getting this error when I embed a view on a page. It doesn't happen when I preview the view in views UI.

"recoverable fatal error: Object of class stdClass could not be converted to string in views\includes\view.inc on line 728."

This is my embed code:

<?php print views_embed_view('list_applications_for_reviewer', 'block_1', array(85, 229)); ?>

I don't have this problem in any of the other views on my site, of which there are many doing similar things.

Any ideas what I might need to fix?

First thing I would try is using  instead of passing the arguments as an array. I recall hitting this issue because views_embed_view() uses func_get_args() to process view arguments and behaves oddly if an array of them is passed.

If that doesn't work, your best bet is to step through the code with Xdebug and see if you can find the difference between that variable when it works (all other times) and when it doesn't (this time).


Adding nodes to term instead of terms to nodes Is there a way to easily add nodes to terms? In other other words, let's say I have a taxonomy called top 5 sellers and I have a collection of nodes that represent books.

Currently it's hard to manage something like that because I have to search and find each book, and then assign the taxonomy term to it. I'm looking for a way to do it 'the other way around' where I have a gui that lets me choose a taxonomy and then choose nodes to add and subtract to it.

I hope that is clear. Any ideas?


How to show only user assigned contents in his dashboard? I have more than 270 pages in my website.

There are some Content Creators, Content Editors, Reviewers and Publisher.
I have assigned each user a different role.
Each user can view, edit and publish each others' pages.

I wanted to create something like;
When user logged in with his user name and password, first he can see only his own created/assigned content pages when he clicks on content tab.

How to show only user assigned contents in his dashboard?

In your view simply follow these steps:

Click the Advance Tab under the RELATIONSHIPS add a new relationship  Content:Author

Keep the Identifier as it is, but remember to check the Require this relationship option.

Now, under FILTER CRITERIA add a new filter User: Current and check the Is the logged in user as Yes

The exported code:
$view = new view();
$view->name = 'article';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Article';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Article';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: Content: Author */
$handler->display->display_options['relationships']['uid']['id'] = 'uid';
$handler->display->display_options['relationships']['uid']['table'] = 'node';
$handler->display->display_options['relationships']['uid']['field'] = 'uid';
$handler->display->display_options['relationships']['uid']['required'] = TRUE;
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'article' => 'article',
);
/* Filter criterion: User: Current */
$handler->display->display_options['filters']['uid_current']['id'] = 'uid_current';
$handler->display->display_options['filters']['uid_current']['table'] = 'users';
$handler->display->display_options['filters']['uid_current']['field'] = 'uid_current';
$handler->display->display_options['filters']['uid_current']['relationship'] = 'uid';
$handler->display->display_options['filters']['uid_current']['value'] = '1';
$handler->display->display_options['filters']['uid_current']['expose']['operator_id'] = '';
$handler->display->display_options['filters']['uid_current']['expose']['label'] = 'Is the logged in user';
$handler->display->display_options['filters']['uid_current']['expose']['operator'] = 'uid_current_op';
$handler->display->display_options['filters']['uid_current']['expose']['identifier'] = 'uid_current';
$handler->display->display_options['filters']['uid_current']['expose']['required'] = TRUE;

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

Cheers!


What cache should be cleared for front end theming work? When theming I work with CSS files and templates files. What cache should I clear while retaining performance?

And what would be the equivalent drush command?

I think drush cc all clears too many things right?

Here's the comprehensive list of cache-clear options and the underlying API functions & what they do:

drush cc drush - drush_cache_clear_drush(): Drush's internal cache for data from the Drupal install (e.g. available module commands).
drush cc all - drupal_flush_all_caches(): All Drupal caches.
drush cc theme-registry - drupal_theme_rebuild(): All theme metadata.
drush cc menu - menu_rebuild(): All menu metadata.
drush cc css-js - drupal_clear_css_cache() drupal_clear_js_cache(): Aggreggated/Minified CSS/JS files.
drush cc block - cache_clear_all(NULL, 'cache_block'): All block metadata.
drush cc module-list - system_rebuild_module_data(): All available modules (reloaded from file system).
drush cc theme-list - system_rebuild_theme_data(): All available themes (reloaded from file system).

That should let you fine target the cache to clear when it's needed.

Depending on your workflow, you might also want to force the cache off (e.g. $conf['preprocess_css'] = 0; & $conf['preprocess_js'] = 0;) in local.settings.php for your local dev environment so it doesn't interfere with feedback.


Restrict creation of content type by user reference I have two content types, Location and Event. The Location has a user reference field containing the owner of the Location. The Event type has a node reference field containing the Location node it belongs to. Now I want the owners to be able to create Events only for their Locations based on this reference field.

Currently I "solved" this by having a Views reference in the Event type that only shows Locations where the author is "Drupal"-owner of the nodes. But this has two downsides:

Administrators get an empty Views reference and thus can't save Events
I have to change the author of the Location node instead of using the user reference field I added

So, is there a way to solve this?

I would create a custom module that uses Entity Field Queries to do the following:

First, use EFQ to select nodes of type "location" where "user" matches the "user" specified in the selected "event" AND also the "location" value matches the "location" specified in your event. This has essentially the same effect as the Views solution you've worked out, I believe.
The advantage over Views here is that now you can node_load() the nodes you find or you can execute more complex logic if there are no matches (i.e. if the user should not have permissions).
Use hook_node_grans() or hook_permission as needed.


Display a block in a page I have a block created with Views that I want to display in a node where "PHP filter" is enabled. How can I display the content of that block?

All the examples I can find seem to be for Drupal 6.

$block = module_invoke('views', 'block_view', 'ViewName-DisplayId');
     echo $block['content']['#markup'];

Parameters in module_invoke:

module to call: 'views'
hook to call, in this case 'block_view'
View name and display id of the block, separated by an hyphen. For example 'testview-block_1'

The display id of the block it will show only when hovering the mouse over the "Block" word in the Views page of the Block. You will see an url like this: http:///admin/structure/views/nojs/display/testview/block_1
The block_1 is the display id in this case.


Internationalization (i18n) + Translation Management - No interface for adding translator available In the Translation Manager menu (http://<mysite>/admin/content/translation-management/manage-translator?from=en&to=hu), when I want to add a translator to a given page, I see the following error message: "No interface for adding translator available.".

What should I do?
I think I gave the right permissions to the administrator and another given user (I checked the following permissions in "ICanLocalize translator" checkbox: "submit content for translation", "can do translation jobs", "can view translation jobs", "translate content", and gave "ICanLocalize translator" role to the admin and the other mentioned user), i18n module is installed, so I don't know what is missing.

Here's a screenshot:

In the meantime I found the answer: I just realized that "ICanLocalize translation service" module wasn't enabled.

After enabling, I can see the following:

So I think I can consider my problem solved. :)

You could also enable "Local translation service" module to add your local translators.


How to save an image resource I have brought an image in from an API and cropped it using imagecrop in a custom module. I now have an image resource. But I cannot figure out how to turn the resource into a file I can save in Drupal or just save the resource directly as a file through Drupal. I have tried variations of file_get_contents and file_save_data. Any help would be appreciated.
When I use the following:
$cropped_image = imagecrop($image_resource, $rect);
$final_file = file_save_data($cropped_image);
$type = array('type' => $content_type);
$node = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->create($type);
$node->field_image = array(
  'target_id' => $image_file->id(),
);
$node->save();

I get the error "Call to a member function id() on bool in" on the $node->field_image line. That has made me think that the resource is not getting saved into a file with file_save_data() (obviously, not exactly sure what is happening).
When I included a file_get_contents($cropped_image) and then process that through file_save_data (as I do when I bring in an image from a URL), I end up with an error that the system is unable to handle the request in nothing in the recent log messages.
I have tried various other methods as well with no joy.

I may have had the code correct at some time yesterday, but I was running out of memory on my localhost. I ended up rewriting some of the code and - once I realized I was having memory issues - moved everything onto the server, where it all worked like a charm. Sorry for asking the question. And, thanks, Simon, for provoking me to question everything anew with your comment.
Here is my final code;
            $cropped_image = imagecrop($precrop_resource, $rect);
            imagedestroy($precrop_resource);

            $file_path = \Drupal::service('file_system')->realpath('public://');
            imagejpeg($cropped_image, $file_path . '/temp-image.jpg');

            // load the image
            $cropped_data = file_get_contents($file_path . '/temp-image.jpg');
            $cropped_file = file_save_data($cropped_data);
            unset($cropped_data);

Then I added the image to the node object and saved the node.
EDIT:
I eventually realized a couple issues with the above code. First, it was not just my memory on the localhost; processing 10MB+ jpegs would exhaust the memory on the server as well because the GD2 image tools process everything in uncompressed format. Second, the files were saving without .jpg on their filenames, so using them could be a problem.
So, I ended up using the ImageMagick to process things and added another variable to the file_save_data function call.
Here is my new and improved final code:
            // crop the image
            $precropped_image = new Imagick($precrop_file->getFileUri());
            $precropped_image->cropImage($rect['width'], $rect['height'], $rect['x'], $rect['y']);
            $precropped_image->writeImage($file_path . '/temp-image.jpg');

            // save the cropped image in the Drupal DB
            $cropped_data = file_get_contents($file_path . '/temp-image.jpg');
            $cropped_file = file_save_data($cropped_data, 'public://' . $image_title . '-og.jpg');


Relate number of values to an integer field I was wondering how to do this with drupal. You probably wonder why I don't just use the unlimited amount of values setting. That's because I want to require the user to fill in the amount of values related to the integer value.

For example, you want to create a group (node) for a specific category (node). A category which contains an integer field (field_members). Now lets say you also have a node reference field (field_category) at those group node its fields, which refers to a specific category (in this case field_members). Then the user must add the amount of users related to the category its field_members value.

You will probably have to setup some way of two step process to enable the reference between both nodes (maybe entityreference). The field you are using will have to be an unlimited multi value field.

with this peace of code you will be able to reduce the items of that field (including the add button). Feel free to provide any other logic for looking up the settings node / proding a default limit etc.

<?php
function mymodule_field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode) {
  if ($entity_type == 'node' && $entity->type == 'my_content_type') {
    $multi_values = array();
    foreach ($form['field_myfield'][LANGUAGE_NONE] as $key => $value) {
      if (is_numeric($key)) {
        $multi_values[$key] = $value;
      }
    }

    if (count($multi_values) > 1) {
      $multi_value_keys = array_keys($multi_values);
      foreach ($multi_value_keys as $key) {
        unset($form['field_myfield'][LANGUAGE_NONE][$key]);
      }

      // get the count of the asociated node, maybe using entity reference?
      $settings_node = node_load($entity->field_settings_node[0][LANGUAGE_NONE]['target_id']);
      if ($settings_node) {
        $limit = $settings_node->field_limiting_field[LANGUAGE_NONE][0]['value']; // e.g. textfield..
        if ($limit) {
          $i = 0;
          // add all the fields that are allowed, cut of the once that are too much (and remove the add button)
          while ($i < $limit && $i < count($multi_values)) {
            $form['field_myfield'][LANGUAGE_NONE][$i] = array_shift($multi_values);
            $i++;
          }
        }
      }
    }
  }
}

You might also want to look at How to dynamically set the maximum cardinality for a multi value field? for another example (setting the access attribute for those fields)


displaying taxonomy term as a header in a view I have a view that displays 3 latest articles from a certain taxonomy term. The issue im having is I need to display the taxonomy term as a Header. I dont see the [field_myterm] under Header > Global : Text area.. I also need this taxonomy term translated when I switch languages.

You should probably try to create a Taxonomy term View and not a Content View. Then, you could add a relationship (Taxonomy term : content with term) to fetch your node fields (or rendered entities). Add a taxonomy term filter to select your certain taxonomy term. Add a sort criteria based on descending post date (relationship with content). Display only 3 items. Finally, the taxonomy term name will become your View title and I guess you're done.


Does drush up do a database backup/dump? Does running drush up run a database backup? From testing, it looks like it doesn't. Should I be doing a separate database backup before I run drush up to update?

To make gzipped mysql dump with drush:

drush sql-dump --gzip --result-file

Update from the wranvaud's comment:
If you don't specify the result file it will be stored on you home folder under: ~/drush-backups/<db_name>/<timestamp>/<database_file>.sql.gz, otherwise you can specify --result-file='~/Documents/'


Is there a D7/Services module for sane field content I/O? For instance, a GET request to the standard endpoint node/1.json returns an object with fields like this:

{
   ...

   "field_my_field":{
      "und":[
         {
            "value":"yucky"
         }
      ]
   }

   ...
}

To build an easy to use API, we would want to GET and POST objects with fields like this:

{
   ...

   "my_field": "clean"

   ...
}

It would be easy to implement the vast majority of field types this way. I thought there was a module for this, but I can't find it.

With the Services module, no. However you could build a Page display with Views datasource, that accepts a node id as a contextual filter. The fields you specify in the View can then be configured to "clean up" the property name (or just turn off the label to use the machine name of the field), and then the value will be "flat".


Body and Subject fields in Mail Function I can't get it working. What am I doing wrong?

$name = $form_state['values']['name'];
$rname = $form_state['values']['rname'];
$email = $form_state['values']['email'];
$message = $form_state['values']['message'];

$params = array('current_conditions' => $data);
$message = drupal_mail('wow', rand(0, 999), $email, $language, $params, FALSE);
$message['body'][] = 'test';
// Only add to the spool if sending was not canceled.
if ($message['send']) {
    drupal_set_message('Success!');
}

The last parameter you are passing to drupal_mail() is FALSE. That parameter is telling the function if sending the mail. The documentation describes the parameter as follows:

  $send: If TRUE, drupal_mail() will call drupal_mail_system()->mail() to deliver the message, and store the result in $message['result']. Modules implementing hook_mail_alter() may cancel sending by setting $message['send'] to FALSE.

As its default value is TRUE, just leave out that parameter, and the mail will be send, if other modules don't set $message['send'] to FALSE.


Execute a file in the body of a specific content type How to load the file, which contains css, javascript and html, in the body of a specific content type?

Looks like you are looking for Code per Node module:

  Code per Node makes it possible to add custom CSS and Javascript per node, per content type, per block, and globally. The code is stored in the database, but served from the file system.


Which permission should I use for a role to see a shortcut to Custom Block Library? I have a custom block that is a site-wide announcement. I have a role, "Announcement Editor", for those people who I want to edit that message.

Most of our users have restricted permissions, and don't have access to the "Structure" menu, etc. We use shortcuts to allow them to see items they can't navigate to through menus. This was set up by a developer who is no longer here.

I want to add a shortcut, "Blocks", linking to /admin/structure/block/block-content to these users' menu. I have added it to the default shortcuts for the site. It shows up for Admin users:

However it doesn't show up for other users:

What permission(s) do I need to add for users to see this shortcut?

Edit Authenticated users have the permission use shortcuts already:

The permissions defined for the module are:

administer shortcuts:
  title: 'Administer shortcuts'
customize shortcut links:
  title: 'Edit current shortcut set'
  description: 'Editing the current shortcut set will affect other users if that set has been assigned to or selected by other users. Granting "Select any shortcut set" permission along with this permission will grant permission to edit any shortcut set.'
switch shortcut sets:
  title: 'Select any shortcut set'
  description: 'From all shortcut sets, select one to be own active set. Without this permission, an administrator selects shortcut sets for users.'
access shortcuts:
  title: 'Use shortcuts'

To see the shortcuts you need the permission Use shortcuts.
To see the shortcuts in the toolbar you need the permission Use the administration toolbar
To see the shortcut for the page /admin/structure/block/block-content you need the permission Administer blocks


Add unique class to webform radio form-item div Can anyone point me in the right direction to show, how to add a unique class to the webform select options container divs .form-item? I would like to theme these divs surrounding the each radio button with a different background image. I don't really care what the class is, numbers, the key, etc. just as long as I can target it in my css.

You can add particular css while creating that field in webform configuration itself.See below section in your webform

For this particular clas you can add css in your code.


Commerce 2.x multicurrency / multiprice setting Is it possible to set two prices each with its currency for the same product so that it appears in two stores with correct price? For example, I have set up two stores one for Czech Republic with CZK as a currency and second one for Germany with EUR as a currency. Now I want to create a product (for example t-shirt) that should appear in both stores but with price for each store different. I haven't found a way to do that, could somebody please shed some light on this problem, or at least point me in the right direction, I am kind of lost here.

Thanks.

[edit]
Still not found the correct way of resolving this problem. I have created a search index and view based on the documentation, the view has two pages each for one store. If I create a product with just one variation, price and currency, then publish it in one of the stores it all works as it is supposed to, but if I create product with two variations and two prices with two currencies, publish it in both stores then it doesn't work.

The https://www.drupal.org/project/commerce_currency_resolver module will help you do this.


Are there any Drupal modules that allow you to select a template to use for output or are there any modular content editing interfaces? I'm doing some work for a design agency and I'm looking into how I can achieve their fanciful designs using Drupal. In particular I'm worried about the formate of their blog posts, it's quite clear that what they want is not going to be satisfied by any kind of WYSIWYG editor. So I'm left with two options:

Allow them to enter HTML and code up each of the blog posts myself (obviously not desirable).
Limit them to a few different templates that they can use for the future.

I think your best bet is to add an additional field to the blog post content type, which can be used in the theme layer to select the proper template. You will provide the templates in advance, which will result in an easy UI for the editor, but will not sacrifice your ability to customize and tightly control the template.

Step 1: make your new field

This new field should provide them with options for the layouts. For the purposes of this example I'll use a field called field_blog_layout that provides two options: Single Column and Staggered. Make sure you provide machine values in a format that is accepted by the theme hook system, just to make it a tad simpler for yourself in the next step. Here would be the values in your field settings:

single_column|Single Column
staggered|Staggered

Step 2: Add dynamic theme hook suggestions

Now that you have your field, add a new hook inside template.php (or a custom module, e.g. if you have a Blog Feature). My example would live inside a module file called my_feature.module:

/**
 * Implements hook_preprocess_node().
 *
 * Provides theme hook suggestions to complement the custom layout.
 */
function my_feature_preprocess_node(&$vars) {
  // Only run this code on Blog nodes.
  if ($vars['node']->type == 'blog') {
    // First, grab the value of the Layout field.
    $my_layout = field_get_items('node', $vars['node'], 'field_blog_layout');
    // Add the theme hook suggestion using the field's value
    $vars['theme_hook_suggestions'][] = 'node__blog__' . $my_layout[0]['value'];
  }
}

If you were careful about using the expected format for theme hooks within your custom field's machine values, there should be no other processing needed.

Step 3: Implement the theme hook by adding templates

With the theme hooks ready to go, you can now create templates. It's simple, just create a template using the exact format of the theme hook, except replace all underscores (_) with dashes (-):

node--blog--single-column.tpl.php
node--blog--staggered.tpl.php

For the content of these templates, just make a copy of node.tpl.php and customize it to your heart's content.

Note: you must have a file called node.tpl.php in your theme for the special templates to work. This is a known behavior of the Drupal 7 theming system.

Step 4: Clear the cache and marvel at your work

New hooks and templates both require a cache clear. Don't forget or you'll wonder why nothing is changing!


how to set value of autocomplete field and trigger search event with jquery I am setting the value of an autocomplete field from a jquery event:

$('input#edit-myfield').val(mynewvaluethatIwant)

That works, but the associated drupal autocomplete search does not fire.

My use case is I have a working autocomplete, but as well as typing a few letter into the field, I want to give users the option of clicking a link to populate the field.

My automcomplete field AJAX handler runs several commands as part of its response, so I'm just wanting to fool the form into thinking the user has entered the value.

Looking in misc/autocomplete.js, there's a function called populatePopup() (Drupal.jsAC.prototype.populatePopup). Since that function is bundled into the jSAC object, we can't call it directly. Instead, let's simulate the event that calls it which is found in the onkeyup() function.

<script>
/**
 *  Fill an input field and then display the autocomplete popup.
 *
 *  @param $field
 *    This is a jQuery field reference -- e.g. $('#my-input-field')
 *  @param searchVal
 *    The text to place into the input field
 */
function ShowAutoComplete($field, searchVal) {
  var e = $.Event('keyup'); // Create an event to trigger
  e.which = 32; // Add the keyCode (32 is a space, but it shouldn't matter)

  // Set the field value, focus on the field, then trigger the event
  $field.val(searchVal).focus().trigger(e);
}
</script>

FYI, I used this post as a reference to figure out how to fire the keyup event.


How can I redirect users to the order information after adding product This is the goal:
Once user click on a link, product needs to be added to the basket, and order information page needs to appear, so user can fill it.

I've created a controller, and everything works, unless the user in anonymous.
In that case, a "You are not authorized to access this page." error appears, and product is not added.
However, (not sure if this is important), if the user visits a product first (just visit, without additional interaction), and then visit the link there is no that error. Also, if there are some items already in the added (with classic buttons), everything also works, for anonymous users as well.

I've used this to add the product:
https://www.drupal.org/node/2866020

Shortly, it creates order item, and adds with cart manager.

and at the end, I've added

$cart_id = $cart->get('order_id')->getValue();
$cart_id_value = $cart_id[0]['value'];
$response = new RedirectResponse('/checkout/' .$cart_id_value.'/order_information');
$response->send();
return;

Any help or guidance will be appreciated.

Thanks

I've solved this by replacing last 3 lines with

return $this->redirect('commerce_checkout.form', array('commerce_order' => $cart_id_value));

And as ssibal suggested, here I do not use hard-coded URL (thanks for that).


"Changed by" column for node list If a node is changed by another user, the change time is shown on /admin/content but not by which user the node was changed. I couldn't find any field in the respective view to add. Did I miss sth?

Edit the "Content" view.
Add "User - Content revision" in Relationships under "Advanced" tab.
Add "Name - User" in the fields using the Revision user relationship. You can set a label for this field as "Last modified by".


drush open_basedir restriction in effect on media temple I'm using drush on mediatemple grid service. I think i've got setup drush correctly. At least to my knowledge. I've been able to use it; but with nagging errors/warnings each time.

And whenever i invoke drush i get these errors:

The following restricted PHP modes have non-empty values: check your configuration settings in /usr/local/php-5.2.14/etc/php.ini or in your drush.ini file

Anyone have any clues how to rectify this?

drush topic docs-ini-files

That command tells more about creating a drush.ini file. In it, you want to remove the listed restrictions (you didn't provide them).


InvalidArgumentException: The specified translation (fr) cannot be removed Configurations:

"drupal/core": "8.4.3",
"acquia/blt": "8.9.10",
"acquia/lightning": "2.2.5",

I am trying to run migration of workbench moderation to content moderation on drupal core version 8.4.3, Install that module wbm2cm and run below the commands,

$ drush wbm2cm-save
$ drush wbm2cm-clear
$ drush pm-uninstall workbench_moderation
$ drush en content_moderation
$ drush wbm2cm-restore

After run drush wbm2cm-restore getting the error:

  InvalidArgumentException: The specified translation (fr) cannot be
  removed. in Drupal\Core\Entity\ContentEntityBase->removeTranslation()
  (line 901 of
  /var/www/cgicom/docroot/core/lib/Drupal/Core/Entity/ContentEntityBase.php).
  The specified translation (fr) cannot be removed.
  (/var/www/cgicom/docroot/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php:805)

My References:
https://atendesigngroup.com/blog/fixing-invalid-translations-drupal-8-content-moderation
https://www.drupal.org/project/entity_clone/issues/2984049

Here I am not getting the solutions. Please can anyone suggest me?

"#3" patch file is working to me!
https://www.drupal.org/files/issues/2019-03-26/3043535-no-failure-deleting-multiple-translations-3.patch

Please refer: https://www.drupal.org/project/drupal/issues/3043535


Spam users and rules I'm getting swamped by spam users.  Can I use rules to automatically delete users that 1) don't have content/comments, 2) have never activated in a few weeks, and 3) have only activated the same day they created their account, but haven't posted content/comments?

To get rid of inactive users, have a look at the Inactive User module.

User Stats will keep track of the IP's used by the various users.

The Spambot module is quite effective at blocking bots which create the inactive accounts. If you can take the time, it will let you report and delete spam postings to help block future attempts.

However nothing will stop them. One of my sites just came under attack over the weekend. Over 600 new user registrations in less than 12 hours (at times 3 per minute). I checked the IP's and found that I had multiple accounts created from a few IP's (between 15 and 45 users from the same IP). Manually blocking the IP's involved at /admin/config/people/ip-blocking and deleting the accounts was the only way to stop the attack.

Good luck.


Rendering a region after rows Having code issue.

I am rendering a the regions[ad_spot] = 'Ad Spot' so that it shows up after the first row.

For some reason it is not showing the region even tho I have put a block in there. So far I have not had an issue with my other regions I have made.

http://dev-honey-in-the-wild.pantheon.io/

Code is here: https://codeshare.io/bHx5N

Am I doing this correctly?

thanks!

I'm absolutely against to add code in templates...

but your problem is here:

<?php if ($row_id == 0): ?>
  <?php print render($page['ad_spot']); ?>

I think this is always FALSE.


Where is the module registry stored outside the database? As a long time Drupal dev, I should probably know the answer to this question, but I'm stumped by the behavior I'm seeing.

Let's say I have a local and a remote site.  On the remote site a module is uninstalled properly and the module code is removed from the file system (git tracks the deletion, etc).

Then to get my local installation up to date, I completely drop all tables in my database (it's completely empty) and I do a git pull, so the local module files are deleted. I then get the remote database and load it into my local.

In that situation there are no database remnants from my old local install and the file system is updated with the deleted modules.  It should reflect the remote site completely.

However, when I load up the local site I get all the 'XXXX module is missing" and everything breaks.  I run the registry rebuild via drush rr, and it fixes everything.  But then, going forward into the future, I continue to see this broken registry each time I reload the site from the remote database (meaning I have to rr each time).

This strikes me as so odd...because where are those old registry records stored outside the database? Why, if I have a fully clean database, does it recognize old modules as missing?

And of course...how can I 'clean them up' permenantly?

Common causes:

External cache (Memcache, etc) that is not purged on rebuild
Your SQL import contains cache from prod (I tend to make sure backups make cache tables structure-only).
Your SQL is imported into a DB which contains tables, but does not drop some of them (such as cache). (I personally drop and create the DB before each import).
The module is still enabled/present in the system table (confirm in your SQL that the row in the system table is gone/disabled & uninstalled).
Something else on your site depends on it and is re-enabling it (eg master module, feature dependencies, etc (although dependencies usually block things from being disabled)).
Sometimes worth doing a drush cc drush after importing the SQL. When in doubt, clear caches ;)


How to modify the Search box input value? I would like to add a value for the search box input to my Bartik subtheme, and modify the value in my Clean Coorporate subtheme. How would I do this?

Edit: Found this code in template.php for the clean coorporate theme.  Editing the 'Search' string updated the value I was wanting to change. I guess I just need to put the same code in my Bartik subtheme as well?

function mytheme_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_block_form') {
    unset($form['search_block_form']['#title']);

    $form['search_block_form']['#title_display'] = 'invisible';
    $form_default = t('Search this site');
    $form['search_block_form']['#default_value'] = $form_default;
    $form['actions']['submit'] = array('#type' => 'image_button', '#src' => base_path() . path_to_theme() . '/images/search-button.png');

    $form['search_block_form']['#attributes'] = array('onblur' => "if (this.value == '') {this.value = '{$form_default}';}", 'onfocus' => "if (this.value == '{$form_default}') {this.value = '';}" );
  }
}

The only line you'd need to set the value of the input is

$form['search_block_form']['#default_value'] = $form_default;

The last line is a basic JS placeholder implementation, but in this day and age the HTML5 placeholder attribute would be preferable:

function MYTHEME_form_search_block_form_alter(&$form, &$form_state, $form_id) {
  $form['search_block_form']['#attributes']['placeholder'] = t('Placeholder text');
}


How to disable copy and paste in webform textarea? Is there a way to disable pasting into a webform textarea field?

I've created a textarea field called: my_words and I want to forbid anyone from copying and pasting text into this field.

I've not tested this code, but a quick Google search suggests the following (obviously change #Password to the ID of your textarea field).

$(document).ready(function() {
    $('#Password').bind('cut copy paste', function(event) {
        event.preventDefault();
    });
});


Entity access controler not called from custom route I define a custom entity named "Politician", where I set the class PoliticianAccessControl as an access handler. This is working fine for the canonical url of the entity set in the following way:

entity.politician.canonical:
  path: '/politician/{politician}'
  defaults:
    _controller: '\Drupal\pw_basic\Controller\EntityViewController\PoliticianViewController::view'
    _title_callback: '\Drupal\pw_basic\Controller\EntityViewController\PoliticianViewController::title'
  requirements:
    _entity_access: 'politician.view'

See the entity access requirement? Here the method PoliticianAccessControl->checkAccess() ist called, everything works just fine.

But when I try the same with another custom route the PoliticianAccessControl class gets not called and I always get an access denied message:

entity.politician.about_me:
  path: '/politician/{politician}/about-me'
  defaults:
    _controller: '\Drupal\pw_basic\Controller\PoliticianFrontend\AboutMe::build'
    _title_callback: '\Drupal\pw_basic\Controller\PoliticianFrontend\AboutMe::title'
  requirements:
    _entity_access: 'politician.view'

What do I forget?

I guess you need to do a route parameter upcasting:

entity.politician.about_me:
  path: '/politician/{politician}/about-me'
  defaults:
    _controller: '\Drupal\pw_basic\Controller\PoliticianFrontend\AboutMe::build'
    _title_callback: '\Drupal\pw_basic\Controller\PoliticianFrontend\AboutMe::title'
  requirements:
    _entity_access: 'politician.view'
  options:
    parameters:
      politician:
        type: entity:politician


Doctrine annotations for custom field formatters in Drupal 8 I am trying to port my Drupal 7 module, Views Hybrid, to Drupal 8. It provides a custom field formatter. In order to provide the field formatter, I am using the Doctrine annotation roughly following this tutorial provided by realize.be. However, I am getting PHP exceptions:

Uncaught PHP Exception Doctrine\Common\Annotations\AnnotationException:
"[Syntax Error] Expected PlainValue, got '>'
at position 168 in class
Drupal\views_hybrid\Plugin\Field\FieldFormatter\HybridFormatter."
at ~/core/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationException.php line 41

If I remove the double quotes from the keys inside the settings array then I get a different error:

Uncaught PHP Exception Doctrine\Common\Annotations\AnnotationException:
"[Semantical Error] Couldn't find constant items_count, class Drupal\views_hybrid\Plugin\Field\FieldFormatter\HybridFormatter."
at ~/core/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationException.php line 52

/**
 * Plugin implementation of the 'views_hybrid' formatter.
 *
 * @FieldFormatter(
 *   id = "views_hybrid",
 *   label = @Translation("Views hybrid"),
 *   field_types = {"entity_reference"},
 *   settings = {
 *      "items_count" => "5",
 *      "view" => "frontpage",
 *      "display" => "linked_title_only",
 *      "classes" => {},
 *      "view_mode" => "teaser",
 *      "arguments" => "",
 *   },
 * )
 */

I am not clear about the syntax that Doctrine expects for these nested arrays, or even on whether Drupal 8 expects the settings array to be included in the Doctrine annotations block when declaring a new field formatter, and my usually debugging techniques aren't very useful for debugging annotations since they're not exactly code. What is the expected syntax and content of a Doctrine annotation for defining a field formatter in Drupal 8?

I confused PHP array syntax for annotation syntax. Those => should be = and the trailing commas need to be removed from lines that are the last in their set. So it should be:

    /**
     * Plugin implementation of the 'views_hybrid' formatter.
     *
     * @FieldFormatter(
     *   id = "views_hybrid",
     *   label = @Translation("Views hybrid"),
     *   field_types = {"entity_reference"},
     *   settings = {
     *      "items_count" = "5",
     *      "view" = "frontpage",
     *      "display" = "linked_title_only",
     *      "classes" = {},
     *      "view_mode" = "teaser",
     *      "arguments" = ""
     *   }
     * )
     */


Custom module library not detected I am writing a custom module to load the crossfilter.js library in Drupal 7. I have followed what I believe are the right steps to doing that when using the Libraries module API.
However when I run drush libraries-list all I get for my library is 'not detected'

Below is my sample code. I intend to load version 1.3.7 of the library and already I have a directory called crossfilter and I have the crossfilter.js and crossfilter.min.js files in that directory.

What could I possibly be doing wrong?

function crossfilter_libraries_info() {
$libraries['crossfilter'] = array(
  'name' => 'Crossfilter JS',
  'description' => 'Crossfilter JS integration for Drupal',
  'download url' => 'https://github.com/square/crossfilter/archive/master.zip',
  'vendor url' => 'http://square.github.io/crossfilter/',
  'version arguments' => array(
      'file' => 'crossfilter.min.js',
      'pattern' => '/version="(\d+\.\d+\.\d+)"/',
   ),
  'files' => array(
      'js' => array('crossfilter.min.js'),
    ),
  'variants' => array(
      'source' => array(
          'files' => array(
              'js' => array('crossfilter.js')
            ),
        ),
    ),

);
return $libraries;

}

Most likely your version regex ist wrong. According to the source code, the version string looks like this:

crossfilter.version = "1.3.7";

The regex pattern needs to account for the whitespace around the equal-sign. I'd probably write it like this

'pattern' => '/crossfilter\.version\s*=\s*"(\d+\.\d+\.\d+)"/',


jQuery error in a theme I'm trying to run a jquery script for my Drupal 8 site, but in the error console, I get a TypeError: $ is not a function. I know this usually happens when jQuery isn't loaded, but the jquery.min.js is loaded fine. Is it loaded too late? Do I perhaps need a wrapper?

In my theme.libraries.yml, I have the following:

global-styling:
  version: 1.x
  css:
    theme:
      css/style.css: {}
  js:
    js/script.js: {}
  dependencies:
    - core/jquery

My script is simply

$('#some-element').on('click', function() {
  // Do something
}

I would think this is all I need, or am I overlooking something?

Edit:

I don't think this is a duplicate question since:

This is Drupal 8
The dependency is defined in the libraries file. I would think this would take care of exactly the problem described in the other question.

In Drupal 8 jQuery is added in the non intrusive way, this means that $ is not defined in the global space.

What you should do is to use closures (this is a very good idea, as it makes it easy for you to fix potential issues with colliding variables names. $ is used by other frameworks as well.

This is done by wrapping your code in a anonymous function so you don't need to get variables from the window object but can get them from the function definition. This means that you can easily change the source one place and it will effect all of the script you have written.

(function ($, Drupal) {

  // It's best practice to use strict mode, can help avoid some browser issues.
  'use strict';

  // Generally you always want to use behaviors, remember to depend on Drupal js.
  Drupal.behaviors.name = {
    // Called on document ready and when no elements is added to the page.
    attach: function (context, settings) {
      $(".selector", context)...
    }
  }

  // Sometimes you just want to do something when DOM is ready.
  $(document).ready(function() {
    // Stuff to do as soon as the DOM is ready;
  });

})(window.jQuery, window.Drupal);


Load custom template from MENU_CALLBACK Here's my current situation: I have an external authentication platform that loads in Drupal via an iframe. When the user is authenticated, the external application redirects the user to a Drupal endpoint I set up using:

function mymodule_menu() {

    $items['mymodule/oauth'] = array(
        'title' => 'My Module Receiver',
        'page callback' => 'mymodule_oauth',
        'access callback' => TRUE,
        'type' => MENU_CALLBACK,
        'file' => 'mymodule.pages.inc'
    );

    return $items;
}

And then my callback:

function myapp_oauth() {

    // Does some stuff, authenticates the user, etc

    echo '
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

Please wait...

';
    exit;

}

This seems like an incredibly sloppy way to handle this to me, I would prefer not to have to exit the application, and ideally I would want to simply define a tpl template file to load in place of the theme files for this page. Can someone recommend a better way to handle this?

You can define a theme function that uses a template file, and then use theme function to for the menu callback output.
The following is example code for Drupal 7; similar code can be used for Drupal 6.

function mymodule_theme() {
  return array(
    'mymodule_oath' => array(
      'variables' => array('id' => NULL), // This is the list of the variables that will be passed to the template file.
      'template' => 'mymodule_oath', // Change this to the template file name.
    ),
  );
}

function mymodule_oath() {
  // Does some stuff, authenticates the user, etc.

  print theme('mymodule_oath', array('id' => 10));
  return NULL;
}


Looking for a function that searches for nodes Is there a function in Drupal-7 that looks or searches for nodes that match some criteria (e.g. promoted nodes, published nodes, nodes of a specific content type), rather than using Views?

The closest thing that you get is EntityFieldQuery, which will allow you to construct a query that will yield the nodes that match the conditions.


Field with unique and auto-increments values I have a content type that in one of their fields need a value that is unique and auto-increment.
There are several obvious solutions:

Use the node id that is unique and auto-increment.
The Serial module.

The problem with these solutions is that they use the MySQL auto-increments.

Drupal, by default, auto-increments the node ID (nid) and other IDs by one digit for each piece of content you create. You can see this if you visit your site by the node ID path:

http://www.example.com/node/1
http://www.example.com/node/2
http://www.example.com/node/3

However, sites that use database replication as a backup strategy (is my case) often will have non-sequential ids, meaning that you could see nids jump by two or more digits.

http://www.example.com/node/10
http://www.example.com/node/15
http://www.example.com/node/20

The MySQL auto_increment_increment variable determines how many digits to jump for each successive auto_increment value.

And then I have this problem:

How I can do to have a field with unique and auto-increments values?

You can achieve it yourself in your custom form submit, lets suppose your field name is  myfield ( machine name will be field_myfield and it is text) and your content type is news ( change them with your data)
first in form alter you can hide it ( it you don't want user see it )
Get idea from my code

function yourmodule_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == 'news_node_form'){
        if($form['nid']['#value']){
          // if we are in adding new node hide that field and add custom submit handler
                hide('field_myfield');
                $form['#submit'][]='_my_autoinrement_submit_handler';
            }
    }
}

function _my_autoinrement_submit_handler($form, &$form_state) {
$lastValue=0;
// search for the last value
$query= db_select("field_data_field_myfield","mf") ->fields("mf")
 ->condition('bundle', 'news','=')
    ->condition('status', 1)
    ->orderBy('field_myfield_value', 'DESC')
     ->range(0,1);
     $result = $query->execute()->fetchAll();
     if($result){
         //get last value entered before this
        $lastValue= current($result)->field_myfield_value;
     }
     // increment last value ( biggest one )
     $lastValue ++;
   //set it in node
    $form_state['values']["field_myfield"]['und'][0]['value']=$lastValue;

}