How to alter node load system to make it possible for only one field is attached to a node? I have created a special content type using the build-in field system, which allows users to create multiple instances of the body field. In some circumstances the body field could be as large as 20M.

I would like to implement a hook that when a user visits a certain URL like node/1/body/0, then when node_load is called, only the body field with delta == 0 is loaded into $node object, so it won't affect much for the performance.

Is it possible? Thanks in advance!

After a long research, found a solution :-)

You can do it using views module and views_field module. Follow below steps to achieve the solution without doing a full node load or full field items load so that you can achieve the performance you are looking for !

Install views module
Install views_field module
Go to the body field settings page and enable the base table by checking " Expose as base table" checkbox.
Create a new view with base table as "Field Body" while creating a new view in show dropdown.
Remove fields in the field list
Set the path as node/%/body/%
Add field "Field Tables: Body > value"
Add contextual filter "Field tables: field_body => Entity id" and set default value as "Raw Value from URL" and Path component as "2"
Add one more contextual filter as "Content: Body:delta" and set default value as "Raw Value from URL" and Path component as "4"

That's it !! It worked for me !!

By implementing above solution, views module directly queries body table with delta and entity id as filters and get's the body value which you will be looking for without loading full node or field body items !!


how to print db_select result using watchdog? I'm trying to debug below code:

$perishables = db_select('userpoints_txn', 'up_txn')
    ->fields('up_txn', array('txn_id', 'uid', 'points', 'remainder', 'time_stamp', 'tid', 'operation', 'description'))
    ->condition('status', 0, '=')
    ->condition('expired', 0, '=')
    ->condition('expirydate', 0, '!=')
    ->condition('expirydate', REQUEST_TIME, '<')
    ->execute();
 watchdog('userpoints', 'perishables->remainder  %perrr', array('%perrr' =>$perishables), WATCHDOG_DEBUG);

Can anyone help me how to get  $perishables in the report log files?

execute(): - this will not return query results to you. All it will return is database connection object and query string. See the screen shot.

In order to get query results, you need to call any of the retrieve function. For example

fetch();        // Use the default fetch mode.

fetchObject();  // Fetch as a stdClass object.

fetchAssoc();   // Fetch as an associative array.
Debugging queries:

I would recommend you to use devel module and its help functions as dpm() and dpq() . They will make your debugging process a lot more faster can clean than watchdog.
watchdog() - I confirm the answer by @Decipher(+1) will record the query object in database, see the scrrenshot tested with a simple query

Might be that log is not something that you want to see, a small change to @Decipher answer if you want to see the query String

watchdog('userpoints', 'perishables->remainder %perrr', array('%perrr' => print_r($perishables->queryString, TRUE)), WATCHDOG_DEBUG);

You can definitely make it better the way you want with above mentioned tools


Using S3BrowserUpload to Add Form to a Content Type I have a content type with a machine name of "video" and I created a module called "df". I want to add a separate form to the content type (above or below the edit fields) that does a direct post to Amazon S3 using the S3BrowserUpload object from the AWS SDK. The steps I am trying to accomplish are:

Create additional upload form on "video" content type.
User enters information and specifies a file in the S3 upload form.
User clicks Save for the Add Content Type page.
Ajax fires the Amazon S3 POST form to upload the video file and handles the response to store the file's key path in a hidden field.
The normal drupal add content type fields are then posted back to the drupal site and processed. It would also have access to the hidden field that had been populated with Ajax.

I am new to Drupal forms so any assistance in integrating S3BrowserUpload with Drupal's forms API in my custom module to accomplish the steps above would be greatly appreciated.

Recently I worked on a project to integrate JW Player into a Drupal 7 site where the videos stream from an S3 bucket. There was also some Zencoder stuff going on but that is not really relevant here I don't think.

Currently we don't upload directly to S3 though, the project ran out of time before we could implement that. What the client does is upload the files directly to S3 and then reference the file in the content type using the Remote File Source module. That is not quite what you are trying to do though.

I have had a look around and see there is an Amazon S3 CORS Upload module which looks promising and might be able to help you. It creates a new form field #type which you can use in your module.

If none of that appeals to/works for you :) then you can use hook_form_alter to add a new custom upload field to the content type form, it is kind of messy but it will work. Then you add an extra submit handler to the form to catch your file. You can then use the code from this example to submit your file to S3.

The nicer way would be to create a new Field using the Drupal 7 Field API.


Links continue to point to live server - Drupal Live to localhost I have inherited a Drupal 6 site to maintain.

I am new to Drupal so there is an element of learning as I go.

I have encountered a strange issue after attempting to set up a test site on my local machine.

All my links on my local site continue to point to the live server. So any menus, login buttons etc all point towards live site.

Steps I have taken:

checked settings.php to ensure that $base_url is set to
"http://localhost:456"
checked settings.php to ensure that MySQL settings are correct
Taken an SQL dump of the entire local database and searched for any
references to live site URL
deleted all the local cache data from database
Checked various blocks to ensure that there was no hard coding of
links
Disabled language support as that does use separate URLS for each
language

I am at a total loss as to where to go from here. I can navigate through the site locally by replacing the url in the address bar to point to the local site, and I have even managed to change the local theme so I can see which version of teh site Im on. The fact that I could do this means that the database is set up correctly.

Totally stumped as to where to go from here. Any takers??

Make sure you updated the $base_url to reflect to you local server name in settings.php. Also check if your menu system is using absolute path.


Custom theme: variable not made available in menu template I've created a custom theme, let's call it "mytheme" in the examples, with the "classy" theme as base. I use several templates, one is menu--account.html.twig, it's an override I made of the classy menu.html.twig template to display a menu. In that template I need the username and some other info from the currently logged in user.

I've tried different ways of getting it to output the username in the template, i.e. the preprocess functions like so:

<?php

function mytheme_preprocess(&$variables, $hook, $info) {
  $variables['current_user_name'] = $variables['user']->getDisplayName();
  var_dump($variables['current_user_name']); //ironically this does dump the variable
}

I've tried using the Bamboo Twig module and get the username like so:

<!-- Get Current User -->
{% set user = bamboo_load_currentuser() %}
<div>{{ user.name.value }}</div>

Both variants don't work for me. If I try to dump the username with

{{ dump(current_user_name) }} or {{ dump(user.name.value) }}

all I get is NULL in the template output. From searching online I'm sure that one of these variants should work, but they don't.

I've also cleared caches several times during the tests, so that can be ruled out too.

Do you have any other suggestions on how to output the variable in that template?

I think that it might work if you do like this,

function mytheme_preprocess_menu(&$variables) {
  $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
  $variables['current_user_name'] = $user->getUsername();
}

Remember to clear the cache.

After debugging, we found out this this code worked, in the case somebody runs into the same issue.

function themename_preprocess_menu(&$variables) {
  $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
  $variables['attributes']['uname'] = $user->getUsername();
}


How can I get a views exposed filter to persist across multiple views? I have 2 separate views that return a set of results for each of my content types. The fields are different, but the filters are exactly the same - Sort by Location / Distance. This Distance / Proximity filter is exposed, and it is set to 'remember' the last entry. I followed the tutorial here http://drupal.org/node/359463 to be able to filter results by distance. It works great.

In views, to remember the last entry, Views uses sessions. But, each view has its own individual $_SESSION variable. That means what I set for one view does not carry over to the next, and even each view can have different values, which is not what I want. Here is a dump of the session after they have been set:

[views] => Array
    (
        [search_pages] => Array
            (
                [default] => Array
                    (
                    )

            )

        [baby_clothes_pages] => Array
            (
                [default] => Array
                    (
                        [distance] => Array
                            (
                                [postal_code] => 11211
                                [search_distance] => 100
                                [search_units] => mile
                            )

                    )

            )

        [baby_gear_pages] => Array
            (
                [default] => Array
                    (
                        [distance] => Array
                            (
                                [postal_code] => 22343
                                [search_distance] => 100
                                [search_units] => mile
                            )

                    )

            )

    )

What I would like to do is create a small module or snippet of code that will simply allow someone to type in their 5 digit zip code and then it update all the values across all my pages with this filter. If it is changed on any page, then it changes it for the rest of the pages as well. It also needs to work so that it affects the results on the next page load so that it correctly shows them filtered.

Here is a snippet of code I was experimenting with to try to set this value, but it's the wrong direction.

 $all_views = views_get_all_views();            // get an array of all views in use on the site

foreach ($all_views['category_pages']->display as $key => $value) {
 //check to see if the structure exists I am looking to modify
if(array_key_exists('postal_code', $all_views['category_pages']->display[$key]->display_options['filters']['distance']['value'])) {

//if so, set its value
$all_views['category_pages']->display[$key]->display_options['filters']['distance']['value']['postal_code'] = '28152';

//try setting the session instead
$_SESSION['views']['category_pages'][$key]['distance']['postal_code'] = '28152';
    }

What's the correct direction? How do I get this value changed? Could it be done in the template.php file with preprocess function? Should I do it in a module, and if so, what do I need to alter?

Very lost at this point. Thanks for the direction!

It sounds like you would need to save the value somewhere. Next when a page load event happens (on any page of your site) you need to load the value into the field. I think you might need to create a cookie to do this.


How do you populate existing entities with the default value for a newly added field? Let's say I have a content type, Article, with several fields. I already have hundreds of Article nodes created, but now I want to add a new field. After I set a default value for this field, how can I make it so that all existing Articles have this new field populated with this value? In other words, I don't want all my existing Articles to have a blank value for this new field.

This seems like it should be a simple task, but I can't find anything when searching for this issue online.

I just found this module: https://www.drupal.org/project/field_defaults

It seems like it might work. But I'll withhold accepting this as the answer unless there are better ideas out there.


Adminimal template and CCS adjustments and priority of css files? In Drupal 7 i use the adminimal template for some pages.

I want to adjust some element and added therefore a SASV file into the theme.
Now some elements I can override but some elements (like table th) are not going well. Looking into a deeper way I can see the priority of the files:

1 custom.css (with my adjustments)
2 reset.css
3 style.css

So Style.css is applied as last. But style css is not in the info file?!?!

In the adminimal.info file I added:

; ========================================
; Stylesheets
; ========================================
stylesheets[all][] = css/custom.css

How to change the order of this processing ?

Solved by

 drupal_add_css($adminimal_path . '/css/custom.css', array('group' => CSS_THEME, 'media' => 'all', 'weight' => 2));

in the template.php file


How to read a Drupal 7 node as a css file? I know that this isn't how Drupal is meant to be used, but I have this special case where I created a node that ends in a .css extension and need to have that file be used as the css file for the whole website.

So what I've got are:

a node named styles.css residing at the url "http://www.mysite.com/styles.css"
all of my regular nodes linking to that file. the "" is hardcoded into page.tpl.php

Drupal appears not to read styles.css as a css file; any ideas?

If you know that Drupal isn't meant to be used this way, then why would you do it? Are you trying to allow the end user to edit the CSS through the UI? There are better tools for that! (eg. Live CSS, Sweaver, Live Themer...)

If you update your question and tell us which problem you're trying to solve, we can help you much better.


Filter price according to Maximum Price of Product I am using better exposed filters(https://www.drupal.org/project/better_exposed_filters) and have created a price filter and the range I have selected is 0 to 2000.But I want the maximum limit of the price filter to be the maximum price of the product on that page(I have multiple pages with different products).

Is there a way to do it using views?

In view, add sort criteria for price filter i.e. Sort descending.


How can I restrict various roles with limit in creating nodes of a particular content type How can I restrict various roles with limit in creating nodes of a particular content type?

you can use node limit module to restrict nodes for various roles.

For each roles you can create a node limit condition with certain limit for nodes for tat particular content type.


Add an external jQuery based library How can we add an external javascript library that relies on jQuery by calling $(document)??

As Drupal 7's jQuery needs to be encapsulated, adding the library just generates errors:

  $(...) is not a function

I don't understand the point of not being able to use $ directly anymore.
And adding jQuery as an external library seems to conflict with the Drupal's one

Thanks for the help

Use drupal_add_js() for this.

Please also check these resources; they could help you out.

For using other versions of jQuery, there is the jQuery Update module.


Link to create new node with taxonomy term from url already selected? I need to make a link to create a new node. I need this link to appear on taxonomy term pages so I was going to put it in a block. Nodes can be tagged with taxonomy terms.

How can I make it so the create node form has the term (from the page the link was on) already selected? So if you were on mysite.com/term/1 and and clicked the create node link, the node would have term 1 already selected.

Ive found this module but its in dev for D7 so there another way?
http://drupal.org/project/prepopulate

Thanks

Yes, you need to download and enable the Prepopulate module.

The syntax you use to prepopulate taxonomy terms with D7 is (AFAIK) not documented anywhere and the syntax it is also radically different from the syntax used in D6 that is demoed in a number of screencasts of the Preopulate module.  In D7 taxonomy terms are fields.  If you read the source code, you'll find that you prepopulate taxonomy terms as would prepopulate other field.

I.e. if your taxonomy term field is field_tags and you want to prepopulate with the term "myterm", you use the following syntax (with clean URLs):
/node/add/article?edit[field_tags][und]=myterm.


How can I auto-populate fields with Ajax? How do I autopopulate fields in a node form in drupal 8?

Basically, what I'm trying to do is create an ajax callback to autopopulate fields based on a call to a 3rd party service.

So I'm using hook_form_alter and a custom validate function, and I'm trying to update form values.

function mymodule_validate($form, FormStateInterface &$form_state) {

  $form_state->setValue('title', [['value' => 'testing 123']]);

  $form_state->setRebuild();

}

But this doesn't update the node title.

What's the correct way to alter values in a node form in an ajax callback?

I was able to get a basic autopopulation callback working based on this question:

How do I modify a core field to use Ajax and add markup?

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;

/**
 * Implements hook_form_alter() on behalf of mymodule.module.
 */
function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  if ($form_id == 'node_publication_form') {

    $form['title']['widget'][0]['value']['#value'] = 'enter title here';

    $form['import_from_third_party_service_id'] = [
      '#type' => 'textfield',
      '#title' => t('Import from third_party_service Id'),
      '#description' => t('To autopopulate fields from third_party_service, enter the third_party_service ID above in the textfield above and hit the import key below'),
      '#maxlength' => 64,
      '#size' => 8,
      '#weight' => '-10',
    ];

    $form['import_from_third_party_service_submit'] = array(
      '#name' => 'custom',
      '#type' => 'submit',
      '#value' => t('Import'),
      '#weight' => -9,
      '#ajax' => [
        'callback' => 'mymodule_import_ajax_callback',
        'wrapper' => 'import-wrapper',
      ],
    );

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

  }
}

function mymodule_import_ajax_callback($form, &$form_state) {

  // replace with code to get value from third party service
  $new_title = 'hello world';

  $form['title']['widget'][0]['value']['#value'] = $new_title;

  return $form;
}


Remove Simplenews Newsletters? I had set a content type to allow it to be used as a simplenews newsletter, and then updated the JSON Feeds Processor so that it filled in the simplenews category for all the items.

However after realizing this wasn't what I needed, I removed the field simplenews from the content type and removed the option "use as newsletter" too, but all the newsletters still show up in the admin page.

I want to delete all of these old newsletters but there doesn't seem to be any option in the module to do that ?

Inorder to remove Simple newsletter completely. You need to disable and uninstall the module.

Follow the steps

Go to Modules list (admin/modules) and uncheck simplenews letter to disable and click 'Save Configuration' to disable the module
Then Go to admin/modules/uninstall page and select/check the simplenews letter module and click 'Uninstall' to remove all data related to Simplenews letter module from your instance.


How to catch the "Login Failed" event? I want to show a custom block, only when log in has failed.
So from visibility settings I have to put a PHP code that returns TRUE only when the login has failed.

But how could I "catch" that event? Do I have to use variable_get(..)? And if yes, how could I use that?with what attributes?

Thank you.

You can use the rules module for this if you don't want to write PHP.

If you want it to be an ajax event you will need to write a custom login form.

The user.module has a set of functions you can call for validation: user_login_final_validate().

I suggest rules module, save yourself some time.


hook_field_widget_form_alter - modify specified field only I'd like to use a hook to modify a widget, but only for a named field.

Use case: a form has an entity reference to another content type, using an options_buttons widget (a list of available courses the user can apply for). Rather than just the title alongside each checkbox, I'd like to display some extra fields from the content type such as date, a URL etc.

The documentation suggests $context['widget'] ("The widget plugin instance.") is the place to look, however a var_dump of that just seems to give me lots of protected properties and no clear way of getting the field name.

Essentially I'm after a D8 version similar to this old example I found:

if ($context['field']['field_name'] != 'field_bannerimage') return;

So it's actually to be found in $context['items']

if (($context['items']->getName() != 'field_myfield')) {
  return;
}

// if still here, our field matches. do something

Also note you can be more efficient by using the WIDGET_TYPE hook, e.g. for my "Check boxes/radio buttons" widget:

function hook_field_widget_options_buttons_form_alter(...)


Max File Upload Size set to big, but Ajax Error with old file size I have changed the upload_max_filesize and the max body size in my php.ini to 15 MB. It used to be 2 MB. Drupal displays the max file size correctly, but when I try to upload files bigger than 2 MB - the old limit - I get an Ajax Error, telling me the entity is too large. Any idea where this comes from?

Just for documentation I'd like to add my findings here. I had this issue in Drupal 8, but I guess the Drupal version can be neglected to answer this question.

Suhosin

As @Clive already mentioned it in the comments to the question it's definitely worth a look under /admin/reports/status/php if the Suhosin PHP extension is enabled.

In https://www.drupal.org/node/725056 people suggest to disable this extension completely, but it's maybe better as @Clive suggested to simply override one of its parameters by editing your php.ini. Or by setting this in settings.php – if that is possible at all – via ini_set('suhosin.post.max_value_length', '-1'); or something like that. Maybe it's a different parameter you have to override.

Or Apache

If there's no Suhosin extension enabled, you may find this forum post valuable: https://www.drupal.org/forum/support/post-installation/2015-04-07/ajax-error-when-uploading-large-files where it's suggested to disable or reconfigure Apache's mod_security security mod.

Or JS

Last but not least you could simply try to circumvent Ajax completely by unbinding the event handler for the submit button, or by removing it completely.

Drupal 7

// Disable ajax upload for file field
drupal_add_js("jQuery(function() { jQuery('#edit-field-image :submit').unbind(); });", 'inline');

Source: How do I disable ajax on file fields?

Drupal 8

(function ($, Drupal) {
  Drupal.behaviors.autokill = {
    attach: function (context, settings) {
      // $('.form-managed-file > input.form-submit').remove();
      $submit_button = $('.form-managed-file > input.form-submit');
      $submit_button.unbind();
      $submit_button.removeClass('js-hide');
    }
  };
})(jQuery, Drupal);


Custom Menu Form Node Creation I have been going over posts and examples for hours but finally need specific help on where my code is broken. I'm trying to create link in navigation that opens a form to create a new node. However no link anywhere is being made and I'm not sure what is missing. While its supposed to also upload a image I'm not worried right now since it doesn't work anyway. As a beginner my module looks correct but experienced eyes can hopefully give me some advice on where I went wrong! Thanks for any support and let me know of anything else I can add to solve this problem.

<?php

function ImageLoader_menu() {
$items = array();
$items['ImageLoader'] = array(
   'title' => 'Image Uploader',
   'description' => t('Upload a image.'),
   'page callback' => 'ImageLoader_upload_form_submit',
   'page arguments' => array('ImageLoader_upload_form'),
   'access arguments' => array('access content'),
    );
  return $items;
}

function ImageLoader_upload_form() {
$form = array();

$form['name'] = array(
    '#type' => 'textfield',
    '#title' => 'Name'
);

$form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Create Node!'
);
return $form;
}

function ImageLoader_upload_form_submit($form, $form_state){
$node = new stdClass();
$node -> type = 'Nature';
$node -> title = $form_state['values']['name'];
$node -> language = LANGUAGE_NONE;
$node->path = array('alias' => '/');
node_object_prepare($node); // Set some default values.
$node->uid = 200;

$node = node_submit($node);
node_save($node);

drupal_set_message(t('Node Created'));
}

You should use below code in your code and clear the cache.

'page callback' => 'drupal_get_form',


How can I fix this error and upload files? I have a simple form with just a field to upload a file on a Drupal 8 site using the Webform module 6.0.1. If I test the form using webforms test tool, the file gets uploaded fine, it displays the loading icon for couple seconds and its ready to upload, but if I try the same in a page with the form embedded as a block, I can not upload the file it will always show me the following message if I try to submit the form, no matter how long I wait.
"File upload in progress. Uploaded file may be lost. Do you want to continue?"

Just for testing, I increased the max upload file to 2GB and the file I'm uploading is just 5kb. All the .js libraries I can think of are on my template.info.yml file. (core/drupal, core/jquery, core/drupal.ajax) The private folder has been set up in my settings.php and has the permissions set correctly the .htaccess file is also set as recommended for Drupal. I have try to upload the files in the public folder just as desperation but I get the same error
Any help will be appreciate.

I figure out what the problem was. I'm posting the solution for my case just in case someone has the same problem.
My problem was that I had change the submit button ID in the input.html.twig file. I replaced it to the original and it works fine.


Can views pages be indexed and be searchable by apachesolr? By default drupal will only send nodes to apachesolr, is there a way to send views pages to solr, so that they may show in the search index?

I know this question seems a little out there, just looking to see what clever minds within Drupal think about what can be done here.

Thought I would post about how we ended up solving this:

Installed the module https://drupal.org/project/viewfield (which has a 7.x-dev release)
Created a new content type called 'Section Overview'
Added a viewsfield to the content type 'Section Overview' that allows the author to choose the view they wish to embed from a dropdown list
Told apachesolr to index nodes of type 'Section Overview'

In the end it was not that hard, just took some lateral thinking.


A view only shows if a certain filter criteria does not exist? I have a view that I am using to list events, specifically "today's events." I used a filter criteria to allow me to only display events that were happening "today" (as asked by an earlier question. I have recently realized that there will not necessarily be an event "Today", and if there isn't, I have a problem, because nothing is displaying. what I want is to have either a separate view (or do it in the current view if it is possible) that only displays if there are no events "today" what I want it to display instead is "upcoming events." that way, if there are no events on the day that you are looking at the site, than ou will see future events instead.

Under the advanced tab you can define "No Results Behavior".  This will allow you to add a view or html instead.  This will be in the same view.


How to hook into Drupal 6 search process? I need to modify the search results drupal generates to include selected content from some other D6 sister sites.  hook_search seemed like the obvious choice, but when I implement it, it's never invoked with the keywords I'm searching for:

function nmc_xsearch_search( $op = 'search', $keys = NULL ) {

    switch ($op) {

        case 'name':
            return t('Content');
            return $form;

        case 'search':
            dsm( "Operation: $op | Keys: $keys" );
                return $results;
    }
}

When I walk through this code in the debugger, my function nmc_xsearch_search() is hit twice.  The first time $op = 'name' and $keys = null.  The second time $op = 'name' and $keys = '1'.

When I put a breakpoint on node_search it is invoked four times - all before my nmc_xsearch_search() is hit.  The last time node_search is hit the provided parameters are: $op = 'search' and $keys = 'my search keywords'.

Basically I want my function to get the same invocation that node_search is getting so that I can access the keywords and modify the results array returned by hook_search.  Any ideas?

If you look at search_menu(), you will notice the following code.

  foreach (module_implements('search') as $name) {
    $items['search/' . $name . '/%menu_tail'] = array(
      'title callback' => 'module_invoke',
      'title arguments' => array($name, 'search', 'name', TRUE),
      'page callback' => 'search_view',
      'page arguments' => array($name),
      'access callback' => '_search_menu',
      'access arguments' => array($name),
      'type' => MENU_LOCAL_TASK,
      'parent' => 'search',
      'file' => 'search.pages.inc',
    );
  }

Every module implementing hook_search() gets a menu tab. So, your module will be asked to search only when the users select its tab.


Devel Module bogus output I need help with the devel module. I'm outputting my objects/variables with dpm($variables); into my template.php and I get the same output on every page. It's pulling one of my views and showing it as the markup for every page. I'm running Drupal 7 with my own subtheme of the Omega project. Any ideas what's going on?

What preprocess function or theme function override are you putting dpm() inside of? If you are inside of hook_preprocess_views_view() then I would expect that you'd get the same results in on every page that the given view is on.


Attach javascript library and settings to a node page Normally, to attach javascript (settings or just a library) to a Drupal 8 node type (page), you should use template_preprocess_node and add it to the #attached array. (example)

Problem with the display suite is that the function is never reached. So you can't add the library and optionally the settings for that library to that node.

Although the hook_preprocess_field function would suffice, I have the issue that I want to add it to a non-renderable field. So the field will never be displayed. I just need some javascript settings based on that field.

Example:

I have a node type: background_carousel_page
With a field: images (field type: image, multiple allowed)

I need to be able to add the images url to the settings of javascript to make the carousel displaying the images.

So to summarize: I need a solution where I can add the library + settings to a specific node based on a field that's not being rendered.

try hook_entity_view or hook_node_view_alter:

/**
 * Implements hook_entity_view().
 */
function mymodule_entity_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {

  if ($entity->bundle() == 'background_carousel_page' && $view_mode == 'full') {
    $build['#attached']['library'][] = 'mymodule/mylibrary';
  }

}

or

/**
 * Implements hook_ENTITY_TYPE_view_alter().
 */
function mymodule_node_view_alter(array &$build) {
  // @see \Drupal\Tests\embed\Functional\EmbedPreviewTest::testPreview
  $build['#attached']['library'][] = 'mymodule/mylibrary';
}


Is Drupal Commons right for me? I'm reading a lot, searching, asking questions. Measuring thrice before cutting once.

Now it seems to be a straight choice between a pre-built Drupal Commons and roll-your-own based on core-Drupal plus some modules.
I absolutely require a wiki, which doesn’t seem to be in the standard distro, no easily addable as a single module.

I won’t mention standard stuff like forums, but will say that I want a “social networking site” for ex-pat foreign workers in another country.

It would be nice to have some form of Goups of fiends & colleagues and to provide sharing permissions at that level of granularity (e.g, world read, group right/ group read only, etc); joint calendars,  access to blogs, maybe chat rooms or even one form per Group; maybe a photo album, although I suppose they can just refer to their Flikr.

Maybe profiles with some extra stuff like IM, phone #, etc,  where the user can control who gets to read it.

(Plus anything more that you can suggest for such a community, of course)

It looks to me like I would be best to start with Drupal Commons – do you agree?

The only thing is that when I go to download it, it says
6.x-2.0 tar.gz (17.4 MB) 2011-Aug-26 Version 2.0 is a major upgrade
Which seems to imply that it is based on Drupal 6, not Drupal 7. Is that correct? Is it a show-stopper for me? Or can I just install it and upgrade everything?

Sorry if I don’t sound too knowledgeable; I am still not a Drupal user, just a dabbler on my local PC.

Thanks in advance for any help.

I would recommend starting with Drupal Commons as a base. It comes with a lot of prebuilt configuration that's very nice, like the fb-style walls for groups and for users. You get all the standard things you mentioned except for forums, but that comes with Drupal core, or you could go for a more advanced solution. You can disable any features you don't want in a per group basis. Commons already comes with a nodes as profiles solutions, so you just need to add the fields you want to the profile node. For chats you will also need an additional module, there are several, maybe this will help get started.

To answer your question more directly, yes Drupal Commons is right for you. It will save you a lot of configuration time, and you can see some best practices in configuration from what they did. Remember to back up your db often and don't be afraid to modify everything to suit your needs, you will learn a lot that way. As long as you have a a backup you can always revert.


How to boost search relevance based on certain values using Search API I'm using the Search API with a database back-end.

I would like search results that are tagged Editorial to be favoured over results not tagged Editorial. So, for example, if two articles match a search query, and one is tagged Editorial, I'd like to see the Editorial one listed first.

Can this be done?

Thanks.

It would be insanely complex to do this properly, since you need to alter some very core Search API mechanics, much of which is handled by the database backend and not search api itself.

What you could do as a hack, it to

Create two fields: A and B.
Select a non existing word like ethsrtsghtpofksd
Add the word in field A when it's an editorial and in field B when it's not an editoral.
Set the searcg weight for field A to be higher than field B
Add the word to all searches before search API sends it to the DB.

Since the word is used in all searches and it always is matches (either in field A or B) it won't effect the results, but the weight they get will be different since field A will get a boost. I haven't tried this before, but it should work. But like I said it's a hack so it's not a pretty solution, but it's a clever way of avoiding to mess with the internal workings of Search API module.


Export sorted View to JSON I need some expert help. I need to export data into JSON. Here are the steps I followed:

1> Created a draggable view to allow admin to provide appropriate sort order.
ref (https://3cwebservices.com/drupal/creating-drag-drop-sorting-interface-drupal-view)

2> Adding a page on the same view, with format as 'JSON data document'

I can see the output in JSON format but the SORT order provided by admin is missing.

Any help is appreciated.

I used the query generated by the drupal page and generated JSON programmatically.


Load Module on Node ID My programming skills are really not up there.

I'm trying to load a module, and whatever instructions in there, only when a node ID is viewed.

I think I need to use hook node_load.

In other words, if Node ID of type webform is being viewed, load the following instructions from enabled custom module.

I think it is best to create a hook_preprocess_node in your custom module. There, you can check the node id and call the required functions.


How do I add a new content status? What hook would I use to add a new content status under the path admin/content?  See image below.

I am trying to give my content type(s) a new status so that I can do some more filtering on it.  Specifically, I want to create a new "draft" status.  Any pointers on where to start and API's to look at?  Or are there any existing modules that do this that I can take a look at the code?

EDIT: I would like the user filling out the form to set their own status as 'draft'.  The reason is that I am using the save_draft module (http://drupal.org/project/save_draft) that allows the user to save values in a form without submitting it.  The problem is that Drupal considers the node to be unpublished.  My editors should not see the content type if it is in "draft" mode, but since Drupal saves it as "unpublished", my editors see this and they are not sure if the content is ready to be edited or if the end user is just saving their work and finishing it up later.

The save_draft module gives me 2 buttons (Publish and Save as Draft).  This allows the user to select their own status.  I would also like this new "save as draft" status to be searchable/sortable so my editors could find out who hasn't finished submitting their unfinished draft, if need be.

You should look at the workflow module. This one is used to create additional work flows and status in your content authoring.


How can I hide the username on a custom user-profile.tpl.php page? I'm making a custom user-profile.tpl.php page and want to put the "business name" field where the Title/Username normally occurs and print the username elsewhere.

The username doesn't appear in the list at:
Administration » Configuration » People » Account settings » Manage Display so I can't remove it there.

My guess is that I need to add some logic to page.tpl.php to not print it on user profiles and then I need to know the variable to add it to user-profile.tpl.php.

Can anyone help me with this?

You can do it by disable field display property using form_alter

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'FORM_ID') {
  $form['account']['your_field_name']['#access'] = FALSE;
    }
  }


Password reset email is not valid? In setting up a new Drupal 7 site, I went to try out the password reset option, and while I received the password reset email just fine, clicking it takes me to a page with an error "You have tried to use a one-time login link that has either been used or is no longer valid".

I've tried sending the reset email a few times and clicking the link immediately each time, and keep getting the same error message. What sort of things make a reset link "no longer valid"? I'm working on a staging server that will be translated to a live server, so URLs and cookie paths might be getting tangled; where do I need to start looking to unravel this?

Note: The user accounts being tested were imported using the Migrate module from another system, hence their passwords are invalid, and I'm hoping users can just request a new password to login.

It's not documented nicely anywhere I can find, but it seems that you can't use the password reset option via email for a user who's an Administrator of the site. Instead you have to use some alternate method to change the database directly, like this.


Where is theThe Comment Form Template? I can find the comments template
at modules/comments/comment.tpl.php

But where is the  comment Form Template please?

I want to add a users image next to the form

Thanks for your help

Charles

It is in the default comment module , and editing the core options is not a good practice at all.

You can alter the comment  form in your active theme template.php or hook_form_alter() function in your custom module

<?php
function THEMENAME_form_comment_form_alter(&$form, &$form_state) {
        //dpm($form); //shows original $form array
        //$form['author']['#type'] = 'fieldset';
       // $form['author']['#title'] = 'Your Information';
       // $form['author']['#collapsible'] = FALSE;
      //  $form['your_comment'] = array( '#type' => 'fieldset', '#title' => t('Your Comment'), '#collapsible' => FALSE, '#weight' => 2, );
        //Subject
       // $form['your_comment']['subject'] = $form['subject'];
       // unset($form['subject']);
     //   $form['your_comment']['subject']['#weight'] = -10;
        //Comment
        $form['your_comment']['comment_body']['#prefix'] = "
User picture
" ;
        $form['your_comment']['comment_body'] = $form['comment_body'];

}
?>

You can add user picture using prefix/suffix in the comment form.
Try if it work for you.


How do I add a link to the #title property of a checkbox? I created a custom module for Drupal 8.6, and I want to post a link to my terms and conditions.

This is the code I am using.

namespace Drupal\commerce_agree_cgv\Plugin\Commerce\CheckoutPane;

use Drupal\Core\Form\FormStateInterface;
use Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane\CheckoutPaneBase;
use Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane\CheckoutPaneInterface;
use Drupal\commerce_cart\Controller\CartController;
use Drupal\node\Entity\Node;
use Drupal\Core\Link;
use Drupal\Core\Url;

/**
 * Provides the completion message pane.
 *
 * @CommerceCheckoutPane(
 *   id = "agree_cgv",
 *   label = @Translation("Agree CGV"),
 *   default_step = "review",
 * )
 */
class AgreeCGV extends CheckoutPaneBase implements CheckoutPaneInterface {

  /**
   * {@inheritdoc}
   */
  public function buildPaneForm(array $pane_form, FormStateInterface $form_state, array &$complete_form) {
    $link = Link::createFromRoute($this->t('my terms'), 'entity.node.canonical', ['node' => 1], ['attributes' => ['target' => '_blank']])->toString();
    $pane_form['cgv'] = [
      '#type' => 'checkbox',
      '#default_value' => FALSE,
      '#title' => $this->t('I have read and accept', ['the general terms and conditions of business' => $link]),
      '#required' => TRUE,
      '#weight' => $this->getWeight(),
    ];
    return $pane_form;
  }

}

The link does not work. When I go to my page, the link is missing.

The server runs on PHP 7.2.

How do I display the link?

The code is not calling $this->t() passing the correct arguments. The correct code would be the following one.

$pane_form['cgv'] = [
  '#type' => 'checkbox',
  '#default_value' => FALSE,
  '#title' => $this->t('I have read and accept the general terms and conditions of business', [':general-terms' => Url::fromRoute('entity.node.canonical', ['node' => 1], ['attributes' => ['target' => '_blank']])->toString()]),
  '#required' => TRUE,
  '#weight' => $this->getWeight(),
];


How to use tokens in webforms? I'm trying to use the [current-page:url] token in a webform hidden field (as the default value) but the submission shows "[current-page:url]" literally.
Am I missing something?

token is a contributed module and not part of Drupal 8 or webform installation.  You have to install and enable before you can use it.

composer require drupal/token
drush en token

NOTE: Webform is not aware of token directly and does not complain because it thinks are you just inputting text


Using Bootstrap with a Zen subtheme in Drupal 7 I was wondering if anyone could provide me with some advice on implementing bootstrap in D7 with the a Zen subtheme.

I'm really only using it for the responsive div sizing at the moment - I've got a 3 column layout on my homepage that uses col-sm-4 so that it stacks the columns when you're looking at it on a phone-width browser. I've done quite a lot of customization in my Zen subtheme, so I don't really want to install an entirely new theme (the Drupal bootstrap theme, or Zenstrap, for example).

I've tried a couple of approaches to this. First time around, I just copied the bootstrap css file into my theme's css directory, then included it in the normalize.css file, at the top. This worked pretty well, but it occurred to me that if I wanted to use any of the JavaScript features I wouldn't be able to.

Second time around I tried using the Drupal Bootstrap library module. This is also pretty good, and includes the css and js files on all the site pages.

However, I note that it overrides quite a lot of my existing styles. For example, I've got a number of linked headings on the homepage. I don't really want them to use the link style, but whatever I do in the normalize.css stylesheet, I can't stop my homepage picking up the Bootstrap styles. I guess maybe the theme stylesheet loads before the bootstrap stylesheet.

So I'd like some advice, please. Which of the two approaches is the better way to use Bootstrap? Is there another way that is better than either of those approaches? Is using Bootstrap even the best way to make my site responsive?

Thanks very much.

In your_theme.info do the following:

stylesheets[all][] = bootstrap.css
stylesheets[all][] = yourstyles.css

This should load both Bootstrap first and your own CSS files afterwards.


Magento + Drupal SSO (Single Sign On) We are looking to build a new website which would make use of 2 web applications: Drupal and Magento. Drupal will be used for corporate website while Magento will serve as a web shop. One of the challenges that I'm facing is the single-sign-on (SSO) part. I have done quite a lot of reading about this subject and haven't come across the "best way" to do this.

Do we keep a separate user database on both Magento and Drupal? (Taking into consideration that not every Drupal user will have access to the web shop.)

Should we use a central authentication server (CAS) instead?

Currently I'm testing the following method:

Installed the Drupal rules module
Configured that the user is redirected to a file sso.php after
he/she logs in on Drupal
The sso.php file reads the information of the currently logged in
user and optionally creates the Magento session for this user (if an
account with a matching username/e-mail) exists

Does anyone have any previous experience in getting the SSO feature between Magento-Drupal? Any input would be appreciated!

Some more info:

The website and web shop will run on the same domain. The web shop is located in a subfolder
Preferably the SSO has to be done programatically without using the slow Magento API

Check out phpSimpleSAML. There's also a similar post here:
https://stackoverflow.com/questions/7763999/magento-and-moodle-integration

Drupal can also support LDAP based logins but your sessions between both apps won't carry over so you will need a single sign on solution as mentioned above.


Custom link to add product As question states, i'm trying to make a custom menu ( hook_menu() ) to call the same pages as how commerce does it originally (will link everything below)

The idea is to let Authenticated users add products (of all product types)
I have changed the permissions for creating product entities
and can acces, as Authenticated users, the add form via the the admin url

But i'd like to change that so they have a custom link and don't see the whole admin/commerce/products/add/bag

but only
/products/add/bag

i have tried to do this by adding a custom menu with the hook_menu() but always get an 'You are not authorized to access this page.' message, even when i am connected as admin

Anyone any idea what i should change to be able to acces it outside de admin zone?

my hook_menu():

function TTK_product_form_menu() {

  //non admin form
  if (function_exists('commerce_product_types')) {
    $commerce_product_bp = drupal_get_path('module', 'commerce_product').'/';

    foreach (commerce_product_types() as $type => $product_type) {

      $items['products/add/' . strtr($type, array('_' => '-'))] = array(
        'title' => 'Create !name',
        'title arguments' => array('!name' => $product_type['name']),
        'description' => $product_type['description'],
        'page callback' => $commerce_product_bp.'commerce_product_ui_product_form_wrapper',
        'page arguments' => array(commerce_product_new($type)),
        'access callback' => $commerce_product_bp.'commerce_product_access',
        'access arguments' => array('create', $type),
        'file' => $commerce_product_bp.'includes/commerce_product_ui.products.inc',
      );
    }
  }

  return $items;
}

problem was that i didn't knew very well how menu hook worked
solution is:

foreach (commerce_product_types() as $type => $product_type) {
  $items['sell/' . strtr($type, array('_' => '-'))] = array(
    'title' => 'Sell !name',
    'title arguments' => array('!name' => $product_type['name']),
    'page callback' => 'commerce_product_ui_product_form_wrapper',
    'page arguments' => array(commerce_product_new($type)),
    'access callback' => 'commerce_product_access',
    'access arguments' => array('create', commerce_product_new($type)),
    'file' => 'includes/commerce_product_ui.products.inc',
    'file path' => $commerce_product_bp,
  );
}

didn't have to apend the path to function names, thought those where called by path for some reason..


Problem extending BookNavigationBlock i have a Problem extending a BookNavigationBlock Plugin. When I extend BlockBase it works, but when trying to extend BookNavigationBlock, it fails when placing the block, without any error messages. What am I missing here? (The Code is inside modules/ifg_book_navigation/src/Plugin/Block/IfgBookNavigationBlock.php)

namespace Drupal\ifg_book_navigation\Plugin\Block;

use Drupal\book\Plugin\Block;
/**
 * Provides a fully expanded 'Book navigation' block.
 *
 * @Block(
 *   id = "ifg_book_navigation",
 *   admin_label = @Translation("Expanded Book navigation"),
 *   category = @Translation("Menus")
 * )
 */
class IfgBookNavigationBlock extends BookNavigationBlock {

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

Thanx!

UPDATE:
I could trace the Problem to the Plugin Factory.
In the getPluginClass method of DefaultFactory it is checked if the class exists:

if (!class_exists($class)) {
  throw new PluginException(sprintf('Plugin (%s) instance class "%s" does not exist.', $plugin_id, $class));
}

The value of $class is Drupal\ifg_book_navigation\Plugin\Block\IfgBookNavigationBlock which seems to be correct. However class_exists() itself seems to fail, not even returning false. This could have something to do with autoloading, as by default class_exists() tries this by default ...

UPDATE: It seems like the behaviour is the same for other existing blocks, just tested UserLoginBlock

The actual class has to be included in the use statement.

use Drupal\book\Plugin\Block\BookNavigationBlock;


How do I make my site "notice" things to index? The built-in search feature in my Drupal site is not working. After looking online, the only solutions I've seen are to "0% of the site has been indexed" but with "x items left to index" (x>0).

My question is how do I make my site "notice" things to index?

Here's a picture of the error I get:

Update: I'm working with Drupal 7.

Here are a few things you should check:

On the Search settings page (located at admin/config/search/settings), make sure Node is checked (enabled) as an Active Search Module.
On admin/reports/status, verify when your cron job was last executed. And use the link 'run cron manually' on that page to manually trigger the cron job to be run.
Disable the "PHP Filter" module (used for nodes that use the "PHP Code" input format), to not get stuck because of some bad PHP code stored in a node. Because nodes containing PHP can cause problems with search indexing.
Clear the cache.
Check the Drupal log for possible errors related to it.

Some more excerpts from Search module: an internal site search system, related to Re-indexing:

Content-related actions on your site (creating, editing, or deleting content and comments) automatically cause affected content items to be marked for indexing or reindexing at the next cron run. When content is marked for reindexing, the previous content remains in the index until cron runs, at which time it is replaced by the new content.
Unlike content-related actions, actions related to the structure of your site do not cause affected content to be marked for reindexing. Examples of structure-related actions that affect content include deleting or editing taxonomy terms, enabling or disabling modules that add text to content (such as Taxonomy, Comment, and field-providing modules), and modifying the fields or display parameters of your content types. If you take one of these actions and you want to ensure that the search index is updated to reflect your changed site structure, you can mark all content for reindexing by clicking the "Re-index site" button on the Search settings page (administer >> site configuration >> search settings in Drupal 6, or administer >> configuration >> search and metadata >> search settings in Drupal 7).

If none of this helps, then you may also want to look at issue # 1715366 (which started in D7 ...) for other possible causes of your issue.

PS: what happens if you run the cron job, eg by triggering it from the admin screens?


How do I add multiple links in each table row form table? I am new to drupal 8. I have created a form listing in admin.Now i want to add three or more links for operation(Edit/Delete/Suspend) in single TD columns. Can anyone let me know how to do this? I tried by concatenation two links but did not work. I am creating links as below.

$query = \Drupal::database()->select('vacations', 'v');
    $query->fields('v');
    $table_sort = $query->extend('Drupal\Core\Database\Query\TableSortExtender')->orderByHeader($header);
    $pager = $table_sort->extend('Drupal\Core\Database\Query\PagerSelectExtender')->limit(10);
    //$results = $query->execute()->fetchAll();
    $results = $pager->execute();
    // Initialize an empty array
    $output = array();
// Next, loop through the $results array
    foreach ($results as $key => $result) {
      $approve_link = Link::fromTextAndUrl(t('Approve'), Url::fromRoute('vacation_forms.operations', ['ID' => $result->id, 'action' => 'approve']))->toString();
      $reject_link = Link::fromTextAndUrl(t('Reject'), Url::fromRoute('vacation_forms.operations', ['ID' => $result->id, 'action' => 'reject']))->toString();
      $newLink = $approve_link; // this works
      //$newLink = $approve_link . "|" . $reject_link; //this does not work it shows plain html in table columns
      $output[$result->id] = [
        //'id' => $result->id,
        'employee_name' => $result->employee_name,
        'employee_email' => $result->employee_email,
        'vacation_start_date' => $result->vacation_start_date,
        'vacation_end_date' => $result->vacation_end_date,
        'leave_days' => $result->leave_days,
        'status' => $result->status,
        'operations' => $newLink,
      ];
    }
    $form['table'] = [
      '#type' => 'tableselect',
      '#header' => $header,
      '#options' => $output,
      '#empty' => t('No users found'),
    ];

I am using Drupal 8.

After a long research i was able to acheive this as follows:

$approve_link = Link::fromTextAndUrl(t('Approve'), Url::fromRoute('vacation_forms.operations', ['ID' => $result->id, 'action' => 'approve']))->toString();
$reject_link = Link::fromTextAndUrl(t('Reject'), Url::fromRoute('vacation_forms.operations', ['ID' => $result->id, 'action' => 'reject']))->toString();
$mainLink = t('@linkApprove | @linkReject', array('@linkApprove' => $approve_link, '@linkReject' => $reject_link));

and then use $mainLink in foreach loop.
Thanks for all your help.


Theming paragraph fields from entity reference in view I have a view (Drupal 8) where I load my entity reference field (display hidden), with three fields from a Paragraph type and a certain custom display).

The HTML markup looks like this now:

    Sogeti

020-55883366

    test@sogeti.nl

I can't find a way how to theme the fields. I don't get any template suggestions.

I had a situation where i had to theme entity reference fields that were used in a view. Have you tried any of these?

Setup a view mode for the Paragraph type, set view Format to Show Content where the view mode was set to the one you needed, and then i themed the view mode
Use a hook_preprocess_hook to get all the results from a View and then store them in the $variables['fields'] and then you modify the twig template for the view

This relies on Views Template Files and Debugging Twig templates


How to set a custom URL for a node without pathauto? I have a content type that requires me to assemble a URL from several sources - the node title, a taxonomy value, and some fields of a product that are referenced from a product display that this content type references.  So:

mynode type
  - title
  - taxonomy value
  - entity ref -> product display -> product field

The entity ref can have one or more products, so there is some logic I need to crunch to assemble the right URL.  I didn't have luck doing this through pathauto, so it looks like I need to handle this on hook_node_presave(), which does set my alias, but I get a 404 on that alias, so it seems I'm missing a step.

My code is:

mymodule_node_presave($node) {
    if (empty($node->path['alias'])) {
        $node->path['alias'] = _some_fx_that_figures_out_url();
        $node->path['pid'] = 0;
        $node->path['language'] = LANGUAGE_NONE;
    }
}

I guess I'm missing something?

This seems to be a duplicate of this issue

Try using hook_node_insert($node) for new content and/or hook_node_update($node) for existing content:

function mymodule_node_insert($node) {
  if ($node->type == 'mytype') {
    $node->path['alias'] = _some_awesome_pattern_maker($node);
  }
}

function mymodule_node_update($node) {
  if ($node->type == 'mytype') {
    $node->path['alias'] = _some_awesome_pattern_maker($node);
  }
}

_some_awesome_pattern_maker($node) {
  // massage node and return string
}


Displaying content type in translated languages So i have a Content Type named "My content type" (a simple form) and it has 5 fields.Now the default language of the field names is in English.[i.e feild1 is 'Name'].
I have translated the field names using the translation interface into 20 different  languages.And when users fill out the form the field names are in their respective and/or preferred language.I have created a custom page template for "My content type",and print the $content of the form there,but it is English (in other words,the field names are displayed as they are written in the content type itself).

My question : How can i display the results of the filled form so that the field names are in a specific translated language ?

A little visual example :

(this is how the "My content type" results are displayed, atm) :

First Name : lorem
Last name : ipsum
Age : 55
Hobbies : lorem ipsum

(and i want the display the field names in a specific translated language,i.e. German)

Vorname : lorem
Familienname : ipsum
Alter : 55
Hobbys : lorem ipsum

This would be a sinch to do if i could use views (but sadly i can't,client specific rule)

If anyone can help ,i'd greatly appreciate it :)

Since you wrote a custom template for your content type. I think the problem would be rendering fields without any specific language

For Example:

In your Template to print a field:

$field_language = field_language('node', $node, 'body');

<?php print($node->body[$field_language][0]['value']); ?>

Since drupal 7 uses Entity translation . You need to select language for specific fields instead of node.


How to extend a test class of dependent module I am creating a module with dependency on another contrib module. When I am trying to extend the test class in dependent module, it works fine locally(using test UI). However when I try to test my new module in qa.drupal.org it throws error saying that the  'Class not found' as the dependency module is not enabled.

You can use function module_load_include to include file in your module. Class not found because main class not include in your case.


CKeditor: Allow choosing CSS classes from a select menu in dialogs The idea is to make it easier for content managers, restricting them to choose a CSS class between a preconfigured list.

This feature is already available using the WYSIWYG module (see screenshot https://groups.drupal.org/files/ckeditor-css-config.png) but not using the CKEditor module.

I'm not sure if there is already a contrib solution for this (based on http://docs.cksource.com/CKEditor_3.x/Developers_Guide/Styles for example).

What would be the best approach?

You can specify a custom "ckeditor.styles.js" editing the profile > CSS > Predefined styles and also the Predefined Styles Path fields.

Additionally, you can override any other CKEditor configuration in Advanced Options > Custom JavaScript configuration


Route callback for RegisterForm results in Call to a member function getEntityTypeId() on null My objective: Let say there is a role named "author". I would like to have a registration form having this path: /register/author, when the user submit, he/she will get the author role (same for any other roles like /register/another_role)

Here is what I have done:

1-Creating a route: last argument will be the role name

mymodule.register:
  path: '/register/{role}'
  defaults:
    _form: 'Drupal\mymodule\Form\RegisterByRole'
    _title: 'Register by role'
  requirements:
    _permission: 'access content'

2-Extending the RegisterForm Class

class RegisterByRole extends RegisterForm
{
    public function form(array $form, FormStateInterface $form_state, $role = null)
    {
        $form = parent::form($form, $form_state);
        if (role_is_allowed($role)) {
            $form['test'] = [
                '#markup' => '<p>Test:' . $role
            ];
        }
        return $form;
    }
}

Of course I must change the submit function to assign the role, but I already have the following error when visiting the /register/author path:

Error: Call to a member function getEntityTypeId() on null in Drupal\Core\Entity\EntityForm->getBaseFormId() (line 111 of core/lib/Drupal/Core/Entity/EntityForm.php).

I found that if I add the __construct and the create functions in the RegisterByRole class definition, the getBaseFormId error disappears... But I don't understand why?... And more annoying, I couldn't get the value of my $role argument (last arg of the route).

What is wrong in my plan?

I believe the problem is here:

_form: 'Drupal\mymodule\Form\RegisterByRole'

You need to use _entity_form rather than _entity, as the RegisterForm is actually an entity form for the User entity, as described in the Entity declaration for \Drupal\user\Entity\User:

"form" = {
  ...
  "register" = "Drupal\user\RegisterForm"
},

But to do this, you'll have to register a new form op for that class. You can do this in hook_entity_type_alter():

function hook_entity_type_alter(array &$entity_types) {
  $user = &$entity_types['user'];
  $user->setFormClass('role_registration', 'Drupal\example\Form\RegisterByRole');
}

Then, back in your route, you'll remove _form and instead implement_entity_form, setting it to to user.role_registration:

_entity_form: 'user.role_registration'


override node.tpl.php in a module I created a module that should be able to display the content of a certain content type. The displaying is kinda complex and to be able to turn it off and to group everything together i created a module for this.

But in the end it should just override the normal node.tpl.php with a custom .tpl.php file. When i put the file in my template folder it gets picked up and the pages shows as intended, but i can't get it to work when the file is in module folder.

I read a lot of things about regsiter the .tpl file and preprocess but nothing that combines the pieces i need.

This is what i have so far

function apps_theme($existing, $type, $theme, $path) {
    $items = array(
        'node--app' => array(
            'template' =>  drupal_get_path('module', 'app') . '/node--app',
            'variables' => array('node' => (object)array())
        )
    );
    return $items;
}

function apps_preprocess_node(&$vars) {
    $variables['theme_hook_suggestions'][] = 'node__app';
}

It is not clear in your question if you are placing your template in sites/all/custom/modules, or in sites/all/custom/modules/the_name_of_mymodule. It needs to be the later.

However, if you:

Have your template in the proper place.
Visited the admin/appearance path to force a theme registry refresh.
Cleared all the caches aftewards.

...but still no dice, you can always specify in your hook_theme() implementation the theme_path key:

<?php
function apps_theme($existing, $type, $theme, $path) {
    $items = array(
        'node_app' => array(
            // Don't specify the path in the template name.
            // Unless you have your template inside a directory within this module.
            'template' =>  'node--app',
            'variables' => array('node' => (object)array()),
            // If you want to put the tpl in another location, you can use this key.
            'theme path' => drupal_get_path('module', 'another_module'),
        ),
    );
    return $items;
}


Form api: Combine two text fields into a div? Using the form api is it possible to combine two text fields onto the same row?

E.g. form

<?php
function foo_form($form, $form_state) {
  $form = array();

  $form['range'] = array(
    '#type' => 'fieldset',
 );

  $form['range']['min'] = array(
     '#type' => 'textfield',
     '#title' => 'Address'
  ),
  $form['range']['address2'] = array(
     '#type' => 'textfield',
     '#title' => 'Address'
  )
  // ...
  return $form;
}

Desired output

Range

  <input name="min" /> to <input name="max" />

<?php
function foo_form($form, $form_state) {
  $form = array();

  $form['range'] = array(
    '#type' => 'fieldset',
    '#prefix' => '
',
 );

  $form['range']['min'] = array(
     '#type' => 'textfield',
     '#title' => 'Address'
  ),
  $form['range']['address2'] = array(
     '#type' => 'textfield',
     '#title' => 'Address'
     '#suffix' => '
',
  )
  // Remaining code
  return $form;
}


Show message at every page regardless page content I need to show some message for user for every page at my site.

I've tried Rules action "Content is viewed" and I see message, but only when some node is displayed.
I don't see message when I open User page, or page with Taxonomy term, or some View page without nodes as content.

How can I show message at every page of my site regardless page content?
(Rules or Hooks or ...?)

Why not to write it directly in the template? Or create a Block which you show in the header? or do you need to use the drupal_set_message() Message?

You can use "Drupal is initializing" event at Rules.


Theme logo and site name how can I put logo and site name in an unordered list?
I am using a bootstrap subtheme !

For that, you're going to want a custom template file (.tpl.php in D7, .html.twig in D8).

In Drupal 8, the logo and site name are contained within Bootstrap's block--system-branding-block.html.twig; in Drupal 7, they're set in Bootstrap's page.tpl.php. If you go into that file, you can change how those elements are rendered - just wrap them in the necessary  /  tags and you'll be good to go!


Newly Inserted Record was not Queried, Immediately after Insertion I have a form element below:

//Calls a function that contains the html for templates table.
$form['myid_templates_editor_table_wrapper'] = array(
    '#type' => 'item',
    '#markup' => myid_create_templates_table(),
);

The function below, populates the element above with the HTML  of a table.

function myid_create_templates_table(){

    //Retrieve list of templates in the database
    $query = db_select('studidtemplates', 't1',array('target' => 'import'));

    $result = $query
        ->fields('t1', array('template_id', 'template_name', 'date_created', 'user_name'))
        ->orderBY('template_id', 'DESC')
        ->execute();

    $table_header = array(
        'template_id' => array('data' => 'Template ID' , 'field' => 'template_id','sort' => 'asc'),
        'template_name' => array('data' => t('Template Name'), 'field' => 'template_name','sort' => 'asc'),
        'date_created' => array('data' => 'Date Created' , 'field' => 'date_created','sort' => 'asc'),
        'user_name' => array('data' => t('Created by'), 'field' => 'user_name','sort' => 'asc'),
    );

    foreach ($result as $record) {
        $table_rows[] = array(l(t($record->template_id), $record->template_id, array('attributes' => array('class' => 'use-ajax'))), $record->template_name, $record->date_created, $record->user_name);
    }
    return '
' . theme('table', array('header' => $table_header, 'rows' => $table_rows)) . '
';
}

It looks like the image below:

Whenever a new record is inserted to the table, the function below renders the $form['myid_templates_editor_table_wrapper'] element to update it's table display.

function myid_save_templates_editor($form, &$form_state){
    global $user;

    $save = db_insert('studidtemplates',array('target' => 'import'))
        ->fields(array(
            'template_name' => 'WEW',
            'date_created' => date("Y-m-d H:i:s", time()),
            'user_name' => $user->name
        ))
        ->execute();

    return array(
        '#type' => 'ajax',
        '#commands' => array(
            ajax_command_replace('#myid_templates_editor_table_wrapper', render($form['myid_templates_editor_table_wrapper'])),

        )
    );
}

I notice something weird about it. When my actual record in the database is 1, the table displays 0 records. When my actual record is 2, my table displays 1 record. When my actual record is 3, it displays 2 records in my table and so on and so forth.

I was suspecting that my $form['myid_templates_editor_table_wrapper'] element was being rendered, even if db_insert has not yet successfully inserted a record in my database.

Now, the question is : How will I execute the rendering of my form element after db_insert had successfully inserted a record in my table?

UPDATE 1:

I tried Shabir A. 's  suggestion:

$save = db_insert('studidtemplates',array('target' => 'import'))
    ->fields(array(
        'template_name' => 'WEW',
        'date_created' => date("Y-m-d H:i:s", time()),
        'user_name' => $user->name
    ))
    ->execute();

watchdog('myid', $save);

if($save){
    return array(
        '#type' => 'ajax',
        '#commands' => array(
            ajax_command_replace('#myid_templates_editor_table_wrapper', render($form['myid_templates_editor_table_wrapper'])),
        )
    );
}

But the problem still occurs, When I view my watchdog table, the $save variable has a value of 371. That means it was inserted successfully, as what Shabir A. said, but the table display was not updated. Is there anything wrong with my query? Where am I missing?

You can simply check against inserted id. If insert successful means you get inserted id only then you render the data otherwise do nothing

$inserted_id = db_insert('studidtemplates',array('target' => 'import'))
        ->fields(array(
            'template_name' => 'WEW',
            'date_created' => date("Y-m-d H:i:s", time()),
            'user_name' => $user->name
        ))
        ->execute();
if($inserted_id) {
   return array(
    '#type' => 'ajax',
    '#commands' => array(
        ajax_command_replace('#myid_templates_editor_table_wrapper',     render($form['myid_templates_editor_table_wrapper'])),

    )
);
}


How do I convert a database from MyISAM to InnoDB? I am going to convert all the tables of 500MB database from MyISAM to InnoDB to see whether it will improve the overall performance of a busy Drupal 6 site. I am wondering what is the best (i.e. safest/easiest/fastest) way to do the conversion.

As a MySQL DBA, I trust MySQL to do the conversion by having MySQL write the script for me.

Form the Linux command run this query

mysql -h... -u... -p... -A --skip-column-names -e"SELECT CONCAT('ALTER TABLE ',db,'.',tb,' ENGINE=InnoDB;') FROM (SELECT A.db,A.tb,A.tbsize FROM (SELECT table_schema db,table_name tb,(data_length+index_length) tbsize FROM information_schema.tables WHERE engine='MyISAM' AND table_schema NOT IN ('information_schema','mysql')) A LEFT JOIN (SELECT table_schema db,table_name tb FROM information_schema.statistics WHERE index_type='FULLTEXT') B USING (db,tb) WHERE B.db IS NULL) AA ORDER BY tbsize" > /root/ConvertMyISAM2InnoDB.sql

The script will convert the smallest tables first. This script was also bypass any MyISAM tables that have FULLTEXT indexes.

Ater looking over the script, you can simply run it in MySQL as follows:

mysql -h... -u... -p... -A < /root/ConvertMyISAM2InnoDB.sql

or if you want to see the timing of each conversion, login to mysql and run this:

mysql> source /root/ConvertMyISAM2InnoDB.sql

This should not get messed up because a full table lock happens when the conversion is being executed.

Once all tables are converted you need to tune the MySQL settings for InnoDB usage and scale down the key_buffer.

Please read this for setting the InnoDB Buffer Pool : https://dba.stackexchange.com/questions/1/what-are-the-main-differences-between-innodb-and-myisam/2194#2194

Please read this also : https://drupal.stackexchange.com/questions/1715/what-would-the-optimal-mysql-configuration-for-a-drupal-7-site-be/2367#2367

Give it a Try !!!


Disable sticky table headers for field collection? I'm using a field collection on my node form and sticky table headers comes baked in with no way to disable it (that I can find, anyway). How do I disable sticky table headers? Preferably with Javascript or CSS... sadly, I'm using an instance of Drupal 7 that has a lot of the internals hidden from me.

One line of CSS will do it:

table.sticky-header { display: none !important; }

Answer found here.


How to add Tags to images being uploaded? Is there a way to add tags to uploaded images (stored in vocabulary under admin/structure/taxonomy/tags/edit)

There is just alt and title fields as default at the moment....

I want users to add/ search tags that relate to images and not nodes (e.g. term reference)

I have found this module Taxonomy Images but it stops at D6 and I have D7

Ideally I would like something like this:

You can use a combination of the modules File Entity and File Entity Inline. File Entity will allow you to add fields to different file types, including images, and File Entity Inline will display all those added fields after clicking "Upload" whenever a user creates or edits content.

In order to make this work with Multiupload Imagefield Widget, you will need to apply two patches, one patch to multiupload_imagefield_widget.module, and one patch to file_entity_inline.module.

These patches are simple enough that they can be applied manually.

First install the modules File Entity and File Entity Inline. Go to Structure > File types > Image > Manage field and add the Term Reference field you want and any other fields you desire for the Image file
Apply the patches. For the sake of convenience I'm pasting below the lines that need to be replaced.

In the directory where your drupal installation lives in the server, find the file multiupload_imagefield_widget.module, usually located under the path sites/all/modules/multiupload_imagefield_widget. Add the following lines at the very end of the file:

/**
 * Implements hook_file_entity_inline_widgets().
 */
function multiupload_imagefield_widget_file_entity_inline_widgets() {
  $widgets = array();
  $widgets['image_miw'] = array(
    'element_type' => 'mfw_managed_file',
  );
  return $widgets;
}

Save.

Then find the file file_entity_inline.module, usually in the path sites/all/modules/file_entity_inline/. Find the line:

if (empty($element['fid']['#value']) || !isset($element['#entity_type']) || !isset($element['#field_name'])) {

and replace it for:

if (empty($element['#value']['fid']) || !isset($element['#entity_type']) || !isset($element['#field_name'])) {

and find the line:

$file = !empty($element['#file']) ? $element['#file'] : file_load($element['fid']['#value']);

and replace it for:

$file = !empty($element['#file']) ? $element['#file'] : file_load($element['#value']['fid']);

Save.

Go back to your site, clear the cache. Then you should be good to go. Be sure to select Multiupload as the widget for the Image field. After selecting the files and clicking Upload, the page will show thumbnails for each file and whatever fields you have added to the image file entity in step 1.

ONE BIG CAVEAT: If you ever install an update or upgrade for either patched module, you will lose your patches, unless they are "committed" to the new module versions. The maintainers of both modules seem to be dragging their feet committing these patches. Multiupload Imagefield Widget has had two new versions without this patch being committed. File Entity Inline hasn't been updated in at least 3 years...


View item duplicates based on total views I have a view that simply loads all the latest articles but I ran into some strange problem. Each time I visit an article, the view count increases but this also means that a certain article will appear in the as much as the count shows.

For example:

View:
- Article 1
- Article 2

When I click on Article 1 my view updates to:

View:
- Article 1
- Article 1
- Article 2

I hope this is clear enough to understand.

Note: maybe worth mention I'm setting up a service so in my json api I get the same results

Solved it by removing Node count: node id I used the wrong fieldto display the id


How to make the image hover between the 2 uploaded image? How to make the image hover between the 2 uploaded image?

    <a href="<?php if (!empty($node->field_link_site)) print $node->field_link_site['und'][0]['value']; ?>" target="_blank">
        <?php print theme('image_style', array('path' => $imageone, 'style_name' => 'image_800x600', 'attributes'=>array('alt'=>$title))) ?>

The script above just make the node display one image.

The second image is not appearing.

How to make it the image change to the 2nd image if mouse move over the image?

Display both images independently with something like this:

<div class="portfolio_area_left">
    <?php print theme('image_style', array('path' => $imageone, 'style_name' => 'image_800x600', 'attributes'=>array('alt'=>$title))) ?>
    <?php print theme('image_style', array('path' => $two, 'style_name' => 'image_800x600', 'attributes'=>array('alt'=>$title))) ?>
</div>

Then use jQuery for the hover/fade: http://jsfiddle.net/adeneo/xTw44/


how to implement hook_menu so that it recognizes URL like ?q=myterm, as sent by jQuery autocomplete? The jQuery UI autocomplete source string expects the search string to be appended to the URL
as mysite/auto/?q=myterm
(see jquery autocomplete doc)

I have written a module that implements hook_menu and it returns the matching records through JSON.
The expected url is mysite/auto/myterm

How should the hook_menu be written so that it recognizes the ?q=myterm

I am using Drupal 7 and have Clean URL

Edit: can you explain with an example or use this code:
can you help with an example?

  url localhost/myauto/?q=sometext

mymodule_menu(){
$items['myauto/%'] = array(
    'title'= 'My example',
    'page callback' => 'myexample_auto',
    'page argument' => array('1'),
    'access callback' => TRUE,
 );

myexample_auto($arg){
...//user $_GET['q'] or drupal_get_query_parameters to get 'sometext' from $arg
}

hook_menu() don't handle query parameters. It accepts only wildcards.
You can get your query parameters in in your menu callback function and build your own logic by getting parameters as $_GET['q'] or drupal_get_query_parameters()


copy term reference from one to other field I have two fields (fieldtype = term reference) in the same content type and I would like to copy the settings from the first to the second one. After searching for a solution I found this thread but I think the description I need is just the one that is not available:

  "Copy contents of a CCK node reference field to another CCK node
  reference field"

Can somebody give me some guidelines, or even an explanation how to achieve this?

You could do something like this:

$result = db_query("SELECT nid FROM {node} WHERE type = 'my_type'");
foreach($result as $row){
  $node = node_load($row->nid, NULL, TRUE); // reset cache
  // Assign one node reference field to another
  $node->field_termreference_2 = $node->field_termreference_1;
  node_save($node);
}

If you've got a lot of nodes, you may need to use the Batch API for that.

Alternatively, you may be able to copy the field tables to another field table at the database level with SQL ( backup first )

Something like:

INSERT INTO field_data_field_termreference_2 SELECT * FROM field_data_field_termreference_1;
INSERT INTO field_revision_field_termreference_2 SELECT * FROM field_revision_field_termreference_1;

and clear Drupal caches after that.


People created by non-administrator role are not allowed to edit their content I created a role called site manager. This role is allowed to create new users. The problem is that users created by this user are not allowed to edit their contents. The Access denied is reported. But people created by the Administrator or people who signup for the site, can edit their content.

This is the permissions of site manager (for Users and content type Image):

and this one

Do any of you know why this happens?

UPDATE

After installing devel node access module I see this for a node which its author is z jafari

This user is allowed to delete its content but unable to edit it.

I also tried content access module, gave appropriate permission but it didn't work again.

Because they don't have any roles associated with them. You need to add a role to the new users giving them the permissions you want them to have.


How to filter admin/structure/block per role I use block access to determine which block a role can edit. I enabled Access the block administration page and View all blocks permissions so that my blocks_editor role now  can access the admin/structure/block page.

But the page displays the complete and huge  list of blocks, with a configure link when allowed to do so, as in screen capture below :

How can I filter/restrict this output to the list of blocks the role has permission to edit ?

Or as an alternative, how can I programmatically generate in a block, the links to blocks a role has access to ?

Thank you.

Checking the code, this popped up:

  // Remove the block completely if it's not allowed to be viewed
  if (!block_access_can_view($module, $delta)) {
    unset($form['blocks'][$key]);

in block_access_check_perms (.module file)

Otherwise it only removes the operations that user doesn't have access to. Now, this function gets called in the form_alter for the block overview page. So, you have two options as far as I can see.

First, restrict the view permission to be the same as edit (these permissions have no effect on the front-end visibility, as per the project page). This is your best bet I believe.

The other option is to alter the form again after this module has already altered it, run your own checks and then unset the blocks with no operations left.


Reseed next Drupal User ID (UID) Is it possible to modify the next User ID when creating new users in a Drupal 7 database?

As an example,

I have a user at UID 100, I then create and immediately two user accounts (101, 102). When I next add a user, I want the UID to revert to 101 rather than default behaviour of 103.

In Drupal 7 the uid column in the users table isn't an autonumber, so there's nothing to reset/reseed.

When you add a user in D7 the user_save() function does this:

// Allow 'uid' to be set by the caller. There is no danger of writing an
// existing user as drupal_write_record will do an INSERT.
if (empty($account->uid)) {
  $account->uid = db_next_id(db_query('SELECT MAX(uid) FROM {users}')->fetchField());
}

So the next user ID is simply the next available free ID (current max + 1) from the users table.

If you have a record with a uid of 100, then you add 2 new users (101 and 102), the next available user ID will naturally/logically be 103; which will be returned by the above code in user_save().

If you need that to be 101 again for whatever reason, you need to delete the user you've just created that occupies the 101 ID, and set the uid manually on the new user record that you want to replace it, before you save it (as suggested by the above comments in user_save()).


Node select list + dropdown + view of entity references In a content type, and a field is an entity reference to another content type (the professionals companies).

I created a view, to display: first: the professionals flagged as favorite; then all the others.

Then comes my problem:

How can I create a selection of professionals like this:

If user click on the "empty" field (empty before selecting): the list of favorites appears (this can be the first 10 of my view)
the user can type and like autocomplete, the results are shown.
if no favorite found, then comes a text (with link) to add node (create a new professional).

In the widget type of the entity reference:

I tried "autocomplete" but the 1. doesn't work (user is obliged to type before something shows)
I tried "view" but it's even worse (and the search is difficult)
I tried "select list" but it doesn't allow to search.

I forgot to specify:
The 3 options should be on the same field.
So, when user click on the field to select (the company), the behavior of the field to select the garage should be like this:

User clicks on it: user's favorites companies appears (through view)
If the company he wants was not flagged as favorite, he can start to type in the field and the results appears (classic behavior in Drupal).
If the name of the company he types doesn't exist, the field shows "no result" and show a link to create a company.

maybe you should try these modules (at least for a part of your question):

Inline Entity Form can help you with #3 (embed a node form within another node form with option on existing nodes)

Entity Browser could help you with #1/#2 (build your own widget, based on a View, here with a contextual filter on logged in user and relationship to favorites) - really nice tutorial here.

and Flag for favorites.

I hope this could give you some fresh ideas.


Redirecting user after login when using the ip_login module I'm trying to show a different frontpage to users of a specific role, using the Front Page module (version 6.x-2.0-rc1) in alias mode. This works fine for users that are already logged in, but the problematic point now is that I'm also using the IP Login module (version 6.x-1.2) to log in certain users based on their IP address. This login seems to work differently from the usual login via the /user page.

Those users that are logged in via IP, they first get the normal frontpage that anonymous users get, they are not redirected automatically to the special frontpage I defined using the Frontpage module. If they reload the frontpage they are already logged in now and they see the special frontpage as intended.

The usual ways of using the Rules module or the Login Redirect module to redirect the users after they login just don't work, the users are not getting redirected when they are logged in via IP address.

Any ideas on how I could work around this problem, so that users logged in via IP see the special, redirected frontpage directly after openening the page?

As mentioned by charan in a comment, this works in version 6.x-2.0-rc1 of the IP Login module.


Changing the User Title I did some searching here, but I couldn't find exactly what I was looking for. Is there a template.php function that I can add to change the content title (not the <head> page title) of a user to be a field created after-the-fact (like a first name or the last name field)? If it can't be a function, maybe some type of 'if' statement to wrap around the content title output to check if it's a user page and then output the fields would probably work.

The page title of the user profile page (like example.com/user/1) is generated by format_username(). If you want to control the username everywhere it occurs in the site, you can implement hook_username_alter in a custom module.

If you just want to change title on the user profile page, you could add THEMENAME_preprocess_page to your template.php to override $variables['title']. An example (untested code):

<?php
/**
 * Preprocess function for page.tpl.php.
 * Replace 'THEMENAME' with the name of your theme.
 */
function THEMENAME_preprocess_page(&$variables) {
  // Only act when the first part of the url equals 'user', the second
  // part is a number and the third part is empty.
  $arg = arg();
  if ($arg[0] == 'user' && is_numeric($arg[1]) && empty($arg[2])) {
    // Do stuff to create the desired username and set the $title variable for the template.
    $variables['title'] = $variables['firstname'] . ' ' . $variables['lastname'];
  }
}
?>


Accessing Drupal 6 data using Drupal 7 entities I have a project where we have a legacy system built in Drupal 6 that has been heavily customized, with much of the data stored in custom tables.  We are currently planning a D6 to D7 upgrade, but we have an immediate need to access that data in a Drupal 7 instance, leaving the D6 site intact for now.

I would like to access that data using Drupal Entities and wrap each D6 table in a Drupal 7 Entity; however I'm having trouble making that work since the underlying assumption with the Entity API is that the data is stored in the local database, and this database is remote.  We can access the database directly from the Drupal 7 instance, and I have the database credentials loaded in settings.php.  I can query the data using Database::getConnection('default', 'legacy')->select(), so I know my connection is good; however I have no idea how to go about structuring an Entity class so that I can leverage EFQ, Views, etc. on this data.

I looked at Remote Entity API, but I"m not dealing with a RESTful service here, I have a direct connection to the D6 database.

Any assistance or hints would be greatly appreciated.  I've worn Google out.

As I understand it you're discounting the Remote Entity API module because you don't have a RESTful service...
The module actually relies on the Web Service Clients module, which provides that REST service for you:

Parallel to the Services module, the Clients module provides the ability to implement pluggable clients to external web services, including external Drupal sites running the Services module, the main use case being connecting to other Drupal installs via the Services module with either the REST or XMLRPC server.
Clients module allows you to create connections to remote services with an admin UI. These handle fetching a result from a remote service. Different types of connection are provided for different types of services. There is a Drupal client connection type for different versions of Services (5.x-0.92, 6.x-2.x, 7.x-3.x), hence Clients can be used to connect to sites with different versions of Drupal.

Emphasis mine.


js files inside custom directory deleted after cache clear I have 2 files with jquery code in custom directory www.mysite.com/files/js/...Every time I clear cache, the files are deleted from server. How is this possible? Anyone came across this issue?

Files were added using drupal_add_js inside node body using php filter. Path was 'files/js/myfile.js' without using domain name. I resolved it by changing directory name from 'js' to 'js-custom'. I think 'js' directory was created by some module there and was emptied after each cache flush. Now everything works ok.


bartik subtheme and css I want to make some modifications to the bartik theme i am using D8
(like changing the logo position,etc) i created a subtheme
named it "mytheme"
following the instruction i found here:

https://www.drupal.org/docs/8/theming-drupal-8/creating-a-drupal-8-sub-theme-or-sub-theme-of-sub-theme

So, first I created the mytheme.info.yml file containing:

name: mytheme
type: theme
base theme: bartik
description: subtheme for bartik
core: 8.x
libraries:
  mytheme/global-styling
regions:
  header: Header
  primary_menu: 'Primary menu'
  secondary_menu: 'Secondary menu'
  page_top: 'Page top'
  page_bottom: 'Page bottom'
  highlighted: Highlighted
  featured_top: 'Featured top'
  breadcrumb: Breadcrumb
  content: Content
  sidebar_first: 'Sidebar first'
  sidebar_second: 'Sidebar second'
  featured_bottom_first: 'Featured bottom first'
  featured_bottom_second: 'Featured bottom second'
  featured_bottom_third: 'Featured bottom third'
  footer_first: 'Footer first'
  footer_second: 'Footer second'
  footer_third: 'Footer third'
  footer_fourth: 'Footer fourth'
  footer_fifth: 'Footer fifth'

Next i created the mytheme.libraries.yml containing the following:

global-styling:
  css:
    theme:
      css/style.css: {}

i went to appearance and enabled "mytheme" as default, went back to site, looks identical to how bartik was
so far so good

my problem now is, how do i move on with the customizations i want to do?

i created a folder called: "css" in "mytheme" directory, inside the css folder i created a blank file called "style.css" and
there i wrote the first modification i want to do

.region-header .site-branding {
    float: none;
    text-align: center;
}

When i go back to site i see no difference, the logo remains on the left like it was on bartik

Can somebody help please?

I am not sure how to proceed and if what I did by creating a css folder, etc is the right way.

Thank you.

Not sure if this is still relevant or not but I was having the same issue and I was just missing a dash.

  libraries:
    mytheme/global-styling

to

  libraries:
    - mytheme/global-styling


Get all related sister (same content type) nodes through a view in Drupal 7 On my node detail page, I am hoping to show all the related nodes through a view which have the same taxonomy term(s) selected.

How can I make sure to get the related nodes on the node detail page (Note:- I don't have taxonomy term in the URL )

Thanks.

To filter nodes with the same taxonomy term, when a node is displayed as main content (/node/???)

View , Display as block

2 contextual filters:

Content: nid -> provide default value: content id from url - more: exclude
Content: Has taxonomy term ID -> provide default value: taxonomy term id from url

It is important to put the contextual filters in this order, the first filter excludes the actual node from display, the exclude-checkbox is at the end under "More"

add additional filters, for example:

Content: your content-type
Content: Published (Yes)

Put the view block right below your Main page content in the Content-Region


Why is it possible to write any string in the hash salt I have researched a bit, but I couldn't find a precise answer to why it's possible to write any string in $settings['hash_salt'].

For me it doesn't make sense that the site chashes if no hash salt has been set and if I then go to settings.php and write,

$settings['hash_salt'] = 'x';

the site works just fine.

Why does the site work just because hash salt have any value?

You can read about it in the default.settings.php file:

  Salt for one-time login links, cancel links, form tokens, etc.

  This variable will be set to a random value by the installer. All one-time
  login links will be invalidated if the value is changed. Note that if your
  site is deployed on a cluster of web servers, you must ensure that this
  variable has the same value on each server.

  For enhanced security, you may set this variable to the contents of a file
  outside your document root; you should also ensure that this file is not
  stored with backups of your database.

This value is used by Drupal as salt for some cryptographic operations. It should be a random value. It adds more security to those cryptographic operations (as long as the value is not known by an attacker).

As far as I know Drupal uses a auto-generated salt value based on Database credentials when no salt is set, so Drupal should work without a salt value.


Overview & help with drupal files and folders on Win 7 I am a newbie. Please forgive me if this is a dumb question.

I'm trying to wrap my brain around what is Drupal and how it works.

I installed Acquia Dev Desktop successfully on my Win 7 computer. I want to make sure that I backup all files and folders, but have discovered that Drupal/Acquia is scattered just about everywhere on my hard drive. I found the following (where "Sam" is my Win 7 username).

C:\Program Files (x86)\DevDesktop
C:\Users\Sam\Sites
C:\Users\Sam.acquia
C:\Users\Sam.drush

Have I missed any locations? Why is everything not consolidated in one folder? It would make life much easier!

If this is not the proper forum for dumb questions please tell me a better place to post.

Thanks!

The confusion is probably resulting from things that differ from the Windows environment compared against the traditional multi-user LAMP environment that Drupal is usually built against.

To explain what those directories are in the order you listed them:

The DevDesktop application code
Your sites you're managing with Acquia
Acquia application configurations
Drush application configurations

This data is separated mostly to accommodate a multi-user environment. So that...

All the data for the DevDesktop application is isolated so multiple users can use the app.
The sites you manage are separate from other users.
Your Acquia application configurations are separate from other users (e.g. your login info).
You Drush application configuration is separate from other users (e.g. your site aliases).