Sort by taxonomy term name in Views? So I feel like I must be missing something obvious, but I can't find a solution to my situation. I'm trying to sort some nodes by the chosen taxonomy term name. This is Drupal 7, Views 3.

I have a taxonomy vocabulary 'Country' that is setup something like:

Asia
--Bangladesh
--India
--Vietnam
Afria
--Algeria
--Libya
--Nigeria

On the content type ('Partners') I have a taxonomy field called field_country. I happen to be using the Hierarchical Select module to make sure that, for this field, only the deepest levels are chosen (countries, not regions).

So all of that works and I can display the country chosen as a field in the view.

But I can't seem to figure out the correct way to sort by that country name. When I add the field_country field to the sort criteria, the ordering doesn't make sense. When I check the SQL statement it actually shows that it is sorting by field_data_field_country_field_country_tid. So it seems to be sorting by the tid rather than the actual term value. Although, a quick scan of the tid values shows that it isn't even sorting correctly by tid!

Here is what the SQL looks like:

SELECT DISTINCT node.nid AS nid, node.title AS node_title, field_data_field_country.field_country_tid AS field_data_field_country_field_country_tid, 'node' AS field_data_field_location_node_entity_type, 'node' AS field_data_field_country_node_entity_type, 'partners:block' AS view_name
FROM
{node} node
LEFT JOIN {field_data_field_country} field_data_field_country ON node.nid = field_data_field_country.entity_id AND (field_data_field_country.entity_type = 'node' AND field_data_field_country.deleted = '0')
WHERE (( (node.status = 1 OR (node.uid = 1 AND 1  0 AND 1 = 1) OR 1 = 1) AND (node.type IN  ('partner')) ))
ORDER BY field_data_field_country_field_country_tid ASC
LIMIT 9 OFFSET 0

Any suggestions? Is there a magical relationship I have to activate to get the correct sort option available?

Thanks!

Wow do I feel stupid today. I've done this before, but just seemed to have a brain issue.

Very simple:

Add a relationship for "Taxonomy: Terms on node". Select the country vocabulary.
In the sort criteria, select "Taxonomy term: Name" (I believe this gets added by step 1) and make sure the correct relationship choice is selected.


The ComplexData plugin does not exist, after upgrade After my Drupal 8.51 upgrade, I keep getting this error.

  Uncaught PHP Exception Drupal\Component\Plugin\Exception\PluginNotFoundException: "The "ComplexData" plugin does not exist."

I have Googled it for two days and haven't found any information about what this is or how to fix it. I get the error while using Panels/Page Manager. I did upgrade both modules to the 4/14 release but that didn't help. Any ideas?

I read in another post where an OP wrote that Composer didn't put all the /core files in place, so he manually copied the /core directory and all its files and that solved a similar problem he was facing.

I tried that last night, manually copying the Drupal 8.51 /core folder into my local install. It fixed the problem. I then copied the files into production and all is well. Thanks to all who commented.


How do I add related products? I want to display, let's say, three additional SKUs (e.g., skuredring3 and skuredring4) similar to the one of the displayed product (e.g., skuredring).

Is this even possible?

Related products in Drupal Commerce can be accomplished in a variety of ways:

As entity references, rendered in a related products view
Using this approach, relationships are defined manually by Store/site managers (they curate/associate what specific products/skus to show as related) as they edit each product node.  Then the view is setup with a contextual filter for the current node ID and a relationship to show all values assigned to the "related products" entity reference field.
Refer to this "Related Products Guide using Views and Entity Reference" post that walks you through the approach.
As taxonomy tags, rendered in a related products views
Using this approach, relationships are defined manually by Store/site managers (they tag products with specific classifications) as they edit each product node.  Then the view is setup with a contextual filter for the taxonomy terms on the current node and a relationship for terms in the specific taxonomy on that node.  See this similar post, "Related Articles - A Block View Of Nodes With Common Taxonomy Terms"
As a view that programmatically looks for skus of a particular pattern
Using this approach, store/site managers don't have to tag products- they just need to ensure following a standard ruleset in defining skus for products.  Then the site manager would setup a view of Commerce Products with a filter on the product sku field containing "skuredring" in your example.  This approach locks the view into showing only those products with the sku.


Custom Module Remote Fails Checksum with Drush Background

I have several proprietary Drupal modules that my company uses. We want to update these across all our sites. To that end, I've built an endpoint that produces code according to the (ill-documented) specifications required at https://www.drupal.org/node/542202#project%20status%20url

For those interested, the endpoint gets the project information from Bitbucket, where each core has a branch, then gets tags and parses out the tags as releases so it can get the newest one.

There's also some unzipping and re-zipping that goes on to put the returned .tar.gz in a format that Drupal accepts.

This works alright but there's a

Problem

While the GUI for Drupal works fine to update the module from the custom remote, Drush fails. Running drush up gives me the expected prompts, recognizes the new version, downloads the file and then fails. The message:

File {filename} is corrupt (wrong md5 checksum).

The mdhash in my XML file is correct, according to the md5 utility on MacOS. (It's calculated using PHP's md5_file utility). So, whenever I download the tar manually and check the hash, it's fine. But I cannot get drush to agree with me.

Any ideas? Thanks in advance.

Answer

This isn't a good answer, but it works:

There is an undocumented drush flag --no-md5 and if you pass that to drush up it will skip the md5 check and the update will succeed.


Drupal 7 page template for right to left languages e.g. page--rtl.tpl.php Trying to create a custom page.tpl dependant on language or 'right to left' support, here is what i have so far.

function THEMENAME_preprocess_page(&$variables) {
    if($variables['language']->language == 'ar') {
      $variables['template_file'] = 'page--ar';
    }
}

Am i on the right track?

In Drupal 7, what you'll want to do is something along these lines:

function THEMENAME_preprocess_page(&$variables) {
  if($variables['language']->language == 'ar') {
     $variables['theme_hook_suggestions'][] = 'page__ar';
  }
}

which will cause Drupal to look for a page--ar.tpl.php file (or even a THEMENAME__page__ar() function, which is the reason for the underscores in the variable value btw) when $language is set to ar.

A possible enhancement:

function THEMENAME_preprocess_page(&$variables) {
  if(isset($variables['language'])) {
     $variables['theme_hook_suggestions'][] = 'page__' . $variables['language']->language;
  }
}

will cause Drupal to look for page--XX.tpl.php files and will use them if they exist; otherwise, will just keep looking for a less specific template and will end up using page.tpl.php.  This way, you don't have to have a lot if's in your preprocess logic.

For that matter, you can also do something like this:

function THEMENAME_preprocess_page(&$variables) {
  if(isset($variables['language']) && $variables['language']->dir=='rtl') {
     $variables['theme_hook_suggestions'][] = 'page__rtl';
  }
}

and now you would have one page--rtl.tpl.php file for all rtl languages.

Lots of possibilities abound here, a quick:

drupal_set_message('<pre>' . print_r($variables['language'], TRUE) . '</pre>');

in the beginning of your preprocess function will show you what you have to work with.


With current D8 status, what's the decision tree for creating a new content entity type versus creating a Content Type for the "Node" content entity? We have seen four years and Drupal 8's first release since the accepted answer was written for the question "When is it appropriate to create an Entity versus just adding a new content type?"  And, entities are more central to Drupal 8 than they were in Drupal 7.(RefB, RefC, RefD)

In this new Drupal 8 world, what is the decision tree for creating a new content entity type versus a new Content Type for the content entity of type "Node"?

As you consider a response, please consider the following:

Is a new Content Type for the content entity type of "Node" still appropriate in 99% situations versus a new content entity type?
Does the decision tree now include more, better, or clearer reasons to veer away from using the "Node" content entity type and instead create a new content entity type?  And if yes, what are they?  Do they include:

Performance?
Security/permissions?
The number of modules that work with Node-entity-type Content-Types and do not work with other content entity types?

Perhaps -- based on the previous accepted answer that is referenced above -- the only general reason to do a custom content entity type is if you want to group Node data, e.g. with taxonomy terms, or otherwise annotate Node, e.g. with comments?

Module compatibility seems like a particularly interesting consideration for a decision tree.  At present, few of the most-installed modules have a release for 8.x that is not merely alpha, beta, or rc (a release candidate).  And it seems difficult to identify how many of them will work out-of-the-box with a new custom entity type versus a new Node-entity content type.  There does not appear to be a project attribute to distinguish between those that are "written for entities" versus "written for node entity content types".

Take a look at pathauto, which is currently the fourth-most installed module of those that have any kind of 8.x release.  Folks are working hard on a 8.x version that generally supports entities and not just Node-entity-type Content Types.  But what about all the other modules?  And will modules that support entities going to generally require custom content entity types to have module-specific "hooks" before the module will work with them?  (Versus how the modules may just work straight out of the box with new Content Types?)  That appears to be the kind of challenge the pathauto team is working with, and perhaps it is a reason to veer away from a custom content entity type?

It might also be worth mentioning that Drupal 8 core contains a UI for creating new Content Types for the content entity of type "Node", but it does not currently contain a UI for creating new content entity types. (RefX, RefY, RefZ)

Decision tree for choosing between creating a new Node-entity-type Content Type versus a new content entity type:

Are you a programmer, or do you have easy access to a programmer?

If no, then you are presently pretty-much limited to creating new Node-entity Content Types.  (There isn't a UI in core for creating new content entity types, and the Entity Construction Kit (ECK) contrib module currently only has an alpha release.)
If yes, then continue...

Do you know exactly which contrib modules you want to leverage for your data?

If no, then the safe bet is probably to just create a Node-entity Content Type.
If yes, do those modules already support the custom entity type(s) you're considering, or are you willing to help enhance them so they will or recreate the desired functionality in your module?

If no, then just creating a Node-entity-type Content Type may be best for you.
If yes, then continue...

Will the actual content data that is enabled by your module merely help group or annotate other content data?  (So that it will seldom be viewed on its own.)

If yes, then consider whether your module is like the existing entity types for taxonomy terms and comments.  If it is, then a new entity type may be a safe bet.
If no, then continue...

Can you clearly articulate why a new Node-entity-type Content Type will not work for you?

If no, then your safe bet is to probably just create a new Node-entity-type Content Type.
If yes, then continue...

Lastly, are you sure that you can't just extend the Node-entity-type and that you want to recreate all of its useful functionality like CRUD operations?

If yes, then go ahead and create a new custom entity type.
If no, or if you're not sure, then you probably want to engage some experts to help you decide.

Notes:

This decision tree does not consider performance or security.  I'm not sure if or when a new custom content entity type would perform better and be more or less secure than a Node-entity-type.
Even if this tree is a good answer, it will probably not remain one over time due to updates in Drupal core and contrib module releases.  StackExchange doesn't seem to accommodate how the "best" answer today may not be the best answer tomorrow.)


Commerce Product generate Preview on Add Product page I want to add a Preview button in Commerce Product Add form. Before adding product, user can see Preview of Product same as Product Display/Detail page.

I am using Rules to create Product Display after saving Product.

I have added below code in form_alter hook but  :

//Add Preview

function mymodule_form_alter(&$form, &$form_state, $form_id) {
 if ($form_id == 'commerce_product_ui_product_form') {
       $form['actions']['preview'] = array(
          '#type' => 'submit',
          '#value' => t('Preview'),
          '#weight' => 10,
          '#submit' => array('product_preview'),
        );

        // Some special stuff when previewing a node.
        if (isset($form_state['node_preview'])) {
          $form['#prefix'] = $form_state['node_preview'];
          $node->in_preview = TRUE;
        }
        else {
          unset($node->in_preview);
        }
  }
}

function product_preview($form, &$form_state, $node) {
  module_load_include('inc', 'node', 'node.pages');
  $node = new stdClass();
  $node->field_product['und'][0]['product_id'] = $productId;
  $node->title = 'test';
  $node->uid = 2;
  $node->type = 'commerceproduct';
  $node->in_preview = TRUE;
  $form_state['node'] = $node;

  node_form_build_preview($form, $form_state);
}

Above code displays preview for edit but problem is in node object i am getting $node->field_product['und'][0]['product_id'] value not whole Product object. So any updated value of product form fields won't be reflected in preview.

I am not sure how to build whole product object within node object.

Can anyone tell me what is missing here ?

You can try rendering the product entity and attaching it to the form.

To render the product entity (see entity_view):

// Extract the referenced product from the node.
$node_wrapper = entity_metadata_wrapper('node', $node);
$product = $node_wrapper->field_product->value();

$product_view_mode = 'full'; // Set the view mode you want to use to display this product.

// This will return a render array.
$rendered_product = entity_view('commerce_product', array($product->product_id => $product), $product_view_mode);

Finally, alter the form so that it also contains the rendered product.

// Now add the markup to the form.
$form['product_preview'] = array(
  '#markup' => render($rendered_product);
);


PDO Error, __construct(): php_network_getaddresses: getaddrinfo failed: I'm pulling a site from my production server down to a new development server that I'm setting up.

I can't get this to work though unfortunately. I imported my database into mysql and made sure that all of my account/privileges information was correct with what I had in my site-root/settings.php file.  I even created a new account with all the privledges and edited my settings.php file to it and still couldn't get it to work.

Is there somewhere else in my drupal installation that I need to input this information that I'm not aware of?   As a side note, I have other sites running locally in the same development environment, and they're running fine, however, I've noticed that they don't have a settings.php file.

Details:

This installation was originally created in MS WebMatrix using the Acquia Distribution As far as I can tell there's not a huge difference between this and other drupal distros beyond it having some really basic stuff already included. My other sites, that work, are running bear distro  and my development server is just your basic XAMPP setup.

This is what's in my settings.php file.  Obviously, the db, user and passwords where all replaced with comments for security reasons.  You'll just have to trust me that they match up.

$databases = array( 'default' => array( 'default' => array ('database' => '####commented for security###', 'username' => '####commented for security###', 'password' => '####commented for security###', 'host' => 'localhost', 'driver' => 'mysql', 'port' => '3306', 'prefix' => '' ) ) );

Here is a screenshot:

Thanks in advance for your time!

The default settings.php is located at sites/default/settings.php, not in the root of your drupal installation.  I have no idea why one of the server techs at my hosting company moved the settings.php into the root, but that was what my previous confusion was.

As a side-note, if your moving from a production to a development server, make sure that you setup your host in settings.php to localhost.  As a corollary, if you're moving from development to production, make sure you set your host field from youraddress.com (or youraddress.hostingaddress.com) from localhost.  It would be nice if there was a field somewhere in drupal settings to handle this, so that you didn't have to snoop through the settings.php to find/set it.  However though, this is likely not possible since drupal pulls everything like this from databases and it has to have these settings in order to see the database.  Just food for thought.

I also normally find it useful to look at code snippets rather than trying to understand what someone said, so here's an example of what your database line in settings.php should look like if your settings up a generally basic development server.

$databases = array (
  'default' =>
     array(
        'default' =>
         array (
            'database' => '##Your_database_name##',
            'username' => '##your_database_username#', #comment & store old user from production server here for safe keeping
            'password' => '##your_database_password##', #comment & store old pw from production server here for safe keeping
            'host' => 'localhost',   #comment and store production database url here
            'driver' => 'mysql',
            'port' => '',  #localhost shouldn't normally need a port, but your production sever likely does, so comment and store that on the side here.
            'prefix' => ''
         ),
    ),
);


Combining views slideshow and views gallery on single page I have a views Slideshow on one page. I also have a views Gallery on another page. I want the views gallery to appear below the views slideshow on a single page. Please could anyone help me out. I have been trying a lot, but I'm unable to do this.

try the following:

create a copy of one of the views as a BLOCK instead of a page
under block configuration (admin/structure/blocks) for that view, limit it by page to ONLY show for the view still set as a page, and place it in the content or content bottom region


Meta tag page descriptions Possible Duplicate:
  Meta tags aren't saved with all content types

I'm using Meta Tags to control the meta data on my Drupal 7 site.  This module seems to give your nodes control over what your page descriptions display via the vertical menu at the bottom of the page you're editing.  This description doesn't show though.

The only thing I can think of is the global options which you can find by "configuring" the module itself.  If I set a global page description, it will show on all pages, and if I disable it, or leave it blank, there will be no description shown.

Why is the data set on individual nodes not overwriting this global quality?  There doesn't seem to be another module to help me with descriptions either.

I've used this module successfully today actually - with no configuration alterations.

One reason for things not working for you could be your theme which after all does control the markup for your site.


Creating a view that groups results by month/year Does anyone know how to build a view that groups the results by Month/Year but can print the results expanded. Take the following dataset:

Events

    Event Name  Event Date
    ----------  ----------
    Event 1     2011-05-01
    Event 2     2011-05-15
    Event 3     2011-05-30
    Event 4     2011-06-04
    Event 5     2011-06-22
    Event 6     2011-07-01
    Event 7     2011-08-16
    Event 8     2012-01-01
    Event 9     2012-01-02
    Event 10    2013-05-15

I would like Views to output that data in the following format:

    May 2011
    --------
      Event 1
      Event 2
      Event 3

    June 2011
    ---------
      Event 4
      Event 5

    July 2011
    ---------
      Event 6

    August 2011
    -----------
      Event 7

    January 2012
    ------------
      Event 8
      Event 9

    May 2013
    --------
      Event 10

So the view would not actually be grouped in SQL it just needs to print out the events with headings visually grouped by month and year.

You can group by any field, including Month-year. You have to select your date field and customize the output. Then, Views can group on the field, using the "Grouping" options under Format: Settings.


How do I get the $language object inside a form builder? I have this necesity to use $language inside MY_MODULE_form($form, &$form_state) function and it seems is not available. I tried to define it as global, but it displays blank.

global $language_content;
dpm($language_content->language);

My simplified structure of MY_MODULE_form() looks like this:

function MYMODULE_form($form, &$form_state) {
global $language_content;
$form['name'] = array(
      '#type' => 'fieldset',
      '#title' => t('Name'),
  );
  $form['back'] = array(
      '#markup' => '
'.t('Back').'
',
  );
  return $form;
}

I found a hardcoded PHP solution:

if(strpos($haystack, 'en')) {
    $back_path = "/project/en/my/home";
    }
  if(strpos($haystack, 'fi')) {
    $back_path = "/project/fi/my/home";
  }
  $form['continue-shopping'] = array(
      '#markup' => '
'.t('Back').'
',
  );

I am looking however to something more elegant.

Always use l() (or url(), which justs generates the URL) for generating links; then you, don't have to worry about the current language, base path, whatever clean URLs are enabled or not.

l(t('Back'), 'my/home');

That said, global $language should always work.


How to show translated taxonomy terms in term listing in content listing style I have question about translation of taxonomy terms in Drupal 8. Let's assume this configuration:

New created vocabulary, vocabulary language - not specified, terms language - not specified, show language selector, enable translation.

With this config, I should be able to translate new created taxonomy terms, if I select specific language while creating one. So I create taxonomy term in English language. Then I go and translate that term by clicking the "translate" tab in this term. I fill all values and save the form. Term is now translated to another language.

And now comes the difference - when I do the same approach with content, in content overview I see all nodes - original, and also translated. When I do this with taxonomy terms, in vocabulary listing I see only taxonomy term which was created first (so in my example the English one) - see the image.

How can I achieve the same behaviour as in content listing? I am expecting, that all terms will be listed here (as in content overview), or at least, when in specified language, terms with this language set should be shown (e.g. in English only links in english translations, if they exists). Taxonomy terms and nodes are all entities, so I would expect the same behaviour while translating them... Or is this a bug?

Thanks

Yes, it kind of is a bug.

The page is I think one of the the only two lists (the other is comments) that is hardcoded and not a view.

Views have configurable behavior to show show the entity in the best translation, or show the default translation.

You can replace this list with a view yourself, just create a view that lists terms on that path. Views doesn't support a few features of that UI however, specifically, that is the drag and drop hierarchy and weight handling. if you don't need that, fine. If you do, you might need to look for contrib modules that offer such features, I'm not sure if there are some for Drupal 8.


Template vs hook for views filed output There are two possible solutions ( php field and view field are not recommended as I know ) to override output of a view field

Create template (tpl) file for field and code for desired output
Use hook hook_views_pre_render

as per the various articles, its not good to have too much templates in drupal.

which approach is good and loads fast ?

as per the various articles, its not good to have too much templates in drupal.

With respect, and depending on exactly what you mean by "too much", that's pretty much nonsense. If we're talking about 10,000 template files on an uncached site, then yeah, you would probably have problems. But those problems would be with your application's design; in the real world, with a normal application, that statement is just untrue.

  which approach is good and loads fast ?

Both are 'good' (or 'bad'), depending on your point of view, and how well you write the code for them; differences in load times will be negligible, especially with caching. If you're really worried about micro-optimising, then you need to benchmark your site, while it's under load and sitting on production hardware; that's the only way you'll know which method is faster for your use case.

It's not possible to give a blanket "this way is quicker" statement, because it depends on what the rest of the site is doing, how you have it and the server configured, and how good your code is. Always test in the real world rather than ask for others' experiences - you have no way to know if their experiences actually apply to your scenario.


Import a custom field type record and relate it to a node I've created a module for a custom field type which selects images from cloudinary.

Is there a way to dynamically add entries as part of an import script? I've tried updating the database directly, but this is not ideal as it does not store any relations.

There is an answer for something similar, however I want to relate mine to an existing node. Is it possible with Node Export? If not, what am I doing wrong here:

My schema:

function cloudinary_field_schema() {

    $columns = array(
        'publicID' => array('type' => 'varchar', 'length' => 255, 'not null' => FALSE),
        'title' => array('type' => 'varchar', 'length' => 255, 'not null' => FALSE),
        'caption' => array('type' => 'text', 'size' => 'big', 'not null' => FALSE),
        'url' => array('type' => 'varchar', 'length' => 255, 'not null' => FALSE),
        'credit' => array('type' => 'varchar', 'length' => 255, 'not null' => FALSE),
        'keywords' => array('type' => 'text', 'size' => 'big', 'not null' => FALSE),
        'description' => array('type' => 'text', 'size' => 'big', 'not null' => FALSE),
        'primaryImage' => array('type' => 'int', 'size' => 'tiny', 'not null' => FALSE)
    );

    return array(
        'columns' => $columns
    );

}

My hook menu contains this:

function cloudinary_menu() {
    $items['cloudinary/add'] = array(
        'access callback' => TRUE,
        'page callback'  => 'add_image'
    );
}

And bad practice importer:

function add_image () {

  $new_image = array();

  //get post
  $entity_id = $_POST['entity_id'];
  $publicID = $_POST["publicID"];
  $url = $_POST["url"];
  $title = $_POST["title"];
  $caption  = $_POST["caption"];
  $description = $_POST["description"];
  $keywords = $_POST["keywords"];
  $credit = $_POST["credit"];
  $primaryImage = $_POST["primaryImage"];

  //validate
  $entity_id = htmlspecialchars( $entity_id );
  $publicID = htmlspecialchars($publicID);
  $url = htmlspecialchars($url);
  $title = htmlspecialchars($title);
  $caption = htmlspecialchars($caption);
  $description = htmlspecialchars($description);
  $keywords = htmlspecialchars($keywords);
  $credit = htmlspecialchars($credit);
  $primaryImage = htmlspecialchars($primaryImage);

  //add to new image
  $new_image["entity_id"] = intval($entity_id);
  $new_image["field_cloudinary_publicID"] = $publicID;
  $new_image["field_cloudinary_url"] = $url;
  $new_image["field_cloudinary_title"] = $title;
  $new_image["field_cloudinary_caption "] = $caption;
  $new_image["field_cloudinary_description"] = $description;
  $new_image["field_cloudinary_keywords"] = $keywords;
  $new_image["field_cloudinary_credit"] = $credit;
  $new_image["field_cloudinary_primaryImage"] = $primaryImage;
  $new_image["delta"] = 0;

  //establish if this is a valid node using entity_id
  $result = db_query('SELECT * FROM {node} n WHERE n.nid = :nid', array(':nid' => $new_image["entity_id"]));

  //if it is, update cloudinary
  if($result->rowCount() > 0) {
    $r = $result->fetchAssoc();
    $new_image["entity_type"] = "node";
    $new_image["bundle"] = $r["type"];
    $insert_id = db_insert('field_data_field_cloudinary')->fields($new_image)->execute();
    drupal_json_output($insert_id);
  } else {
    drupal_json_output(false);
  }

    drupal_exit();
}

I'm very new to Drupal so struggle a lot with this stuff! Any help greatly appreciated!

Just to double check: You have a content type with fields for your images from cloudinary, and you have nodes that already exist in your site that you need to get the data from Cloudinary into your node?

It looks like your looking up nodes through a query by the entity id (nid). Instead of doing that I would simply just load the node object by the node_load function (like node_load($entity_id). You should be able to then assign the value of cloudinary fields in the node (it's gonna be something like $node->FIELD_NAME['und'][0]['value']). Once you have all your custom fields inputed, just use node_save($node).


FAPI redirect *and* store to local database What I'm trying to achieve

I am successfully using the Form API in Drupal 7 to dynamically alter Webforms to redirect to an off-site URL on submit.

What I need is twofold; I need (a) for the client to visit the offsite URL so the site can store a lead via query string parameters, as well as (b) for the same information to be documented in my local Drupal database.

Every lead must be documented, so I have tentatively ruled out JavaScript/AJAX as an option.

How I tried it

I thought the best way to do this was to set up a module with $form_state['redirect']:

/**
 * Implement hook_form_alter to change the form's submit action
 */
function myform_form_alter(&$form, &$form_state, $form_id) {
    $form['actions']['submit']['#submit'][]='myform_submit';
}

/**
 * Callback as specified above
 */
function myform_submit($form, &$form_state) {
    // Values for the query string
    $vals = array('mykey' => 'myval');

    // Redirect appropriately
    $form_state['redirect'] = array(
        // $path
        'http://www.anotherwebsite.com/',
        // $options
        array('query' => $vals),
        // $http_response_code
        302,
    );
}

I did that, and as expected, the user is redirected immediately after form submission. However, the Form API does not submit to my database before redirecting the user.

I read the FAPI documentation for Drupal 7. I sought using #action, although it apparently reports only accepting internal values and my users must visit an offsite URL. I wound up using redirect in the meantime, which was no longer documented but was suggested in the comments.

Where do I go from here?

EDIT: tenken's response works, but I have another problem!

My callback now uses array_unshift($form['#submit'],'my_callback') and via drupal_http_request, is submitting to both websites. However, my webform is still not saving submissions locally, and instead on submit, redirects to self (even with no hook_form_alter).

EDIT: added option (1) after thinking about this more, haha. It's a much simpler solution.

(1)

If the below is to complex you (and you actually want to POST something) you could form_alter the form and append your own additional FAPI #submit function which uses drupal_http_request() to POST/GET the url with all the submitted form params.

(2)

I think you want to set the destination value from within the #action of the form to be wherever the default webform submit path is and tag on a destination querystring parameter to the action which drupal will then goto after the form has been validated/submitted.

I know you said you tried using #action but I'm talking about the action being the drupal action and destination being a remote url (url-escaped).

Eg, I have customized a login form to use various login backend logic depending on the url of the login: /user/login, /student/login, /staff/login ... etc. I then make the destination of a succcessful login goto a specific drupal page. destination is used by drupal_goto() to redirect the user anywhere -- even an external url.

Here is a small example from code I have in D7:

/**
 * The following 2 functions allow our form overrides to occur.
 */
function MYMODULE_form_user_login_block_alter(&$form, &$form_state) {
  if (_MYMODULE_auth_is_student_login_page_url()) {
    $form = $form + array('#auth-destination' => 'student');
    _MYMODULE_auth_user_login_form_alter($form, $form_state);
  }
  if (_MYMODULE_auth_is_staff_login_page_url()) {
    $form = $form + array('#auth-destination' => 'staff');
    _MYMODULE_auth_user_login_form_alter($form, $form_state);
  }
}

function MYMODULE_form_user_login_alter(&$form, &$form_state) {
  if (_MYMODULE_auth_is_student_login_page_url()) {
    $form = $form + array('#auth-destination' => 'student');
    _MYMODULE_auth_user_login_form_alter($form, $form_state);
  }
  if (_MYMODULE_auth_is_id_login_page_url()) {
    $form = $form + array('#auth-destination' => 'staff');
    _MYMODULE_auth_user_login_form_alter($form, $form_state);
  }
}

function _MYMODULE_auth_user_login_form_alter(&$form, &$form_state) {
  global $conf;
  $saveForm = $form;
  $form = array();
  # overrides the default validator.
  foreach ($saveForm as $key => $value) {
    if ($key == '#validate') {
      $form[$key] = array();
      foreach ($value as $validator) {
        if ($validator == 'user_login_authenticate_validate') {
          // If we progressed down to this level of nested Alters, we have
          // #auth-destination.
          $type_of_login = $saveForm['#auth-destination'];
          switch($type_of_login) {
            case 'staff':
              // These functions are custom validate functions whose logic is
              // copied/altered from the default
              // 'user_login_authenticate_validate' implementation.
              $validator = 'MYMODULE_auth_staff_authenticate_validate';
              // the form posts back to itself and supplies a unique destintation.
              $form['#action'] = '/?q=staff/login&destination=%3Cfront%3E';
              break;
            case 'student':
              $validator = 'MYMODULE_auth_student_authenticate_validate';
              // the form posts back to itself and supplies a unique destintation.
              $form['#action'] = '/?q=student/login&destination=student/my-surveys';
              break;
            default:
              break;
          }
        }
        $form[$key][] = $validator;
      }
    }
    else {
      $form[$key] = $value;
    }
  }
  $form['name']['#title'] = ($type_of_login == 'Staff') ? 'Staff Username' : 'StudentCampusID';
  unset($form['links']);
}


Webform comfirmation page token Example I have webform at http://www.example.com/webform. Once I submit the form it will redirect to confirmation page which is http://www.example.com/node/8/done?sid=18&token=ggffdgdf7g8df7g89d7fg98df77

May I how to get this token value from database? I had tried md5() for submitted time, but the value is not the same.

I found the answer in the webform.module file:

/**
 * Return the access token for a submission.
 *
 * @param object $submission
 *   The submission object.
 *
 * @return string
 *   The access token for the submission.
 */
function webform_get_submission_access_token($submission) {
  return md5($submission->submitted . $submission->sid . drupal_get_private_key());
}

So it's an MD5 hash of a concatenation of the submission date, submission ID and a random private key, set by the webform module.


Better understanding of Drupal behaviors I read about Drupal behaviors today, and I tried writing the following code.

(function ($) {

  Drupal.behaviors.mymodule = {
    attach: function (context, settings) {
      $('#mymodule_id', context).change(function () {
        alert('Handler for .change() called.');
      });
    }
  };

}(jQuery));

Is Drupal.behaviors.mymodule the namespace?
What are the context and settings parameters passed to the Drupal behavior?
Is this the equivalent of document.ready()?
Can I attach any number of functions?
Can I define JavaScript functions which will be called somewhere?

In short, the advantage of Behaviors over document.ready() is that they are automatically re-applied to any content loaded through AJAX. mymodule is your namespace, which needs to be unique. context is the part of the page for which this applies, for example a part of a form that has been updated with AJAX. You can attach multiple behaviors, but I think you need to use a unique name (mymodule) for each of those.

Have a look at the following resources for more information:

Drupal behaviors
Drupal Javascript API
Changes in the Drupal JS API for D7


Override the taxonomy pages In Drupal 7, you can use taxonomy-term.tpl.php to override taxonomy pages.

Inside the taxonomy-term.tpl.php page, you can use <?php print $term->field_NAME['und'][0]['value'];?>to print out the content of any fields attached to the taxonomy term. (*)

However, how do you get to the list of nodes that is displayed on the taxonomy page?

There doesn't seem to be anything in the taxonomy-term.tpl.php file to indicate how to theme the nodes that are displayed on the term page.

I know you can use Views to over ride the page. However, Views does not let you display nodes tagged with a term and fields that are attached to the term in a single View.

(*) I know you are not supposed to use UND. However, the correct method for access node based fields does not seem to work with taxonomy based fields.

The template file you want to use is not taxonomy-term.tpl.php; that's used for the taxonomy header at the top of the page. The template file used is node.tpl.php.

If you look at taxonomy_term_page() which is used to build the term page view, you will see the nodes are build separately by calling node_view_multiple(). node_view_multiple() is just a wrapper for node_view(), which uses the standard node.tpl.php file.

Also you should be able to use field_get_items() for taxonomy terms. I'll look for something like $field = field_get_items('taxonomy_term', $term, 'field_name');.

I haven't tried but it should work.

You should really never use 'und', but the constant LANGUAGE_NONE.


Error while mass subscribe using simplenews I get this error while i am trying to mass subscribe users/email for a newsletter using the simplenews module in D7. How can i solve this error ?

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column
'tid' cannot be null: INSERT INTO {simplenews_subscription}
(tid, snid, status, timestamp, source) VALUES
(:db_insert_placeholder_0, :db_insert_placeholder_1,
:db_insert_placeholder_2,
:db_insert_placeholder_3, :db_insert_placeholder_4);
Array ( [:db_insert_placeholder_0] =>
[:db_insert_placeholder_1] => 1285
[:db_insert_placeholder_2] => 1
[:db_insert_placeholder_3] => 1368003712
[:db_insert_placeholder_4] => )
in simplenews_subscription_save()
(line 1501 of /sites/all/modules/simplenews/simplenews.module).

You are getting this error because when it is trying to insert the taxonomy term ID:

INSERT INTO {simplenews_subscription} (tid ...

The value that is being passed is null:

Array ( [:db_insert_placeholder_0] =>

Best plan to fix this is to try and determine why it is not passing this taxonomy term. Did you select the term as an option when mass subscribing? This may be a bug or quirk in simplenews itself according to this thread or maybe an issue with corruption of your dataset.

Another way to resolve this if that is the case would be to alter that column to allow nulls (temporarily!), do your mass subscription action, manually add the correct taxonomy term to the database and then finish by restoring the null constraint to the column.


Date popup on exposed filter How can I get a date popup on the exposed filters of a view on D8 ?  I do not see the option, is it on D8 yet?

Currently, exposed filters in Views in Drupal 8 don't use the new HTML5 elements.  Essentially, you get text inputs, selects, or checkboxes/radios.

There is an existing feature request to add this to Drupal 8.

I suspect you could form alter the exposed form to change the types.  This is untested, but essentially what the patch on that issue does:

function MYMODULE_form_views_exposed_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $form['the_exposed_date_element']['#type'] = 'date';
}

That won't work for ranges, but it should give you a start.


How to show a block on user/uid but not on user/login and user/registration? I have public profiles for my users at /users/1 etc and show blocks on that page with the setting "Only the listed pages" of "user*".

Now those blocks also appear on user/login and user/registration pages.

How can I exclude blocks from those 2 pages?

Otherwise I'll probably use the Pathauto module to have the user profiles at /profile/....

Enable the PHP module, and use this for block visibility settings:

<?php
return (bool) menu_get_object('user');
?>


Browscap doesn't seem to hide blocks on google chrome for android I have a website where I write some web development articles in it, in the blog page, I have set a slideshow with Views because the most of the slideshow modules are useless (it's my personal opinion, I was needing that the slideshow shows the image the title of the article with its caption, there were no slideshow modules that can do that), I used a forked version of Responsly slideshow (it's not the big deal but I liked it because it's really simple), unfortunatelly the slideshow looks pretty bad on mobile devices, I used Browscap to hide the slideshow on mobile devices and works great, but, Browscap doesn't seem to hide blocks on google chrome for android, I still don't have time to work on the slideshow, so, is there something I can do to solve this problem??

NOTE: I don't know the version of google chrome for android that I'm using, my cellphone is a galaxy S (international version) with cyanogenmod 9, I am not sure if it's a bug or if it's my phone.

Using Browsecap (AKA 'user agent sniffing') will always be error prone, because there are so many different browsers, all with different user agents.

Instead, consider implementing a responsive design, using CSS3 media queries, to hide certain elements based on screen width.


apply css for particular node and do not apply for particular node I used the CSS injector module to replace the default CSS. I applied that CSS for  paths like node/*. How do I exclude node/add from that CSS (the one I created with the CSS injection module)?

This is the sort of thing that I'd do by code, but that's because that's just the way I roll.

In the template.php you will want something like:

function MYTHEME_preprocess_node($vars) {
  if (drupal_get_path_alias(current_path()) == 'node/add') {
    drupal_add_css(drupal_get_path('theme', 'MYTHEME') . "/css/foo.css");
  }
}

I hope this helps.. :)


Prevent logged in users from seeing other registered users information I'm using Drupal 8 and I have a security requirement to prevent authenticated users from seeing other authenticated users' profiles.

I have a view which customizes the user profile page of each authenticated user. Each logged in user can see their own profile by accessing the path /user-profile/userId.

Now if the user decided to randomly change the userId in the URL, they cannot access other users' profiles, since, in the view I have set the 'Filter Criteria' to current user. Which works perfectly.

However, if a user decided to randomly change the userId in the path /user/userId they will have access to other users information. What I need to do is to prevent them from accessing /user/userId.

It's important to mention that the users are free to change their own information using the URL /user/userId/edit

Any suggestions?

You should change the permission for authenticated users.

Go to admin/people/permissions and under user permissions dissallow authenticated users to View user information


Is there a module that creates a taxonomy of the world's languages? Before I go creating my own taxonomy with the worlds languages as terms, I just wanted to see if there was a module out there that is already handling this?

EDIT:

I did lots of searching for a module before posting here but just wanted to make sure I didn't miss anything before going my own way.

I searched for such a module fairly extensively but was unable to find anything.

In the end, I used the Taxonomy CSV Import/export module, which allows you to create a list based on a CSV (comma-separated value) file, which is very easy to prepare.  I then referenced one of the lists of languages on Wikipedia.  I would share my list with you except that mine is specific to my site; it doesn't list all human languages, but instead just the most popular ones in Asia.


Possible timing issues when using setActiveConnection to an external database under normal Drupal 8 operation I'm using Drupal 8.0.5. In my settings.php file I have defined an external database:

$databases['notificationsdb']['default'] = array (
  'database' => 'NotificationsDB',
  'username' => 'my_user_name',
  'password' => 'my_password',
  'prefix' => '',
  'host' => '127.0.0.1',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

I have then created a custom form where I need values from the NotificationsDB database to populate a form fields. In my custom form class in the __constructor I created an instance of my Notification Client class:

public function __construct() {
        $this->_notificationClient = new NotificationsClient();
}

In my NotificationsClient class I have the following code:

public function __construct() {
        // Set the active database to notificationsdb
        \Drupal\Core\Database\Database::setActiveConnection('notificationsdb');
        $this->_db = \Drupal\Core\Database\Database::getConnection();
    }
public function __destruct() {
        // Set the active database back to the default
        \Drupal\Core\Database\Database::setActiveConnection('default');
        // https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Database!Database.php/function/Database%3A%3AsetActiveConnection/8
}

When I go to view my form I get the following error:

Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'notificationsdb.shortcut_set_users' doesn't exist: SELECT ssu.set_name AS set_name FROM {shortcut_set_users} ssu WHERE (ssu.uid = :db_condition_placeholder_0); Array ( [:db_condition_placeholder_0] => 1 ) in Drupal\shortcut\ShortcutSetStorage->getAssignedToUser() (line 103 of core/modules/shortcut/src/ShortcutSetStorage.php).

From what I can tell the Shortcuts module is trying to run some queries against the NotificationsDB. I'm guessing this is a timing issue. I'm also concerned with how Drupal handles multiple database connections.

In looking at the getConnections method closer you can pass it the $target and $key parameters directly and it will return a handle to the specified database.

$this->_db = \Drupal\Core\Database\Database::getConnection('default', 'notificationsdb');

This way you don't have to mess around with setting the active database.


Plugin versus Module Drupal has many specific terms that can have different meanings depending on usage (e.g. view vs. a Drupal View). It looks like another in Drupal 8 is plugin & module. Generically, both seem to imply extending functionality to existing code (e.g. FireFox plugin, WordPress plugin, Drupal module, Angular module, etc.). However, it seems like they are 2 different things in Drupal 8.

As I understand it, D8 plugins (the incorporation of CTools plugins in D8?) are reusable components like a form widget, while modules are extensions to Drupal 8 core code that can implement or create plugins. Is this correct?

Yes, you're right: Modules are still modules, the equivalent of what WordPress calls plugins. Each module can implement one or more plugins.

For example, the Voting API module has a plugin for each of the methods to show the result: Average, Sum and Count.

Plugins also needs a plugin manager, which is the responsible for actually calling the plugins.

You can see this on:

https://github.com/pedrorocha-net/votingapi/blob/8.x-1.x/src/Plugin/VoteResultFunction/Average.php
https://github.com/pedrorocha-net/votingapi/blob/8.x-1.x/src/VoteResultFunctionManager.php


Current password required to change password for self-registered users. No password was ever set I cannot figure out how to validate users through email using drupal.

at admin/config/people/accounts I have Require e-mail verification when a visitor creates an account checked, and under Who can register account I have it set to Visitors.

When I go to create a new account, it says a success message and no email is sent. No errors, nothing in the logs. If I request a password, it sends that email no problem. I can also change my password without entering a current password when using the request password link. So the site is sending emails, just not validation/registration emails.

I have to use rules in order to send the registration emails because the emails are not sending and we have a deadline. I got rules to successfully send the emails but the one time validation link does not exist in the email.

I had to then download Login One Time in order to show a validation link in the email.

After clicking the email and successfully logging in as that newly created user, I am unable to change my password because the form is asking for a current password, which is not available for the user to even populate at the registration step.

I have tried using logintoboggan and tried generating temp passwords to send to the user but the token provided by login-toboggan shows up as nothing when the email is sent.

I am seriously confused as to why this is such a difficult process to achieve. Is email validation this difficult out of the box with drupal?

Does anyone know why drupal is prompting me for the current password for newly created users?

Is there something I am missing as to why only registration/validation emails won't fire from my website, but other system emails do?

I have solved my issue by re-installing the login one time module and clicking the Ignore the current password field checkbox.

This hides the Current password field for the one time login link, and everytime after requires the user to provide a Current password if they want to change their email, password ect.

The problem is that this website will still ask for a current password for validation links if I uninstall the Login-one-time module, which makes no sense to me.


Create custom page in theme templates i am currently working on a custom theme and i would like to know if it is possible to create a custom page which would include some php and would be visible after enabling the theme? or is it maybe better to create pages using drupal front end way and then packing it in installation profile ?

Yes, Drupal supports custom pages.
But with different naming conventions
Follow this link of drupal.org https://drupal.org/node/1089656


add a link next to the search button? I like to add a "help tips" link next to the search button. I made some changes on the "search-block-form.tpl.php" (see below) but it does not show on the search result page.

Some documentation on the web suggests using function hook_form_alter to make the changes. Thank you in advance

  <?php if (empty($variables['form']['#block']->subject)): ?>

<?php print t('Search form'); ?>

  <?php endif; ?>
  <?php print $search_form; ?>
  help_tips

function MODULENAME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_block_form') {
    $form['help_link'] = array(
      '#markup' => 'help_tips',
    );
  }
}

That should do the work, but I am not sure if the id 'search_block_form' the right one is.
If you don't have any custom module, just place this code into your current template's template.php, replace MODULENAME with templatename, save and clear cache.


Theming node add form I have a content type 'project' and I want to theme the node add form for this content type, I tried to create a page--node--add-project.tpl.php but I don't have the list of form element to render in this file.
devel_themer don't print the variables list in the node add page
thanks

On the page level forms are rendered and so you cannot get its elements. You will need to implement a hook_theme function in template.php file where you define the path of the template file and also implement preprocess function if required.

You can see a detailed explaination here .. Theming Forms with Template file


My custom Save button does not save the new form values I added a custom button to my form which I want to call a function which grabs some values from that form, email them out to whomever, and then save the form. I have successfully emailing the value, but I cannot get the form to save.

function my_mod_form_node_form_alter(&$form, &$form_state, $form_id) {

    $type = $form['type']['#value'];
    if($type !== 'support_ticket')
        return;

    $form['actions']['submit2'] = array(
        '#type' => 'submit',
        '#value' => t('Accept And Close'),
        '#submit'=>array('my_mod_email_and_close')
    );
    return $form;
}

function my_mod_email_and_close(&$form, &$form_state) does not contain any logic to actually save the form values. It only checks the form for some values and emails those values out.

I need to save the form however, how do I also get this custom button to submit and save the form. I tried adding these lines to the bottom of my_mod_email_and_close()

$form_id = $form['form_id']['#value'];
drupal_form_submit($form_id, $form_state);

but it doesn't actually save. I get 2 of the same errrors however: Trying to get property of non-object in _support_assigned() from a different module so I am not sure whats going on.

Perhaps I am using the wrong hook?

Add the original form's submit function to your #submit array in addition to your custom function.

https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7#submit_property


View of related nodes by continent or country without taxonomy terms I have a content type called Packages.Each content has two fields:
Title and Continent(this field was created using the module Countries).

I have created five contents of content type Package:
Title        Continent

 London      Europe

 Madrid      Europe

 Paris       Europe

 Brussels    Europe

 Tokyo       Asia

I want to make a block of related nodes by the continent.

For example: if I am viewing the node of London in the block of related nodes show the cities on the same continent in this case: Paris, Madrid and Brussels.

I want to do this without terms of taxonomy, otherwise I'll have to create a vocabulary with more than one hundred fifty terms.

There are like mostly in Drupal several possible solutions. One would be to filter Views views for each view and therefore you can filter any field you want the same way, like you do with terms (check the terms view pages as an example, how to build such filtered views).

Another option would be to create node relations like provided with the Relation module or the Entity reference module. The advantage of the relation module is, that the relations are own custom entities which are fieldable again, like term view pages. Thanks to @diqidoq for pointing me to this solution.


How to add a filepath to a file uploaded in form API Problem

I have a custom form which creates a node. It's based off this link and uses the entity metadata wrapper to create the node.

The node created has an image field and you can use the form to upload an image on creation.

How can I set an upload directory for the image that's uploaded? At the moment they just default to my public folder.

Set-Up

There's more to this form, but these are the important parts. I declare a file field.

function postajob_form($form, &$form_state){
   ....
   $form['file'] = array(
     '#type' => 'file',
     '#title' => t('Thumbnail/Advert Picture.'),
     '#size' => 5,
   );
 }

I then submit that file using an entity metadata wrapper.

function postajob_form_submit($form, &$form_state) {

  global $user;

  $values = array(
    'type' => 'job_advert',
    'uid' => $user->uid,
    'status' => 1,
    'comment' => 1,
    'promote' => 0,
  );
  $entity = entity_create('node', $values);

  $ewrapper = entity_metadata_wrapper('node', $entity);

  if (array_key_exists('storage', $form_state)) {
      //if is required incase no image is uploaded.
      $ewrapper->field_req_thumbnail_school->file = $form_state['storage']['file'];
      //field is unset now it's no longer needed.
      unset($form_state['storage']['file']);
   }
}

I tried changing the URI inside the form_state, however this had no effect.

 if (array_key_exists('storage', $form_state)) {
      //altering the uri where the files are uploaded too
      $imagefilename = $form_state['storage']['file']->filename;
      $form_state['storage']['file']->uri = "public://user-upload/job-advert/$imagefilename";
      //save the file
      $ewrapper->field_req_thumbnail_school->file = $form_state['storage']['file'];

   }

But this didn't effect anything.

Whenever I use a file field in the submit handler I use:

$validators = array('file_validate_extensions' => array('csv'));
if ($file = file_save_upload('upload', $validators)) {

You can add an optional argument to file_save_upload after $validators which is $destination, take a look at https://api.drupal.org/api/drupal/includes!file.inc/function/file_save_upload/7 for more details


D8. How can check is a formatter in use? I contribute a module that provides additional formatters for the core image and link fields.

To protect the module from uninstall, I need a possibility to check if a providet formatter used on a image or link field.

To do this, I use the hook_system_info_alter() with

$info['required'] = TRUE;
$info['explanation'] = t('Field formatter(s) in use');

Someone has an idea?

Solved.

See the function dsbox_system_info_alter() of the Drupal Swipebox module to get detailed informations of the solution.
Or, here is the link to the code of the module file: dsbox.module


Wrong status after updating from 7.64 to 7.66 I recently manually updated my localhost drupal site from 7.64 to 7.66.  I ran update.php without errors.  When the process finished, I cleared all cache and checked the status.  It still reported 7.64.  I then re-ran the manual update and got the same results.  When I look at system.info, I see:

; Information added by Drupal.org packaging script on 2019-04-17
version = "7.66"
project = "drupal"
datestamp = "1555533576"

I've noticed other posts (here and here) on the Drupal site that report the same type of symptoms, but, no one has reported a valid solution to resolve this discrepancy.  Does anyone know how to get things back in sync?

UPDATE: As part of this process, I successfully updated two other sites I maintain to 7.66.  The glaring difference that I need explained is after running update.php on localhost, I do not see "Pending Update" as I did on the other two sites.

Try to delete the includes folder and add new includes folder from 7.66 version, bootstrap.inc defines the drupal version.


Tabs redirect to different page I'm building a job directory.

This will allow users to register, create Companies and Jobs associated with those companies.

A Job can be from one of the following types: Full-time, Part-time, Freelance and Internship.

The current Jobs View can be seen here:

It was created using Views, just like in this video and looks like this on the back:

My current problem is anytime a tab is clicked, the user goes to a completely different page, requiring the page to load again.
I don't want the user to go to a different page anytime they select a type of job...

Unsure how to do this using Drupal but I were to do this manually, would use Ajax and PHP so that the data could be retrieved from the DB and the page wouldn't require to load again.

Drupal Legoland builds tabs using Field Group Module. This looked like a good technique and easy to implement, but for my case doesn't really work as I don't have a specific field in the content type Jobs just with the Full-time Jobs Data and not sure how to create it.

There's a module called Quick Tabs, which allows to create Ajax loaded tabs. We need to flush all caches after creating the new tab in order to be seen as a normal block. It fixed the problem.


Notification and Messaging module for sending mails I have installed send methods as html mail and i have set notification module with subscriptions to content type.

I am not receiving an email when notification actions get created.

have anyone pass through such scenario? Please let me know.

Html mail is not reliable, buggy and some features are not supported. I've got rid of it. Mime mail is much better. Mail system and SMTP module must also be installed.

In the settings SMTP Authentication Support SMTP server, SMTP port, User name, E-mail from address, E-mail from name must be filled, Allow to send e-mails formatted as Html could be ticked and password of your SMTP server must also be entered.

In the module Mail system in the submenu New class MimeMail_SmtpMailSystem must be constructed and filled in Site-wide default MailSystemInterface class and Mime Mail module class. In the settings Mime mail E-mail format Full HTML can be selected and Sender e-mail address need to be filled.

This configuration must work.


How to get node ID from drupal 7 when i know title (title shouldnt be duplicated) Drupal My module is creating node with title "123title", after this i want to create next node, with entity reference field whose have to contain id of node with title "123tile" whose i created before. –

As suggested by Mołot you can do this with EntityFieldQuery.

// Initialize EntityFieldQuery.
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');

$query->propertyCondition('title', "My title", "=");

// Execute query and collect results
$result = $query->execute();

$nids = array();
if (isset($result['node'])) {
  $nids = array_keys($result['node']);
}

In the example $nids will be an array with all node ids that have the title "My title". Entity field query really helps you when the query gets more complicated. You don't have to do joins for example yourself but can instead do something like $query->fieldCondition('field_news_types', 'value', 'spotlight', '=') which using db_select would require joins on tables.


Failed to connect to your database server I have uploaded my drupal commerce files. I get the message that my credential are wrong.  I am just not sure whaht info they want for the

In order for Drupal to work, and to continue with the installation process, you must resolve all issues reported below. For more help with configuring your database server, see the installation handbook. If you are unsure what any of this means you should probably contact your hosting provider.

  Failed to connect to your database server. The server reports the following message: SQLSTATE[28000] [1045] Access denied for user 'admin'@'localhost' (using password: YES).

  Is the database server running?
  Does the database exist, and have you entered the correct database name?
  Have you entered the correct username and password?
  Have you entered the correct database hostname?

I though I knew all of this information.  I am running on my web host using admin as username.  Any help would be greatly appreciated.

Change the settings in your settings.php file.
For remote server you should change this like below;

$databases = array (
  'default' => array(
    'default' => array (
      'database' => 'name of database uploaded on remote server',
      'username' => 'root',
      'password' => 'root',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

'username' and 'password' are for the remote server
'host' is the hostname of the hosting server


Drill into computed field entity data I am using Drupal 7. I installed the computed field module and have a computed field in a content type. I need to be able to access the actual name of a node reference field that is in the same content type so i can then work with the data in the computed field. Currently I can only get the number of the node reference field using this in the computed code (php) field:

    $entity_field[0]['value'] = array_pop(field_get_items($entity_type, $entity, 'field_charity_reference'));

I need to be able to access a 'drill' into the the node reference to get the rendered title, which is a human readable name.

When using views and custom php I can use dpm($data); to explore the data and use this to work out I can access the rendered title by using:

    $data->field_field_charity_reference[0]['rendered']['#title']

Since originally posting this question I have found i can use dpm(field_get_items($entity_type, $entity, 'field_charity_reference')); in the 'Display Code (PHP)' input in the computed field to give a devel printout of the field I wish to access data from.

I would like to know how to drill into the results returned by field_get_items($entity_type, $entity, 'field_charity_reference') in order to output the name of the node reference field. Thanks

Procedurally:

if ($field_items = field_get_items('node', $node, 'field_charity_reference')) {
  $referenced_node = node_load($field_items[0]['target_id']);
  $title = $referenced_node->title;
}

Or OO'ly with the Entity API module:

$node_wrapper = entity_metadata_wrapper('node', $node);
$title = $node_wrapper->field_charity_reference->value()->title;

If you go the OO route this post will probably come in handy


Complicated content/node access scenario, input wanted the requirements are the following:

In the site we'll have groups of users, that can access content posted in their group, much like Organic Groups does.

Apart from that though, the author of each node, must have the ability to override that functionality and "invite" specific users to view the node, even if it's in a group bypassing the group's settings. So if the group contained the users U1, U2, and U2, but the author invited U2,U4 and U5, U1 and U3 wouldn't be able to access the node.

On top of that, the author must have the ability to add specific users as "facilitators" to that node which grants them "Edit" rights on the node and the ability to invite more people to view the node as described above.

By using organic groups AND node access user reference, I've been able to accomplish the grouping and either the "participants" feature OR the "facilitators" feature, since as it seems, node access user reference cannot support 2 grant types on the same node.

Now, the general advice is "you don't want to use more than one node access module on your site." (http://drupal.org/node/270000). So the idea of adding yet another one, to accomplish the missing feature sounds wrong. Also creating a custom module to encapsulate all of this functionality seems like a lot of work.

So, since I am facing a sort of a blocker in my project analysis I'd like some input on how you guys would go on about tackling such an issue. Thanks in advance.

EDIT: Seems that even the synergy of Organic Groups and node access user reference is not working as intended. Just works in public groups' content since there is no 'group_access_authenticated' record in the 'node_access' table and node access user reference handles all the grants. In private groups where for example one user (U10) can be a member of the group but NOT in the list of the node's "participants", since he has the 'group_access_authenticated' grant, he is able to view the node in question thus breaking the functionality.

Well, just for anyone who stumbles upon this in the future, DO write your own content access module. Once you grasp the logic it's quite simple and it will solve your problems while allowing you to keep the logic of other modules involved in your project. Simply copy their code/logic and set it along with the rest of your requirements with higher priority.


For a customer database table, do I have other options, beside creating a custom module? I'm upgrading my site to Drupal 8.

Currently, I have a custom module with a custom database table and I query that to provide historical data that is in the table. The data is really purely tabular and has thousands upon thousands of records.

If there were fewer pieces of data, I would just create a custom content type.  However, I'm not sure that creating thousands upon thousands of nodes would make sense.

The database table includes the following fields.

Person
Product Sold
Revenue Generated
Month Sold

Let's say I generate a few records per month.

How should I handle this? Should I make another custom module to output the data?

Since you already have a module, I would rather not convert all the data in nodes.
I would not use nodes to store arbitrary data, since that is not the purpose of nodes, especially when I don't need to show all the data I store, or when I show a table with a pager only to the users with a specific permission. Nodes are by default readable by every registered user; making them visible only to users with a specific permission is not hard, but requires extra modules, and changing configuration.

With Drupal 8, there are few alternatives, but a custom database table is the easier solution, especially if you don't want to write migration code.

If the data is linked to user accounts (which means, that person field is a username or the user ID), you could use the user.data service.
That service, though, loads all the data for the specified user ID, module, and key. You cannot tell to the service to load just the first, or the last, N records, for the fact the service doesn't have a concept of record. You could assign the data to different keys (for example, a key for June, one for July, etc), but that means making the code more complex.
If the data is only pertinent to a site, and you don't want to export it to other sites, you could use the state service, but this still load all the data associated to a key (not module, user ID, and key) at once. The workaround is the same for the user.data module, with the same cons.
If the data needs to be exportable to different sites, you could use the configuration API, but with much data, it's probable you would get some performance issues. (Yet, creating different, but related, records is not that immediate.)
You could create a configuration entity for your data. In Drupal 8, configurations entities are used for user roles, content types, image styles, and much more.

The first three methods I described would not allow you to easily search for data as a SQL query would. The last one would allows you to get data using an API similar to the one used to query data from a database table.

If I wanted to quickly convert the code to Drupal 8, I would rather use the database approach I was using for Drupal 7. In that way, the data stored in the custom database table won't need any conversion when updating the site to Drupal 8, and you could easily control the users who access the data using a custom permission (in the same way you would do in Drupal 7).

If I wanted to make the code more "Drupal 8 code," I would use configuration entities. It requires to write code to migrate the data, but it's worth the effort.


Manually deleting images (from db and file_usage table) I was given 'temporary' images for a number of bio pages, and now have better quality images to replace them with.  Removing or replacing the old images in the Admin UI is failing (without giving me any error messages or indications of anything wrong: the old image is just there no matter what I do).  If I connect to the server by SSH and rm CEO.jpeg from bash, then the database is out of sync with the file system, and when I upload the new version of CEO.jpeg, I get an error because that is already in the database.

If I just edit the file_usage table and set count to 0, will that have any nasty side effects?  (I will also, of course, manually delete the file from the file system.)   Do I have to manually track down each node and edit it too?  Or can I just go to those nodes in the Admin UI after manual removal and add the new versions of the images?

(I've checked answers to this question and this question but the situation in those is very different.)

This is probably more of a comment but the code won't fit in...there should be no reason for the UI to fail on the file delete, unless the web server daemon doesn't have write permission to the files folder. That would be the first thing I'd check, then try again.

If that fails, you might want to give it a go manually:

$nids = db_query("SELECT nid FROM {node} WHERE type = 'the_type'")->fetchCol();

foreach (node_load_multiple($nids) as $node) {
  $node->field_name[LANGUAGE_NONE] = array();
  node_save($node);
}

That will take care of the whole lot (removing the data from file_managed, file_usage, and deleting the file from the disk if it exists and is writeable).


DRUPAL 7: insert images via URL instead of via "file-upload" My boss asked me to edit an existing page (in which is already possible insert text and images) in order to be able to insert images not only by uploading them from local pc but also via Remote URL.

My version is 7.31 and is already installed "File Field Sources" module that SHOULD be the most useful to achieve desired behaviour.

My questions are:

After entered in Edit Mode of a specific page, how to verify
which module is actually used to manage images uploads?
In case that it is already "File Field Sources", how to configure it to
be able to put remote URL?

Thanks

I guess you are having problem to use the module File Field Sources.

Use below steps

Download and install the module
Edit any image field, for ex. Article content type is having image field. Let's use this module over there.
Go to URL : admin/structure/types/manage/article/fields
Edit the field field_image
Check the option to use remote URL there. See screenshot.
Create article content and see there option to use remote URL in image field. See attachment.


Issues sending HTML email with Simplenews module I am able to send plaintext emails with the Simplenews module.
I have installed the Mimemail module; I configured the mail system to use Mime Mail Mailer in DEFAULT MAIL SYSTEM. After sending the emails to queue, when I run the CRON job, Drupal displays an error message:

  Unable to send email. Contact the site administrator if the problem persists.

Has anyone used Simplenews to send HTML emails in Drupal 8.1.1? If so, can you please advise how to do this?

Check out the following modules, in their configuration it's easy to set email system and html format:

Mail System.
SMTP Authentication Support.

Select mime mail in the config of mail system. Also make sure that content text format and newsletter settings is full html and it should do it.


How to check if view result is empty Twig To check the field I use the following code:

{% if content.field_name|render is empty %}

How to check on node.twig if {{ my_cool_view }} result is empty? Is this generally possible in Drupal 8? Thank you for help.

You can use twig_tweak Module, and use drupal_view_result extension like:

{% if drupal_view_result('who_s_new', 'block_1') is empty %}

For more info look at this module Cheat sheet


Entity Reference of multiple types I would like build out page content using entity references. The problem is I would like to reference multiple types of entities (nodes and terms) plus content that is not an entity (views.)

I've explored this and what I have now is a field for both Node Reference and Term Reference and another with a View Reference which is not a very user-centric. Is there a more succinct way to achieve this?

While relation can handle multiple entity types in a single relation type it can't reference Views. It's a challenging problem for two reasons: the view_id is a string unlike say nid so a database schema made to refer numeric IDs won't be able to copy with views. Also, views is not stored in the database necessarily so the utility of such reference is limited.

It should be possible to maintain an entity in the database that has a numeric ID and all it contains is the Views ID. Your only problem becomes when someone changes the machine of a view that is maintained in code -- how do you plan to be notified of such a thing when it happens outside of Drupal?


Memory warning message I keep getting this error message:

  Warning: require_once(): Unable to allocate memory for pool. in Database::loadDriverFile() (line 1742 of /home/site/public_html/includes/database/database.inc).

I am not sure what the problem might be. It started when I installed Varnish 3.0; I couldn't get it to work, so I reverted back to my previous configuration with only APC. Now, I keep getting the message, and it is also visible to anonymous users. I have disabled the system help block from all themes, and turned off error reporting, but it still appears.

I also have mod-pagespeed enabled.

Seems to definitely be an APC issue, there's a post about it on StackOverflow which links through to a bug report on PHP.net for precisely this issue.


Sort handler for pseudo field in views I have made a custom views field handler by the following instruction:

http://www.interactivejunky.com/blog/database-independent-views-3-custom-field-handlers

The problem is that, I cannot sort the values of the created pseudo field in view. I know the reason is that my pseudo field basically doesn't exist in query of the corresponding view, and cannot exist there as it doesn't exist in any tables and it's just a computed field for that view.

Any ideas about making this field sortable?

you should pass 'click sortable' => TRUE parameter together with 'handler':

...
  'field' => array(
    'handler' => 'views_handler_my_custom_field',
    'click sortable' => TRUE,
  ),
...

Then you can override click_sort($order) in your views_handler_my_custom_field class, e.g. you can explicitly override the 'orderby' array of query object:

function click_sort($order) {
  ...
  $this->query->orderby[] = array(
    'field' => '...', // here may be a field, or some SQL clause e.g. FIELD(str, str1, ...)
    'direction' => strtoupper($order),
  ...
);

See also click_sort($order) in views_handler_field class.

HTH,
Alexander


How to replace large, original images used for image caching? All of the content types on my site allow users to upload up to 10 images. Each file is around 2 to 6 mb in original size.

I don't want to add another layer of complexity to their posting experience by enforcing that they use photoshop or some other software to 'format for web.' before uploading (which would be the case if I set the max file size to, 512k, for example).

Instead, how can I do like other services where you can upload whatever size and then the backend takes care of formatting them to a much smaller size for storage as well as the be the original that image caching uses for its work?

I see two ways of handling it:
write a module that understands when the file is saved and use PHP to reformat via its image functions, and then save that new file on the file system as well as be the source of any related image information needed in the database.

or, if the image data in the database is not dependent on the uploaded file size, etc, then why not just write an independed script to loop through all the images and reformat their sizes? Doesn't even have to be a module really.

Thoughts on the best way to do that?

hook the image while finishing the upload process, then compress the size is a good Drupal approach much better than another batch job since the project can be managed in a good scope.

If it is a once-off task, script batch job is fast and efficiency but regarding the daily normal usage, a module is more preferable.

There is a module ImageAPI Optimize (or Image Optimize)

BTW, the theory could be:

Something like the following may be what you need:

function MYMODULE_node_insert($node) {

// See if a file has been added
  if ($file_items = field_get_items('node', $node, 'field_file')) {
    // Get the first file item
    $file_item = array_shift($file_items);

// Load the file object from the cache/database
$file = file_load($file_item['fid']);

// The path to the file is in $file->uri
do_something_with($file->uri);

}
}

REF: https://api.drupal.org/api/drupal/includes%21file.inc/group/file/7


Problem with temporary URL in new host I'm migrating my Drupal website to a new host.

Here's what I've done:

1 - Create an DB.mysql.gz using backup and migrate module (in old host)

2 - Create a new database and user in new host and restore this DB.mysql (step 1) directly using mysql -u USER -pPASS MYBD < /home/DIR/DB.mysql

3 - Install in new host the drupal using QuickInstall (installed v7.32)

4 - Transfer all data by directory www (old host) to a new host (hostgator - public_html) overhidding all files of Drupal 7.32 (installed by QuickInstall) to my current install v7.34.

5 - Change settings.php database content

I need check if all site is running OK before change DNS, for it, i need login using www.URL_TEMP/~MYUSERHOST/user/login, but this URL return 404 - Page not found.

Home page is load disfigured and browser log say 404 not found in css/js files, eg: www.URL_TEMP/~MYUSERHOST/sites/default/files/css/css_xE-rWrJf-fncB6ztZfd2huxqgxu4WO-qwma6Xer30m4.css and others. This file exists in public_html/sites/default/files...

I try change hosts file in my local machine (http://support.hostgator.com/articles/general-help/technical/how-do-i-change-my-hosts-file) but not solved.

This problem does not allow that I access with admin and change file temporary path in /admin/config/media/file-system, clean cache and test website.

Am I missing something, or do something wrong?

Ps: In old host the website is running OK!

If you are sure that settings.php and ftp files are all set right, my guess is you miss some package in php or in appache. Please compare php and appache settings between old host and new host. For example, rewrite_module in apache


How can i put popup box captcha on managed file remove button? Can We write function for remove button as I want to display Captcha in popup on Remove button for security reason.

same type of some function like used in below post.

How can I automatically upload images on file selection rather than pressing the upload button?

I have solved it. I have hide remove button access. and then put my own remove button, and open dialog box in form to display popup box.

please see code.

drupal_add_library('system', 'ui.dialog');
drupal_add_js('jQuery(document).ready(function(){
    jQuery("#clicky").live("click", function(){
        jQuery("#dialog").dialog({ modal: true ,height: 250,width: 350, buttons: [
            {
            text: "Cancel",
            click: function() {
                jQuery(this).dialog("close");
            }},
            {
                text: "Submit",
                click: function() {
                     jQuery("#dialog-form").submit();
            }}
        ]});});});', 'inline');


How can I link an image of a jCarousel to a certain link? I would like to link the different images of my jCarousel to different specific links depending on the actual image.

I assume you're using views and jCarousel and Drupal 7.

On same content type that you have your image fields, add a new link field. Add this link field to your view but check the Exclude from display checkbox, set the Formatter to URL, as plain text and make sure the link field is before of your image field in order.

Edit your image field settings in the view and, under Rewrite Results, check Output this field as link. Scroll down to the replacement patterns and copy the pattern that references your link field. Put this pattern in the Link Path text box.


How to print $item separately, with different content, in views-view-grid? I am trying to create an image gallery, using Views 3 for Drupal 7. A brief overview of what I did:
- Create custom content type for photo gallery (title and image fields
- Create View for the gallery page
    - Set format to "Grid", and show to "Fields"
    - Added field: "Content: Photo" (preview image style)
    - Added field: "Content: Photo" (thumbnail image style)

As you can see, I have two fields with the same field so that I can have two differently sizes of each image. What I need to do, is print these images in two different places in my template.

This is my views-view-grid--gallery.tpl.php:

  <?php foreach ($rows as $row_number => $columns): ?>

      <?php foreach ($columns as $column_number => $item): ?>

          <?php print $item; ?>

      <?php endforeach; ?>

  <?php endforeach; ?>

I want to be able to do something like this:

    <?php // foreach ?>

        <?php // print preview image ?>

  <?php // foreach ?>
    <?php // print thumbnail image ?>

I have tried a multitude of things, but I can only make $item print either one of the images, or both of the images. Since only the final, HTML-formatted image is returned, I can't figure out how it is possible to split it up.

Thanks much in advance!

Anyone still looking for this, that's how I did it:

First I've created a simple view with a block to show just the fields that I needed on top (let's call it view-top), striped all default elements and classes to make it clean and easier to work (not really necessary to clean it). In OP's case would be the miniature for the gallery.

Then I've made my main view with the fields that I wanted on bottom (let's call it view-bottom). In OP's case would be the full sized images. In the header of this view I've added a "Global: Visualization area" and called my view-top.

This way I had two views, one embedded in the other, and with a bit of Drupal's behaviors I've made the click logic.


How can I access the virtual machine filesystem from within Windows? I've recently tried to get used with Oracle VirtualBox Manager and the QuickStart 1.0 VM machine: http://drupal.org/project/quickstart. I've installed it on

Everything looks fine and great but the only big issue is I cannot access the files from outside (Windows 7). I need to have a way to control the Drupal installs (backup them, commit/checkout with the linux server etc). How do I?

I heard there is a solution to install samba but this only works if you have a real linux installation on your computer.

Create shared folders from Virtual Box Manager. For each drive you will have to create a shared folder. These shared folder will appear in guest OS as network file-systems.

As Ubuntu (Linux) is underlying in QuickStart.

Mounting temporarily need to fire this command from terminal:

sudo mount.vboxsf [share_name] [directory - mount point e.g. /mnt/share/]

OR

sudo mount -t vboxsf [share_name] [directory - mount point e.g. /mnt/share/]

Mounting permanently using fstab (/etc/fstab)
Make sure to install samba first (in ubuntu it should be already installed or do it sudo apt-get install samba, it needs internet connection)

Now edit your fstab file and add an entry in the last

\\vboxsvr\[share_name] [directory - mount point e.g. /mnt/share/] vboxsf rw,gid=100,uid=1000,auto 0 0


Getting other fields during a Drupal Services GET I made the following request via GET: api/node?fields=nid,title,field_media

But I'm getting the errror: Invalid query provided, double check that the fields and parameters you defined are correct and exist. SQLSTATE[42S22]: Column not found: 1054 Unknown column 't.field_media' in 'field list'

I'm assuming its only looking at the node table, but how do you make it grab all the fields of this content type?

I couldn't easily find the documentation of these endpoints and how to call them properly. How is everyone figuring this out?

Use Views Datasource or Views data export and create a page view that contains your fields in JSON, or XML, or whatever you want to use. Then simply do a GET to your view's URL.


Custom field storage, Per field How can I alter a field's storage property? What's the correct hook to use to alter $field['storage'] = 'my_custom_storage';?

I am currently using the global db variable field_storage_default but I find that to be gross. I don't want to do it for all fields.

I thought this can be done using hook_field_create_field, but it's not possible. Using that hook and then calling field_update_field will not work because the update does not allow this:

  if ($field['storage']['type'] != $prior_field['storage']['type']) {
    throw new FieldException("Cannot change an existing field's storage type.");
  }

Drupal doesn't want you to screw up existing data. So being careful and knowing what you are doing, the existing fields could be modified in the field_config table in the database. Reimplementing field_update_field you could do:

/**
* Implements hook_field_create_field().
*/
function mymodule_field_create_field($field) {
  if ($field['type'] == 'fieldtypetostore') {
    $field['storage'] = array(
        'type' => 'mymodule_custom_storage',
        'settings' => array(),
        'module' => 'mymodule',
        'active' => 1,
    );

    // Build record to update.
    $record = array(
      'id' => $field['id'],
      'storage_type' => $field['storage']['type'],
      'storage_module' => $field['storage']['module'],
      'storage_active' => $field['storage']['active'],
    );

    // Update the field storage.
    $primary_key = array('id');
    drupal_write_record('field_config', $record, $primary_key);
  }
}

/**
* Implements hook_field_update_field().
*/
function mymodule_field_update_field($field) {
  mymodule_field_create_field($field);
}

The best way to do this is to create the fields in your module that you need to use and at that time, set the storage for the field. It's cleaner than changing existing fields.


Use migrate to populate entity_reference with nid I am migrating a D6 site to D8. The D6 site used the "Node Relativity" module, which has been broken for a while. It was used to establish a link between two content types, which I will call meeting and recording.

Now I am trying to use the migrate module (and friends like migrate_plus) to establish an entity reference to recording in the meeting content type. Here is what I have done:

In the D8 site, specified the field structure for the two content types. In the meeting content type there is an entity reference for the recording called field_recording_link.
Exported the configuration into custom modules. I can now create a database from scratch and it creates the content types.
Connected my D6 database to import content. Textfields from the meeting content type do get imported.
Written a custom source module with a prepareRow() method that exposes the NID of the recording nodes (called recording_nid). I can see this NID in the migration.

In the migrate_plus.migration.upgrade_d6_node_meeting.yml file, added the following stanza in the process section:

field_recording_link: recording_nid

but this does not populate the field. I have also tried:

'field_recording_link/target_id': recording_nid

but that does not work either. I feel as if this ought to be straightforward, but I am pretty stuck.

Do I need to make a process plugin? If so what should it do? Use PHP to create an entity reference and populate it?
Do I need to call an existing process plugin? If so which one?
Do I have to write a separate .yml file just for this field? If so what would it look like? I have been looking around for examples but have not had much luck.

I would appreciate any advice you have, as well as links to examples of this.

It was straightforward. I had a typo in my YML file. The correct answer was:

field_recording_link/target_id: recording_nid

The important thing is to set the target_id field, since that is what the entity reference really is.


Theming the field.tpl.php - accessing variables from a field collection I've got a field template which is rendering a field collection field using the standard field.tpl.php file:

  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item): ?>
      <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><?php print render($item); ?>

     <?php endforeach; ?>

I want to output the a CSS class inside the div in the loop with some text which comes from a colour field inside the $item variable.

EG. I would like to access the variable such as:
render($item['field_colour']);
in the loop, but this obviously doesn't work.

What's the best practice for doing this?

In standard field.tpl files you can access your field collection items using this code:

foreach ($items as $k) {
  foreach ($k['entity']['field_collection_item'] as $id => $field_collection) {
    $field_collection_item = field_collection_item_load($id);
    $field_wrapper = entity_metadata_wrapper('field_collection_item', $field_collection_item);
    $field_colour = $field_wrapper->field_colour->value();
  }
}

I don't know if it is a best practice to do that, but this is my way.


Fatal memory Error at the bottom of the page but not WSD. What this means? I occasionally get the following error showing at the bottom of some pages when I'm logged in as Admin. I have seen this error before when the server didn't have enough php memory. But then always the page was WSD.

However I don't get WSD with the php memory error message I'm getting now.
It's just showing at the bottom of the page and the page itself works as usual.
What is the difference between this one and the one we get on WSD?
Can I just ignore it?

Fatal error: Out of memory (allocated 175112192) (tried to allocate 7015932 bytes) in  /public_html/includes/database.inc on line 225

You can change the amount of memory available in your php.ini file (i think) - making more memory available to your drupal installation and thereby doing away with this error

see https://drupal.org/node/76156
and https://drupal.org/node/1915140

for further details


How to link to a taxonomy term of a view? I would like to add a link in my template to the view page "taxonomy term", for a term of taxonomy to partiluer.

For example, in my taxonomy "thing" I have the term "truc", and I would like the link redirect to the page of the term taxonomy "truc".

I tried {{ 'Name'|t }} but of course it does not work because I do not know where to put the term in question (in example the term "truc").

Do you know how to do it ?

Try this one

 term_id}) }}">{{ 'Name'|t }}

Where term_id is your taxonomy term id.


Drupal base_url incorrectly writing extra subdomain We have a basic drupal multi-site installation on a RHEL (RedHat) server.
For some reason when viewing the site, the asset URLs (CSS/JS) all point to the wrong subdomain.

Our site URL: http://drupal.sandbox.domain.com the drupal index page loads up with asset URLs being written as: http://drupal.sandbox.sandbox.domain.com.
Why would drupal add in the extra .sandbox subdomain?

The .htaccess file has been left as the default, also attempted to set RewriteBase to /, but there was no change. The sites/default/settings.php file has the base_url set to: $base_url = 'http://drupal.sandbox.domain.com' but Drupal is overwriting this somewhere. Setting the $base_url to the IP of the server causes the assets to be linked to the correct location (using the IP rather than the actual domain), but this is not ideal.

I've tested using the same configuration on an Ubuntu Server without any problems. I'm not sure exactly how to track down the cause of this problem.

How would I go about debugging this and discovering what is causing the overwritten URLs?

This is not a Drupal-specific problem. This can easily be checked by creating a standalone PHP page and using the same code to test. Being that the variable is overwritten immediately after it is set shows that PHP/Apache is the one doing the overwriting.

It is possible for Apache to overwrite input and output. See: What would cause PHP variables to be rewritten by the server?