How to disable the comment for a specific node programmatically? I'm using Drupal 8. I would like to close the comment for the node, once someone commented on that node. But I don't know how to disable the comment for a specific node programmatically.

my_module_comment_insert ($entity) //implement the comment insert hook
{
    $node = $entity->getCommentedEntity();//get the attached comment node.
    // How to implement code here to disable comment for the $node?
}

In D8, the comments are stored as field containing various comment properties including comment status.

You can disable node/entity comments using something like below:

use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;

/**
 * Implements hook_comment_insert().
 */
function [MODULE_NAME]_comment_insert($comment) {
  // Get comment field name, default comment.
  $field_name = 'comment'; // $comment->getFieldName();

  // Get entity.
  $node = $comment->getCommentedEntity();
  $node->get($field_name)->status = CommentItemInterface::CLOSED;
  $node->save();
}


how to alter notification email in search api saved search module. I want to add more details about the search I m using search api saved search module to save my search selected using facets.
In the notification email i want to add selected search options which i saved, Ex: country or city name which i selected while saving the search.

hook_mail_alter is your best friend, just keep in mind this hook fired on all emails so make sure you check if your are targeting the search-API emails. Here is a snippet of code copied from the mail_example module:

function email_example_mail_alter(&$message) {
  // For the purpose of this example, modify all the outgoing messages and
  // attach a site signature. The signature will be translated to the language
  // in which message was built.
  $options = array(
    'langcode' => $message['language']->language,
  );

  $signature = t("\n--\nMail altered by email_example module.", array(), $options);
  if (is_array($message['body'])) {
    $message['body'][] = $signature;
  }
  else {
    // Some modules use the body as a string, erroneously.
    $message['body'] .= $signature;
  }
}


Can I set Commerce to accept floats for quantity rather than just integers? I have a specific requirement for a certain product type in Commerce to accept the line-item quantity as a float rather than an integer. Is this possible?

For example 5.34 rather than 5.

The context

Product Type 'Tile' is sold in sqm (squared meters)
User chooses required quality in sqm when they add to cart
Drupal works out the minimum amount of tiles required for the chosen sqm value
The sqm value is then adjusted based on number of whole tiles required
Therefore sale price may be 5.12 sqm, if 5 sqm is required (because that is the specific sqm for X whole tiles.

Drupal Commerce supports decimal quantities, there just isn't a UI based configuration mechanism for using that vs. integer quantities. You have to alter the Add to Cart form and Shopping Cart form to change the #datatype property on quantity text fields to 'decimal' (or whatever you prefer) and then add appropriate validate handlers to ensure valid decimal values are being submitted. Search the code for datatype and you'll see the integer example code.


Is it safe and fine to block external access to sites/all/modules folder and all its subfolders and files? That's to say block all except 127.0.0.1?

If you are talking about blocking HTTP access (for browsers), then it won't give you any additional security.

But if you nevertheless want to do so, then exclude *.css, *.js and all images from being blocked.


Suddenly my website front page was not found! My websites richtown.ae, and hannahaicah.com suddenly are not showing the front page; the rest of the pages is working fine. My hosting provider changed the php.ini file this morning, due to problems with PDO. Can anybody tell me what happened?

I also changed the path for the front page but nothing happened.

Edit your .htaccess and the setup of your subdomain.richtown.ae...
frontpage on a subdomain?

# If your site can be accessed both with and without the 'www.' prefix, you
# can use one of the following settings to redirect users to your preferred
# URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
#
# To redirect all users to access the site WITH the 'www.' prefix,
# (http://example.com/... will be redirected to http://www.example.com/...)
# uncomment the following:
# RewriteCond %{HTTP_HOST} !^www\. [NC]
# RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
#
# To redirect all users to access the site WITHOUT the 'www.' prefix,
# (http://www.example.com/... will be redirected to http://example.com/...)
# uncomment the following:
# RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
# RewriteRule ^ http://%1%{REQUEST_URI} [L,R=301]


Can you preprocess a specific region in template.php? In your template.php file, I know you can use theme_preprocess_region and check what "region" you are in, and accomplish what I am attempting like that...but I was wondering if you can do something like theme_preprocess_region_specific_region to further break things up and not have a lengthy preprocess_region function?  I can't seem to find any documentation on that.

Well, you can define your own preprocess function if you want to, since you have all the elements for that. In the theme_preprocess_region function, you can simple do :

$function = 'yourtheme_preprocess_region_'.$variables['region'];
if (function_exists($function)) {
  $function($variables);
}

Then, you just have to define the a function for your region :

function yourtheme_preprocess_region_YOURREGION(&$variables) {

}


Custom Webform Email Response to two different recipients When a customer fills out a webform, I create a customized email response by creating a custom email template (e.g. webform-mail-26.tpl.php). I needed to create this so that the customer could see exactly what options he chose and not options he did not. The email also has some nice instructions. But I also need to send the admin an email with all the information that was in the form. How can I send two emails, one to the customer and one to the admin, but have each email display different content?

We ended up doing this by creating a custom email template (e.g. webform-mail-26.tpl.php). And then we created another email recipient but chose to over-ride the "default" template with a "custom" template where I used the same text and tokens as the "default" template. It was counter-intuitive but it worked.


Changing field instance display settings for view_mode Background

In the user.module file in user_build_content(), there is a line that adds fields for a given view_mode:

$account->content += field_attach_view('user', $account, $view_mode, $langcode);

The documentation for the field_attach_view() function says

  Each field is displayed according to the display options specified in the
   $instance definition for the given $view_mode.

Digging further, I find that the instance definitions are loaded/cached using FieldInfo->getBundleInstances(), which loads them from the field_config_instance table in the database in field_read_instances().

Question

I have some custom user fields already being displayed for the 'teaser' view_mode, to the exclusion of others, and I cannot find where this is coming from since no hook appears to do it in the code.

How do I change the display settings of a field for a specific view_mode? Is there a place to do this in the field UI somewhere?

Edit: I found the defaults coming from hook_field_default_field_instances(), which were exported into a module using the Features module. Can anyone tell me where I can change them in the UI in order to re-export the feature?

This took me so long to find. Account Settings -> Manage Display

admin/config/people/accounts/display/teaser


Is there a way to hide the price on a product using Drupal Commerce? Basically I want to create a commerce site, load all the products but not give a price yet, for competitive reasons.

Instead of displaying 0 I want to:

Change the price to - "Call for price"
Hide add to cart button

At a later stage when I give the item a price it should:

Display the price
Display add to cart button

I know this is possible in Magento but would rather try using Drupal Commerce.
Any tutorials or links will be appreciated.

I guess giving the product a price is a manual process.

To make things clear I suggest adding a 'price hidden' boolen field to the product content type. Based on this field you can adjust the output of the product by implementing hook_node_view_alter.


Simple button to send users info to an email address What would be the best route to create a button on a page that once it's clicked, it sends an email to the administrator. Basically we are using the profile percentage completion module, and when a user is at 100% I want to display a button to opt into a program (the program meaning, it sends us all of their info in their drupal account)

It seems very simple, but I can't wrap my head around this. I could definitely add the logic to where if the profile is 100%, it will display a button. It's just the button functionality that I don't know how to do. Would I write a ajax hook? create a custom module?

Any help would be appreciated!

Thanks!

Hope this will help you.

In Drupal 7 you can use ctools for your requirement.

Just create a ctools link after 100% of profile completeness

Steps

Create link on 100% of profile completeness in the profile page

global $user;
ctools_include('ajax'); // Include the CTools tools that we need.
$entity_type = 'user';
$bundle = 'user';
if (module_exists('pcp')) {//check for 100% completeness
  $check_percentage = pcp_get_complete_percentage_data($entity_type, $bundle, $user);
  if (is_array($check_percentage)) {
    if ($check_percentage['current_percent'] == 100) {//100% of profile completed
      $mail_link = '';
      $mail_link = ctools_ajax_text_button(t("Send Mail"), "send_mail/nojs/$user->uid", t("Send Mail"));
      $link = "
uid . "'>"; //must have unique ID for replacement
      $link .= $mail_link;
      $link .= "";
    }
  }
  return $link;
}

Create menu for callback

$items['send_mail/%ctools_js/%'] = array(
  'title' => '',
  'page callback' => 'send_mail_link',
  'page arguments' => array(1,2),
  'access callback' => TRUE,
  'type' => MENU_CALLBACK,
);....
 return $items;

Send mail callback

function send_mail_link($js, $uid) {
  // Include the CTools tools that we need.
  ctools_include('ajax');
  $output = '';
  if(isset($uid)){
     $output .= 'Mail Sent';//without link
    //Code for sending an email to the administrator
    if(/* mail sent */){
       drupal_set_message('mail sent');
    }
  }
  if ($js) {
    $commands = array();
    $commands[] = ajax_command_html("#send-mail-$uid", $output);
    print ajax_render($commands);
    exit;
  }
  else {
    return $output;
  }
}


How can I show two users what taxonomy terms they have selected in common? I have a taxonomy vocabulary, Hobbies.  Users can select their hobbies from a list of about 300.  Many users select a few dozen hobbies, which makes for an extremely long list.

What I'd like to do is show a special list of those hobbies that the logged-in user has in common with the user being viewed.

I'm using Panels to override the user profile page, so I can easily attach views/content panes, blocks, etc.  I also have access to the logged-in user and the user being viewed through Panels contexts.

Is it possible to use Views to filter out taxonomy values in this way?  If not, how might I show users those terms that they have in common?

You are looking for Taxonomy Filter module

  if vocabulary A is set to be 'filtered' by vocabulary B (which may be
  vocabulary A), then whenever someone views the taxonomy listing of a
  term in vocabulary A they will see a 'filter' menu of terms from
  vocabularies A and B. This allows the visitor to narrow down the
  listing by choosing another term - effectively showing them the
  intersection set of nodes from the two terms.


How to provide a custom option for an exposed filter in Views? I have a site in which members can upload pictures of themselves (imagine a personals site).  Users can upload up to five pictures, and each time they upload a picture, a rule increases the value of a custom field, Number of pictures.

Members can search for other members using a view.  This view has a number of exposed filters.

What I would like to do is add another option, Show members with pictures only.  Ideally, this would be a checkbox.  However, I have no idea how to add such a thing to a view.  I could add the Number of pictures field as an exposed filter, but since this is an integer, users would have to type "1", which is ugly and unintuitive.  How might I start to go about this?

if you are not able to achieve what you need with views default options.
You can create your custom views handler. In this case, it would be a filter handler.

https://api.drupal.org/api/views/handlers!views_handler_filter.inc/group/views_filter_handlers/7

https://drupal.org/node/1239866

Extending views functionallity to provide an approach to your problem


Update node revision time in hook_entity_presave In my site Drupal 8, I have custom entities (say components) and bundles. I load these entities in a node using the Inline entity module.
On the front-end, the contextual links provide two edit links: an edit link to edit the node with all inline entities and a link for a specific entity. When users use the second link, they get the edit page for that entity and its field values. Using the second link, the node last update value won't change.

I tried updating the node value in hook_entity_presave(), but it creates infinite redirection. How do I avoid it?

Make sure you don't call $node->save() in your presave, just update the time, the save will happen automatically.


Is there a module to create incentivized social media marketing conditionals? Currently I'm looking to implement a feature where a user can facebook/twitter share a link or a snippet of text to their social media network and then have drupal capture that feedback to see if they did it or not. From there I want to be able to give them a % discount when purchasing something from my site which is running drupal 7 commerce. Is there something like this built already? if not how would one go about doing this feature?

I've never seen a module that does this.

You're going to have to be pretty familiar with Drupal, Commerce, PHP and the APIs of the platforms you'd like to use.

Because this question is so huge, it's not a good fit for this forum.  This forum is only for asking direct questions, with clearcut answers.


Why is Drupal prepending 'node' to the link URL? I am working on a Drupal site. My issue is that when a link is created either by using the url() or the base_path variable, it works OK on local development environment. But when the very same code is put on the server, the URL prepends node string in the path .

E.g. the path is <drupal site>/latestnews. The generated path is <drupal site>/node/latestnode and when clicked, it shows the page not found error. However I would like to mention that the links work fine (i.e generate correct path) when clicked from the home page.

Any help would be appreciated. If it can help, am using Pantheon hosting for testing.

UPDATE

menu link generation code is as under. (the  code can show my proficiency in drupal :) )

function GetMainMenuItems()
{
    $menu = menu_tree("main-menu");

    $keys = array_keys($menu);

    $count = count($keys);

    unset($keys[$count-1]);
    unset($keys[$count-2]);

    $items = array();

    foreach ($keys as $key) {
        $temp = array(
            'title' => $menu[$key]["#title"],
            'url' =>   url($menu[$key]["#title"])
        );
        $items[] = $temp;
    }
    return $items;
}

the issue (for the current scenario) turned out to be hardcoded link in the page.tpl.php file. the front page was working ok as it had its own custom template but other pages were using the page.tpl template for rendering the links.

seems that sometimes small issues goes undetected. :) . just leaving this answer so that someone else may also look into such a possibility in their case.


Redirecting to external validation page using oauth with drupal_http_request() I'm working on a module to integrate with the Piryx API, and per the OAuth documentation, I should be redirected to an external page where the user can allow access to my application.  The problem is that I'm using drupal_http_request():

$response = drupal_http_request($url, $headers, 'GET', $data);

to get the data, and the page markup is returned in $response['data'] instead of redirecting me to the external page (if I put the URL in my browser, it brings up the page fine).  Is there something I can do to redirect to the external URL so the user can allow access, or do I just somehow need to use the markup to display it in my site?

Thanks.

In the case the request is redirect to a different URL, $response->code is 301, and $response->redirect_url is the redirection URL. If the request is redirect, you can call drupal_http_request() using $response->redirect_url as new URL.

See aggregator_aggregator_fetch() as example of Drupal function that verifies the request is being redirected.

  // Process HTTP response code.
  switch ($result->code) {
    case 304:
      break;
    case 301:
      $feed->url = $result->redirect_url;
      // Do not break here.
    case 200:
    case 302:
    case 307:
      if (!isset($result->data)) {
        $result->data = '';
      }
      if (!isset($result->headers)) {
        $result->headers = array();
      }
      $feed->source_string = $result->data;
      $feed->http_headers = $result->headers;
      break;
    default:
      watchdog('aggregator', 'The feed from %site seems to be broken, due to "%error".', array('%site' => $feed->title, '%error' => $result->code . ' ' . $result->error), WATCHDOG_WARNING);
      drupal_set_message(t('The feed from %site seems to be broken, because of error "%error".', array('%site' => $feed->title, '%error' => $result->code . ' ' . $result->error)));
  }

If you want to redirect the users to $result->redirect_url, and not requesting that URL with drupal_http_request(), you use the following code.

drupal_goto($response->redirect_url, array('absolute' => TRUE));


How do I show product attribute fields in a view? I'm having difficulty with what seems straight forward and have tried many Drupal Commerce extra modules. Can anyone advise on showing product attributes in a add-to-cart form?

I have product types:
- "product" and
- "boat checkout"

And "boat checkout" products:
- 1/2 day
- full day

And node types:
- basic page
- boat
- boat reservation

I'm not able to get boat product attributes showing in the add form nor in the checkout view, despite attribute settings on Despite visibility on /admin/commerce/products/types/boat-checkout/fields.  I'd prefer using a view to keep the site simple (and not creating 2 nodes to display 2 products).

Separately, can product attributes be saved/ shown on orders??  Very hard letting users change or view attributes.

Answer borrowed from my answer over here.

Most straightforward way is to use views to render your product display nodes. Instead of "fields" choose "node" and then choose your display mode. Perhaps use display_suite or panels to get more advanced control over what your products look like when rendered.


Bootstrap theme: editing the registration page I am new to Drupal and wondering how to edit the look and feel of the registration page form? For what it's worth, I'm using the Bootstrap theme. I'd usually do this via CSS; however, with Drupal this is somewhat tricky. The problem is the form fields are expanding to fill their container, and, as you can imagine, it looks pretty ridiculous having a username field filling 3/4 of the screen. Looking at the elements class shows no clues as it is not a standard Bootstrap class (must be Drupal generated I imagine). I have edited the basic page content type in an attempt to make it work - but as I have learnt: the registration page is not styled from basic page. Any help would be great, thanks!

Take a look at drupal api documentation. Customizing forms is quite easy.
https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_form_FORM_ID_alter/7

Just hook into that user_registration_form and for example add into class index bootstrap classes col col-lg-*. Or you can add #prefix and #suffix to wrap things into columns etc. And install Devel module to examine form's structure.

I'm not sure if it possible to use page--user--register.tpl.php to modify layout. Possibly you could create that and add col col-lg-offset-* col-lg-* to whatever element is the container for page[content] variable.


XML-RPC Custom Hooks Request I have developed my own xmlrpc hook, which have certain functions.

Basically I need to call that functions outside Drupal. So I can't use xmlrpc() function.

What is most simple method to call that functions through Drupal's xmlrpc.php?

PHP has an extension for XML-RPC, but it's not enabled by default. If your PHP installation doesn't have the extension, you can use one of the PHP libraries that handle XML-RPC requests, such as XML-RPC for PHP, and The Incutio XML-RPC Library for PHP; if you have downloaded the Zend Framework, you can use its XML-RPC classes.


How can I make a module's configuration exportable by features? At a high level, what needs to be undertaken to take a module's configuration data and make it exportable by Features?

Whether this is a contrib module that does not yet have Features support or a custom module that I have written, where can I start so that I can get it in code?

Instructions are in the Features API.txt, which provides several examples of how to better integrate your module with Features.

The easiest way seems to be building your module around the CTools Export API. Here's a pretty good article explaining how to do that.


Create a custom fieldset template Normal scenario
In a custom form (created using FAPI) I have a fieldset definition:
$company_field_set = [
  '#type'  => 'fieldset',
];

If I would like to customize the fieldset template, I normally would create a hook_theme_suggestions_HOOK_alter function to add suggestions and then overwrite the template.
Alternative
I was wondering though why I wouldn't simply use the #theme key, so I tried this:
$company_field_set = [
  '#type'  => 'fieldset',
  '#theme' => 'my_custom_company_fieldset',
];

This does indeed render my custom template instead of fieldset.html.twig, but I don't get any variables in it. I would expect it to behave just like fieldset.html.twig.
I have tried several theme definitions:
// Same as default fieldset
'my_custom_company_fieldset' => [
  'render element' => 'element',
]

// Another tryout
'my_custom_company_fieldset' => [
  'render element' => 'children',
]

My template currently looks like this:
{% extends 'fieldset.html.twig' %}

I also tried:
{{ children }}

I see the template contents (like static text and such), but no variables.
I think I know a little bit too little about this and am missing something somewhere.
Could anyone point out my mistakes and/or tell me whether or not this is even possible?

After looking a little deeper in the Drupal core I found out that in this case I shouldn't overwrite #theme, but use #theme_wrappers instead.
So my theme definition:
function mymodule_theme($existing, $type, $theme, $path) {
  return [
    'my_custom_fieldset' => [
      'render element' => 'children',
    ],
  ];
}

In my form:
$form['some_fieldset'] = [
  '#type'  => 'fieldset',
  '#title' => 'Some title',
  '#theme_wrappers' => ['my_custom_fieldset'],
];

$form['some_fieldset']['some_field1'] = [
  '#type' => 'textfield',
  '#title' => 'Some title',
];

$form['some_fieldset']['some_field2'] = [
  '#type' => 'textfield',
  '#title' => 'Another title',
];

And then my template my-custom-fieldset.html.twig:
<fieldset>{{children}}</fieldset>

Or for example:
<fieldset>
  {{ children.some_field1 }}
  Some customization here
  {{ children.some_field2 }}
  Something custom here
</fieldset>


How to correctly format a POST request to the file_upload Rest Response? This is my first time posting a StackExchange question, so thanks in advance for your patience.

We are attempting to upload an image to a headless Drupal application using the File Upload REST resource. In testing the endpoint with Postman, we've run into a weird issue. We are able to target the endpoint and upload an image fine through Postman's 'binary' body type, in which you just attach an image to the GUI and it does the rest for you. But if we use the 'raw' body type and pass in the Base64 code for the image, the image entity is created but the actual appears broken in Drupal. According to the linked documentation, it appears the binary data just needs to be passed in directly with the appropriate headers.

So my questions are: Is there a specific way to format or package Base64 image information to upload directly to Drupal? Am I falsely equating Base64 and binary data? Does anyone have any similar experience? Thanks a ton for taking a second to read this.

For context:

Our endpoint in both cases is http://localhost:8000/file/upload/{entity_type_id}/{bundle}/{field_name}?_format=json

And our headers are:

Content-Disposition: file;filename="test.jpg"
Content-Type: application/octet-stream

And when we attempt to preview the image in Drupal after passing the Base64 directly, this is what the preview looks like (an ominous white outlined square on a black background):

Recently I have faced the same issue in a file upload. For this, I have done base64_decode() before the file_save_data() in Drupal.
Example code:

  if (isset($file_data['title']) && isset($file_data['data'])) {
      // Get base64_encode of file data and explode to get data.
      $encodedImgString = explode(',', $file_data['data'], 2)[1];
      // Decode the data.
      $decodedImgString = base64_decode($encodedImgString);
      // Get the file name.
      $file_name = preg_replace('/\\.[^.\\s]{3,4}$/', '', $file_data['title']);*/
      // Save the file using base_decode() data.
      $file = file_save_data($decodedImgString, 'public://' . $file_data['title'], FILE_EXISTS_RENAME);
      $file_result = [
        'target_id' => $file->id(),
        'title' => $file_data['title'],
      ];
    }

Hope this helps you.

Note: Here I have used custom REST API for file uploads.


How can I enable download link in the Media browser library tab My media browser has a list of powerpoint and visio files:

How can I add a download link or preview it next to each file? The idea is to make it easier for user to choose which file they want before saving the content. I am using media module 7x-2.8.

1 Create your view, add the fields you'd like displayed.

2 On the "Content: Video" field settings, choose the "preview" option under formatter - this displays the thumbnail.

3 Add the "Content: Path" field to your view

4 Uncheck the settings for label, check the box for "exclude from display"

5 Click on rewrite results and select "Use Absolute Link"

6 Next you'll need to reorder your fields so that "Content: Path" is above "Content: Video".

7 Edit your Content: Video settings.

8 Go to rewrite results and check "Output This Field as a Link".

9 Put [path] as the link path.

10 Save it.

You are done.


MIssing 'Drush configuration' and 'Php configuration' when running 'Drush status' If a run the method 'drush status' in the terminal I see that the values for  'Drush configuration' and 'Php configuration' are missing.

It give me not problem at all. But is this correct?

Look the capture:

I use the free version of MAMP.

One of my colleagues has MAMP installed and that's what his Drush status looks like too.

I'm using the build of Apache built in to OSX and the only difference I see is that the PHP configuration is filled in:

Like you, neither my colleague or I suffer any problems with these settings missing so I wouldn't worry too much about it.


Can Views output clean URLs from titles with quotes, and other special chars? I have a view that really needs some nice clean URLs; the links are the titles of the content items in the view.

I am pretty sure I have been able to clean up URLs with views before (I could be wrong though), but I just can't seem to find it today.
Removing spaces is simple enough but I need more.

Any help greatly appreciated.

If you are loading nodes they will already have a path associated with them. Assuming you have setup path aliases (url aliases), and potentially url patterns with the pathauto module) for these nodes there will already be a field (Content: Path). This field will contain a clean and tidy url you can add which will give you the path to these nodes.  If you just want the node title to be linked to itself there is an option to 'Link this field to the original piece of content' when you add 'Content: Title'.

tl;dr Try to keep this stuff out of Views and add the relevant fields that are already available.


Drupal 8: how can I "eager load" Entities referenced via EntityReferenceFieldItemList field Note: this is my first Drupal project as I am usually working with Laravel.

I have some entities my-nodes that have a field EntityReferenceFieldItemList (a multi-select linking to other entities of another content type related-nodes).

I want to query the my-nodes entities together with the related entities in 1 query (in Laravel I would describe this as eager loading the relationship).

The my-nodes entities all reference different related-nodes entities and I need to access related-nodes related values.

I'd like to optimize the amount of calls to the database to possibly only 1.

Method referencedEntities does not look like what I need because it's lazy loading, not eager loading:

$node->get($field)->referencedEntities();

Any idea?
Thanks in advance!

This doesn't exist in Drupal, you can't load entities of different types at once, the best you can do is load all referenced entities of the same type at once, which is what referencedEntities() does.

Each entity type has its own storage handler which doesn't know anything about other entity types, as far as those handlers are concerned, those other entities might not even be in the database but stored in MongoDB or text files.


I want to uninstall l10n_client which may be duplicated I use composer.
The L10n_client module could not be updated or occasionally not found.
I feel that the names of L10n_client or l10n_client_ui are different.
It is a similar atmosphere as below.
https://www.drupal.org/node/2658756
I do not know if it is the same cause.
Since Composer update can not be done, I have memories that I executed composer require as override.

I got a message to install the l10n_client module under some circumstances, so I ran the installation on admin/modules, but an error was returned.
Localization Client Interface The module is unchecked.
Localization Client Contributor module is not installed.
Error message is ‘Unable to install Localization Client Interface, l10n_client_ui.settings already exists in active configuration.’

How can I solve it?

Environment:Drupal 8.4.2

I ran "drush config-delete l10n_client_ui.settings".
I was able to install the module.


Automatically Generate PDF from Webform Submission First off, this is under Drupal 7.  I'm looking to have the server save a PDF of the submitted webform when a user submits it or updates it (overwriting the old one on update).  So far I've had no success with fill2pdf, views pdf, or entity print modules in getting this accomplished.

I do have the Print module working where I can click a link and download the PDF, but that's only if I take the action.

I figure the easiest way at this point would just be to have a Rules action execute some custom PHP code using the PDF that the Print module is generating.

I'm just not sure what that code would look like.  Basically, upon submission, the Rule would Execute Custom PHP code.  That code would user the PDF generated by the URL (www.example.com/printpdf/[nid]/submission[sid]) and would save that file to a location on the server (going to that URL would save it on the user's local machine) that I would like to use some tokens from the webform for (private files/year/username/node title.pdf).  Preferrably this would all be done in the background so the user wouldn't see it, but if that's not possible redirect the user after saving the webform.

Anyone know how I can accomplish this?  Thanks!

It seems like the entity_print module does exactly what you want.

From the docs:

  Entity Print allows you to print any Drupal entity (Drupal 7 and 8) or View (Drupal 8 only) to PDF.

The module is weel maintained with more then 5K websites using it.


Using multiple taxonomy vocabularies for views filters I need to display nodes in a view, based on a combination of multiple taxonomy terms, in multiple vocabularies.  For example, for car sales, one vocabulary lets the visitor select one or more colors, and another selects one or more model types.

I assume I can do this by exposing filters, but how do I group them as check boxes in a sidebar instead of on top of the view?

In the "Advanced" section of your view settings, select Yes for the "Exposed form in block" setting.

Then there will be a block available for your view, which you can assign using drupal core blocks, context, panels, etc.


How to make content private and only for certain roles to see I have a content type called collection and 2 user roles: role1 and role2. role1 users can create collections. What I want to do is to allow role1 users to indicate whether they want their collection remain private (in which case only logged in users and hence role2 users can see it) or let it remain public, in which case anonymous users can see the content. Each collection is really just a collection of pictures. I am using Drupal 6.

There are a couple options (and more, I'm sure):

http://drupal.org/project/nodeaccess (easier to set up, but more manually intensive for the end user)

or

http://drupal.org/project/taxonomy_access (a little bit more to set up, but easier on ur end users)


Drupal admin menu on/off issue I am using drupal 7 . I am having issue with drupal admin menu. When I open new menu this time admin menu disappear and after refresh this page 2-3 times then menu display.

It's cache issue of admin menu, you should disable the caching on client side.

You can do it here: /admin/config/administration/admin_menu, under Performance tab.


Offset problem in Drupal 7 I want to use the Views module to display the top item from a listing.

I've utilized the "Use Pager" to display that one item. But sometimes I want to display the second item, or third item, or X item. I've found the offset option to skip the first item, but the result I get doesn't seem to match. What I get instead is some random item, and not, say, the second item.

Any suggestions?

Did you accidentally enable random ordering as well? In a randomly ordered list, the second item will always be random as well.

If this is not the case, please provide more information about the configuration of your view. Two ways of doing this are to make a screen shot of the edit form, and to upload the exported view to http://pastebin.com.


How can I get the saved value in the variable table to show on a form? I have a form that gets values set in the variable table if any have been submitted. All of the fields work as expected except a radios field, which always shows the default. Here's the relevant code

$one = variable_get('one', array());

$form['one']['visibility'] = array(
 '#type' => 'radios',
 '#title' => t('The title'),
 '#options' => array(0 => t('Yes'), 1 => t('No')),
 '#default_value' => (!empty($one['visibility']))
 ? $one['visibility']
 : 1,
);

I had thought that keying the options array with strings would solve this but it doesn't. I'm still Googling, but I'm wondering if there's something easy I'm missing.

You'll have to refer to the Form API docs for radios for tips.

Second, it might make things easier to reason about if you do:

$one = variable_get('one', array('visibility' => 0));
$is_visible = $one['visibility'];

$form['one']['visibility'] = array(
 '#type' => 'radios',
 '#title' => t('The title'),
 '#options' => array(0 => t('Yes'), 1 => t('No')),
 '#default_value' => $is_visible,
);


Is there a way to set up a default layout for a scholar site in Open Scholar? I would like new scholar sites to have a specific widget found in the Open Scholar layout editor set in a certain region. Is it possible to set up/change the default template for the layout of scholar sites?

Assuming you're using the web-based installer here, it is possible to update this but you're going to have to do it by editing the install profile script. In your sites directory, you're looking for the file:

/docroot/profiles/openscholar/openscholar.profile

You're going to want to add a function, openscholar_profile_final() here (following this guide: http://drupal.org/node/67921) and add a function to add your blocks in:

db_query("INSERT INTO {blocks} VALUES ('blockname', '0', 1, 0, 1, 0, 0, 1, 'my*', '')");


Store credit card details I've built website using drupal 7. Site is having store of products, for transactions using commerce, commerce_payflow_pro modules.
Requirement:
Store -> Orders table not containing used credit card details i.e. last 4 digit of credit card number, used to place transaction & card type used to place the transaction.

Please suggest solution.

Commerce Card on File module was built exactly to solve this purpose!

  Commerce Card on File provides an API and user interface for storing and reusing credit card data on subsequent orders within Drupal Commerce. The module does not retain full card numbers locally but instead stores the remote ID of the full card data from the payment gateway used to validate and process your credit card transactions. This means card on file data will only be good for a single payment gateway; if you change payment gateways or accounts, your stored card data may no longer be usable.


List of nodes that have no taxonomy terms I'm maintaining a D6 project, where the customer wants to see a list of nodes where no taxonomy terms were added.

I want to solve this with views. I already tried some Filter settings for that, but nothing worked so far.

I would know the solution in D7 with Views 3 but in this case I can't get rid of this problem.

Try this:
1. create a node view
2. in 'Fields', add 'Node: nid'
3. in 'Relationships', add 'Taxonomy: Node'
4. in 'Filters', add 'Taxonomy: Vocabulary', in next step, choose 'Is empty (NULL)' as the operator.
5. test some of the nids given in the preview to see if they are the ones you are looking for, you might need to tweak a little the usage of relationship.
Step #3 is here to give you extra operators to choose from.

update

Okay the above assumes the content type only has one term field, so nevermind...
Now that I understand the issue better, I think you will probably need views_or module. Also we don't need 'relationship' anymore.

On my test Views, I use filter 'taxonomy:term(term id)' for each vocabulary, chain them together via Views_or. Set them to dropdown with hierarchy. Then highlight all terms in the vocab and check 'is none of' for the operator on the left. It's a very ugly query but that's the only way I got it to work...You'd better cache it for a better performance. I attached some screenshots hope to clarify the config part.


Why can't I programatically create a location field in a node? I'm trying to programmatically create a node with a location field, but I'm not able to do it. I have done it in a similar project and it works fine. I use the Entity API module to create the nodes, with this code.

 $localizationmap = array(
   'latitude' => $item['field_mapa']['latitude'],
   'longitude' => $item['field_mapa']['longitude'],
   //other elements added here (province, postal_code, country [es, en,...],additional, ...)
 );
 $entity->field_mapa->set($localizationmap);

I checked the values that are given to the array and they're OK.
Drupal log contains the following error:

  EntityMetadataWrapperException: Unknown data property field_mapa. en
  EntityStructureWrapper->getPropertyInfo() (línea 335 de
  /var/www/vhosts/drupal/litoral.interdigital.biz/sites/all/modules/entity/includes/entity.wrapper.inc).

field_mapa exists and it is the name of the location field I'm trying to fill.

What am I doing wrong?

It's simply because the stable version of the Location module doesn't support Entity API.

There's a patch here that claims to provide the missing support, obviously use with caution on a dev version of the site first.


How to translate a custom module template file? How do I translate a custom module theme file?

function bonds_graph_theme($existing, $type, $theme, $path)
{
    $items = array();

    $items[BONDS_GRAPH_MODULE_NAME] = array(
   'arguments' => array(),
   'file' => 'inc/theme.inc',
   'template' => 'tpl/bonds_graph',
 );

return $items;
}

The theme file has a translatable string

<?php print date('Y') . ' ' . t('Issuance'); ?>

The language file zh-hans.po has the translation

#: tpl/bonds_graph.tpl.php:7
msgid "Issuance"
msgstr "发行"

The site language is set. How do I get the string translated?

The .po file must be located in custom_module/translations directory - see locale_batch_by_component function. Translation file though is only imported once module gets installed, so in case you want to reimport the file you would have to run some "hacky" drush command, such as drush php-eval "locale_system_update(array('custom_module'));drush_backend_batch_process();"

You can also upload .po file manually using Drupal's admin UI.


Drupal 7 inserting space before inline HTML tags upon rendering Whenever I try to use , , , or  tags (or probably any other inline tag), Drupal inserts a space before the HTML tag. This does not happen within the node but rather upon the HTML rendering.

For instance:

2342 in the body field

is rendered as

234 2 on the page

Any idea why this would be or what I can do to eliminate the space that is being added? I have TinyMCE installed on the site, but (long story) it is disabled so that I input everything in raw HTML.

If you use "Full HTML" text input rather than "Filtered HTML", then Drupal won't parse or modify your markup.


Multiple Field , same ajax callback I created a custom field. The hook_field_widget_form has an submit element with an ajax callback:

  //Add more
  $element['add_zone'] = array(
    '#type' => 'submit',
    '#name' => $field_name . '-add_more-' .'name',
    '#value' => t('+'),
    '#limit_validation_errors' => array(),
    '#submit' => array('dms_polygone_add_more_add_one'),
    '#ajax' => array(
      'callback' => 'dms_polygone_add_more_callback',
      'wrapper' => 'zones-fieldset-wrapper-'. $field_name,
    ),
  );

I add 2 fields of my custom field type to a node. Ex: field_polygone (field type: polygone) and field_polygone_2 (field type: polygone).
When i press the 'add_more' button of my first field_polygone, my callback function 'dms_polygone_add_more_add_one' thinks the trigger element is field_polygone_2.

Callback function:

function dms_polygone_add_more_callback($form, $form_state) {
  //@todo: $i gebruiken voor veld als er meerdere waardes zijn toegestaan.
  $parents = $form_state['triggering_element']['#parents'];
  return $form[$parents[0]][$parents[1]][$parents[2]]['zones'];
}

$parents[0] is the field_name => When i press 'add_more' , the $parents[0] variable in the callback function should be 'field_polygone', but its field 'field_polygone_2'.

How can is solve this problem? Why does the callback function think the trigger element is field_polygone_2 instead of field_polygone.

I had a similar issue in Drupal 8. I had one form with multiple entities (not drupal entities) that had an identical subset of fields and each had their own button. My $form_state->getTriggeringElement() would always show the last of these buttons, no matter which I clicked. My issue was that I was not setting #name on the buttons and they were both defaulting to op (they had the same #name value). Explicitly setting a unique #name for each button resolved my issue.


How to implement the two categories of the same content type to automatically generate a new aggregation page? example: there are two taxonomy fields of each article, a taxonomy is regional, another is the attribute，I want to achieve the "regional + attribute = regional attribute" automatically generated such a new aggregation page.

Create a new view, go to admin/structure/views/add

Show: Content of type: All

✅ Create a page

Display Format: Unformatted List of: Fields

Save and Edit

Now in your view, Click on Advanced (located in the right side).

RELATIONSHIPS click add

Select ✅ Taxonomy terms on node

For Vocabularies checkmark your vocabs and then checkmark ✅ require relationship.

Then in FILTER CRITERIA add Has taxonomy term

✅ Autocomplete, then type regional, attribute.


How can access the Question from its Course when using the E-learning module? I am using Drupal 7 and I have installed the "E-learning" module.

I have created these items:

a Question.
an Exercise (which includes the Question).
a Unit (which includes an Exercise).
a Course (which includes the Unit).

How can access the Question from the Course I have created?

This module creates an hierarchical structure COURSE > UNIT > EXERCISE > QUESTION.

These are entity types connected with each other using an Entity Reference field. You can attach and reuse different units to each course, different exercises to each unit, etc.

So to access the Question from the Course, you follow the "links" that are created via the Entity Reference field. Obviously, for that you must first have entered the data (entity references) for each Question (and its related Exercise), and for each Exercise (and its related Unit), etc.


Force render the block programmatically? Is it possible? For example, if the module's block meets your needs but it a block (not a page) and you want to use ready solution. Writing in a tpl.php file something like render(desired_block), i.e. to get an output markup of the block for reuse.

Not sure what version of Drupal you are using but here is how I rendered a block in drupal 7.

<?php
  $block = block_load('MODULE_NAME', 'DELTA');
  $output = drupal_render(_block_get_renderable_array(_block_render_blocks(array($block))));
  print $output;
?>


How to add section titles to group fields in content type input form used to create content? Is there a module or setting to provide a title to sections of the content type input form used to create content?

For example - a job application form would have sections:

Section Title: Your Details
- Name
- Address

Section Title: Previous Employment
- Employer etc

Section Title: Qualifications

Happy to consider writing a custom module to output HTML and CSS to do this but wondered if there was a module or setting.

I'm currently using display_suite to do some layout design of the form in-browser.

(I've done some research and have seen https://drupal.org/project/multistep module but I would prefer all the sections on one page at the moment, that module may be useful for something else, though. Also aware of https://drupal.org/project/field_group which I expect to use but not sure if it provides titling above the field group).

Field Group module is best solution. It will allow you titling above the field group.

Fieldgroup will, as the name implies, group fields together. All fieldable entities will have the possibility to add groups to wrap their fields together. Fieldgroup comes with default HTML wrappers like vertical tabs, horizontal tabs, accordions, fieldsets or div wrappers.


Can I use another entity in the route to provide an entity to an entity form? I am working on a custom content entity that I want to 'link' to a user by adding it as a tab to the user profile. Each user can have one such entity.

My route is defined as follows:

entity.my_entity.edit_form:
  path: '/user/{user}/my_entity'
  defaults:
    _entity_form: my_entity.edit
    _title: 'Edit entity'
  requirements:
    _entity_access: my_entity.update
  options:
    user: \d+

And the tab (module.links.task.yml):

entity.my_entity.edit_form:
  route_name: entity.my_entity.edit_form
  base_route: entity.user.canonical
  title: Entity

Though this works and the tabs show up, they result in a fatal error (cannot return getValue() on null from the getters) presumably because the form does not have an assigned entity.

If I change the route path to /user/{user}/my_entity/{my_entity}, the form works, but I cannot create a tab as the last value is unknown to the routing system.

Can I use the provided user entity instead from the route instead and during the building of the entity form retrieve (and set) the entity I need?

You can use a controller with the user as only route parameter. There you can put the code to retrieve the entity that matches the user and build the entity form:

public function myEntityForm(UserInterface $user) {

  // get $my_entity that matches $user

  $form = $this->entityFormBuilder()->getForm($my_entity);

  return $form;
}


How can I use Html::getUniqueID? The Drupal Twig clean_id filter calls HTML::getId(), which is inferior because accessibility tests fail if your ID appears twice, for example when the template is placed twice on a page. In the vast majority of cases, if you're generating an ID in Twig you really need to be guaranteeing uniqueness.
Hard to believe Drupal doesn't support this out of the box.

The purpose of the clean_id filter isn't providing a unique ID, but removing from the string used as HTML ID the characters that aren't allowed. Basing on 6.2 SGML basic types HTML IDs can only contain letters, digits, hyphens, underscores, and colons.
Html::getUniqueId() itself uses Html::getId().
// If this is an Ajax request, then content returned by this page request
// will be merged with content already on the base page. The HTML IDs must
// be unique for the fully merged content. Therefore use unique IDs.
if (static::$isAjax) {
  return static::getId($id) . '--' . Crypt::randomBytesBase64(8);
}

// @todo Remove all that code once we switch over to random IDs only,
// see https://www.drupal.org/node/1090592.
if (!isset(static::$seenIdsInit)) {
  static::$seenIdsInit = [];
}
if (!isset(static::$seenIds)) {
  static::$seenIds = static::$seenIdsInit;
}
$id = static::getId($id);

The documentation page for Html::getId() says it should be used only when the ID doesn't need to be unique.
For the cases where the ID needs to be unique, Drupal core modules set a variable passed to the template file, which is what's done in template_preprocess_pager(), template_preprocess_block(), or template_preprocess_views_view_table(), for example.
variables['heading_id'] = Html::getUniqueId('pagination-heading');

// Create a valid HTML ID and make sure it is unique.
if (!empty($variables['elements']['#id'])) {
  $variables['attributes']['id'] = Html::getUniqueId('block-' . $variables['elements']['#id']);
}

// Improves accessibility of complex tables.
$variables['header'][$field]['attributes']['id'] = Html::getUniqueId('view-' . $field . '-table-column');

Since Drupal core doesn't have a Twig filter that returns a unique ID, that is the only way to obtain one: Set a variable in a preprocess function used for the template file with the value returned from Html::getUniqueId(), and use that variable where the template file needs a unique ID.


Text field formatter with link to the entity? I have a text field that I use to store an entity title.
It is not the "native" entity title, but just a field named field_title.

Now I want to display this text field as a link to the entity (e.g. product/123).
(I am working with Display Suite here, but the question is not limited to that)

I know I could simply create a custom formatter for this. But isn't there an easier way? I think I even did this once, just can't remember.

I also found the Field Value Link Formatter module , but this doesn't seem to be it.

EDIT: There are some known solutions like DS custom fields, or Custom Formatters, or hook_field_formatter_info() in a custom module, or node template override, or field template override, or the awesome hook_ds_field_theme_functions_info().

However: This seems such a recurring use case that I consider to write a new (reusable) module and publish it. So, I am looking for a solution so easy that it invalidates the desire to write a new module :) I think I saw something like this once, just can't remember.

you could do this with a Display Suite custom field and use the tokens to build the link.

I would do it like that if I wouldn't like to write a custom template. Or, as already mentioned, create a template for that node. Due to the fact that you don't use the native title, you will have it available in the node template and you can change the markup there.


Caching issue with View and anonymous users Our site uses Views heavily and unfortunately we've got a caching problem.

On our front page we've got a View that only shows content whose publishing date is more recent than the current date. So if we post an article whose publishing date is 2 hours from now, it should be visible in two hours from now on.

This works fine for logged in users. But the majority of our visitors doesn't have an account. And when not logged in the article gets published seemingly at random. It could be visible 20 minutes or 1 hour past the desired date.

The View has got no caching enabled. Site wide we've got the following options enabled:

Caching mode: normal
Page compression
Block caching
CSS caching
JavaScript caching

Do you have some hints regarding our problem? I'm using Drupal 6.

Here is a small hack to prevent some pages from being cached for anonymous users:

// Prevents frontpage caching
if (drupal_is_front_page()) {
  $GLOBALS['conf']['cache'] = FALSE;
}

Hope this helps, cheers!


Commerce module in not drupal commerce I have a website, built as a non Drupal commerce website. I want to add functionality to my website so customers can buy books, and add checkout page and cart.
I mean add commerce functionality in a not Drupal commerce site.

Can I do that?

Yes that is possible. Download the modules from: https://www.drupal.org/project/commerce

You can not install the install profile (https://www.drupal.org/project/commerce_kickstart) on top of an existing Drupal website.


altering them for node edit page not working I got the following to work by adding it to the admin template.php file. But I am not having any luck changing the one edit form to use boostrap_subtheme vs the default admin theme. Any advice with that? To add a little more to this, I am using the following code to set the add node for data set to the default theme, how would you do this for a node edit page?  The url for the node edit page contains the node id.

function mymodule_menu_alter(&$items){
    $items['node/add/data-set']['theme callback'] = 'mm_get_default_theme';

}

function mm_get_default_theme(){
    return variable_get('theme_default', '0');
}

I am using the hook_theme() function to override the theme for a given node's edit form. This works when you create a new node but does not override the theme with the use clicks "edit". Any ideas? Path of the edit form is for instance node/39/edit.

$items['custom_node_form'] = array(
  'arguments' => array('form' => NULL),
  'render element' => 'form',
  'path' => drupal_get_path('theme', 'bootstrap_subtheme') . '/templates',
  'template' => 'custom-node-form',
);

Its working on my site, although i haven't made a template but it should work with a template too. here is my code

function modulename_theme(){
     $items['article_node_form'] = array(
    'arguments' => array('form' => NULL),
    'render element' => 'form',
  );
    return $items;
}
function theme_article_node_form(&$var){
    $form=$var['form'];
    $output = '<h2>' . t('Please enter your information below') . '</h2>';
    $output .= drupal_render_children($form);
    return $output;

}


How to programatically get the product id of newly added product using the commerce form I allow users to create their own products using the default commerce product add form (/admin/commerce/products/add/product). Programatically, I need to get the product ID and do more processing.

I have a submit handler attached like this (I use it to redirect users to a custom page):

$form['actions']['submit']['#submit'][] = 'my_module_redirect_handler';

However, I don't seem to have any information about the newly added node. How can I obtain it?

Provided that your additional submit handler is invoked after default one (which by looking how you added it, is the case), you can access nid of the node created as follows:

function my_module_redirect_handler(&$form, &$form_state) {
    $node_id = $form_state['values']['nid'];
}

Now that you have nid you should be able to do required processing.

Hope that helps.


Can I setup a backup migrate schedule from settings.php I am using Pantheon to host a development, staging and production drupal 7 site.  I have backup migrate module setup to perform period backups. When I migrate the production site's content to the staging site for testing of new features, the backup migrate settings come with, and all of sudden I now have both production and staging servers backing up to a remote server.  I don't mind having to delete the schedules every time I perform the migration, however I'd hate to write this step into the SOP for other developers as they come on the project.  So is there a way to setup a backup migrate schedule in settings php?  My only thought is to add some config variables in settings.php, and then create a custom module that builds a backup migrate schedule based on these config variables.  I feel like there could be a more elegant solution than this.  Any thoughts?

Thanks

According to this thread (the first part is about the Environment Indicator module but the last part is about Backup and Migrate), Pantheon forbids the use of the Backup and Migrate module on their platform.  While it is possible to make Backup and Migrate settings exportable, including for use in settings.php, it's probably best not to violate your web host's policies.

That said, Pantheon should really start writing their rules down clearly somewhere.


What can I remove after install of Drupal 7 What files and folders can I remove after I have installed Drupal 7
My installation uses SQLite
In order to make the total package as small as possible I have removed unused themes from the root themes directory but what else can I remove?
Can I remove modules from te root modules directory that I will not be using e.g. Aggregator, Forums etc?

Theoretically, yes if it's not enabled you can remove it... but why? You're not really saving a lot of space.


Unable to add content in panelized page as administrator, how to overcome? I'm Unable to add content to panelized page as a administrator. Is there any configuration hidden to overcome this?

An Ajax error pops up showing You are not authorized to access this page.

Only Uid=1(super user) has access to add content to the panelized pages.

  How to make other administrator users also have access to add content?

Only page content type is panelized.

Image:

Permissions

You might want to go to admin/user/permissions, and see if admin has access to add content.

You might want to see this page Permissions issue

It might be a drupal core issue because it works in drupal 7.5


How to make loadByProperties or entityQuery case sensitive for field value Neither loadByProperties or entityQuery are case sensitive. How to make it case sensitive? I'm using MySQL as a database but would rather have a portable solution if possible.
With LoadByProperty
$nodes = $this->entityTypeManager()
              ->getStorage('node')
              ->loadByProperties(['field_myfield' => $value]);

With entityQuery
    $entity_ids = \Drupal::entityQuery('node')
        ->condition('field_myfield',$value)
        ->execute();

You can, of course, build your own query as explained in this answer. But my question is specifically about using loadByProperties or entityQuery API.

It was this long issue thread, they add sensitive case support to entityQuery.
So instead of = operation you can use = BINARY or instead of LIKE you can use LIKE BINARY.
Try this:
$entity_ids = \Drupal::entityQuery('node')
  ->condition('field_myfield',$value, '= BINARY')
  ->execute();


Display Suite: Panel layouts in doesn't appear in "Manage fields" I can select panel layouts using display suite in the manage display tab, but only display suite layouts are available in the manage fields tab but none of the panels layouts are.

Can you please help me with this problem?

The Manage Fields tab is used for arranging fields for the Node Add/Edit form, as well as to Add/Edit/Remove fields to the Node/Entity.

If you want to use Panels for the layout of your Node Add/Edit forms, then you would do this through the Panels Interface by enabling and editing the Node add/edit form Panel that comes included when you install Panels. You would create variants in this Panel to handle the layouts for each content type you have. Hope that can help.


Customising the print stylesheet for the print module I Would like to customise the http://drupal.org/project/print style sheet.

In the readme file it says: - To modify the template of printer friendly pages, simply edit the
print.tpl.php or the css/print.css files.

Re: css/print.css
Does it refer to the print.css inside the print module or inside my theme? If inside the module, wouldn't this make the maintenance difficult when the module needs updating?

Though I haven't worked with print module but as per Drupal structure, if you have to override any CSS file(in your case print.css) of some module, you can simply write your style in your own CSS file which stay in your theme directory. But if you want to use the same file & keep your styling separate then simply cut that from the module directory & paste in your theme directory...mention the CSS file in your INFO of theme...and extend it as much as you want...

Don't forget to clear your cache after you do cut/paste & done with INFO file edit..

In same way...you can copy your print.tpl.php file from the module folder & paste in your theme directory(no need to mention tpl in INFO file)...& then you can do as much editing as you want to have custom look...clear your cache in this case too..

I hope this will solve your worry about maintenance as you will get this file in your theme folder itself...


Single language site other than English What is the best approach of having a single language non-English site? I am thinking of performance mostly.

I dont want prefix or suffix in urls. I dont preferably want entity language (Language neutral possible in D?)

Adding a second language, deleting English? Will this have implications?

For a Single Language non English site, When you install Drupal 7, it gives you option of selecting the Language. Plus you will need to download the language PO files for your language.

But if you are using Drupal 8 the only requirement is selecting correct language when you install your Drupal. Drupal 8 will automatically download all the language files for you.


Twig find if a css class exists in a tag Is there a way to find out if a css class exists in a specific tag through twig?
For example:
<body class="new-class">

Then I'm able to do a conditional statement in twig based if new-class exists.
Is this possible?

You could use hasClass to find the CSS class in a specific tag
eg. {% if body.attributes.hasClass('new-class') %}


Writing a news ticker module. It works, but it's sloppy as hell. Is there a better way to do this query? I've got three pre-existing websites that use the story module, the path module, and CCK to produce customized news stories in Drupal 6. I wanted to create a news ticker module, to consolidate the news from all three sites, and replace the per site views based approach we're using now.

Studied the entire schema that the sites use, and dissected Drupal to see if there was a relatively straight forward way to do this. Turns out, there isn't. Architecturally, Drupal is all over the place.

So what I came up with was a situation where I do a crazy join between the nodes table and the the url_alias table, then union the whole thing together because the tables are identical between schemas.

Like this:

            SELECT
                   'site1' as disposition,
                   url_alias.dst as destination_url,
                   node.sticky,
                   node.promote,
                   node.created
              FROM    site1.node node
                   INNER JOIN
                      site1.url_alias url_alias

                   ON (node.nid = substring(url_alias.src,6,15) )

              WHERE substring(url_alias.dst,1,5) = 'news/'

              UNION

              SELECT
              'site2'  as disposition,
              url_alias.dst as destination_url,
                   node.sticky,
                   node.promote,
                   node.created
              FROM    site2.node node
                   INNER JOIN
                      site2.url_alias url_alias

                   ON (node.nid = substring(url_alias.src,6,15) )

              WHERE substring(url_alias.dst,1,5) = 'news/'

              UNION

              SELECT

              'site3'  as disposition,
              url_alias.dst as destination_url,
                   node.sticky,
                   node.promote,
                   node.created
              FROM    site3.node node
                   INNER JOIN
                      site3.url_alias url_alias

                   ON (node.nid = substring(url_alias.src,6,15) )

              WHERE substring(url_alias.dst,1,5) = 'news/'

              ORDER BY 4 DESC

But it seems to me that this is incredibly sloppy, and that there has to be a better way to do basically the same thing by depending on correctly formed relationships and keys, rather than using SUBSTRING to parse url aliases.

What do you think?

Two things jump out at me, both related to the use of {url_alias}:

I don't see why you need to do the string shenanigans in the WHERE.  You should be able to to use node.type to limit yourself to the subset of nodes you want, especially if you are primarily using Pathauto settings.
I don't see why you explicitly need to return url_alias.dst in the result set. If you have the nid, then you can just use $path = url('node/' . $nid); to build up paths (or use l()).

I think this means that you should be able to eliminate the JOIN on the {url_alias} altogether, which should make the query much faster.


How can I check which nodes have the highest value in a certain field? My content type 'Article' has an integer field called 'Ranking'. How can I check which nodes have the three highest values after saving a new node or comment? I'd like to use the result in a rule, so I'm looking for some kind of "The node has ranking 1/2/3" condition.

Any ideas how I can achieve this?

If within your Computed Field you've selected Store value in the database, you can easily use Views to sort results based upon this field.

So, for example, in broad strokes, you could create a View that filtered on whatever you needed, most probably published and node type; then for sort, you would select this field and select descending; in paging, you'd select a specific number, eg, 3; and in fields, you'd select whatever you wanted to display.

If you wanted to have a block of the top three nodes, in the fields I could see you selecting the title and so forth, but if you are wanting to see if a specific node was in the top three, I'd just put the node nid in there.

So, if that's the case, when this View is run, it will return three nids.

If you look into views_get_view_result() you can quite easily access that output, eg:

$result=views_get_view_result('top_three'); // or whatever the name of the view is

will populate $result with something along these lines:

Array
(
    [0] => stdClass Object
        (
            [nid] => 2340
            [node_created] => 1390349535
        )

    [1] => stdClass Object
        (
            [nid] => 1176
            [node_created] => 1390086303
        )

    [2] => stdClass Object
        (
            [nid] => 1133
            [node_created] => 1390086313
        )

)

So, now you just have to look in there to see if your current nid is in there and if so, act accordingly.

Now, of course, the other question is where to put all of this?  I'd suggest looking into hook_node_update() but be aware of the performance considerations of doing all of this each time a node is updated.  Caching is certainly your friend here.


I want to do something after users voted I want to do something after users voted. I know I can do it by using hook_nodeapi('view') , but I just want to add my action while a vote is being inserted in the database table. How can I do that?

You're most probably after VoteAPI integration with Rules: Voting Rules

It enables you to configure actions to occur when a user submits a vote, when a user deletes a vote, and when the results of a vote are calculated. Currently, Voting Rules supports votes on nodes, users, and comments.


AJAX Replace on Select I've been trying to get an answer to the following question AJAX dependent select. However I think I'm compounding to many concepts. Perhaps I should first master the FAPI AJAX before building upon it. I can not get the following to work properly. After selecting an option I get the drupal clock like it's going to re-render the text field however nothing happens and the value does not change. Where am I going wrong?

function main_iosupload_form($form, &$form_state) {
//Define SQL Lookup Query
  $sqlplatform = "SELECT vid, name FROM {taxonomy_vocabulary} WHERE vid >= 4";

  $result = db_query($sqlplatform);
  $options = array();
    foreach ($result as $row) {
      $options[$row->vid] = t($row->name);
    }

$form['platform'] = array(
  '#type' => 'select',
  '#title' => t('Select a Platform'),
  '#options' => array(
    0 => t('- Select -')) + $options,
  '#default_value' =>  0,
  '#required' => TRUE,
  '#ajax' => array(
    'callback' => 'ajax_select_callback',
    'wrapper' => 'replace_model_div',
    'effect' => 'fade',
   ),
);

$form['model_wrapper'] = array(
  '#type' => 'textfield',
  '#default_value' => (!empty($form_state['values']['platform']) ? $form_state['values']['platform'] : t("Intial Value")),
  '#prefix' => '
',
  '#suffix' => '
',
);

return $form;
}
function ajax_select_callback($form, $form_state) {
  return $form['model_wraper'];
}

Almost a whole week of hitting my head on this. Yeah it helps if in the callback function I call back the correct form name... sigh


Entity query on custom entity is not checking access rights I have a custom entity called project_member. Not all user have access to this entity. But when I query this entity with entityQuery as follows
\Drupal::entityQuery('project_member')->execute()
all the entities are returning. It is not checking the access rights. I am missing anything. I tried to implement hook_project_member_access() to restrict the access still entityQuery is not checking those access results.

You will need to implement hook_query_ENTITY_TYPE_access_alter  ( hook_query_project_member_access_alter) to apply the custom query access check.
For example https://api.drupal.org/api/drupal/core%21modules%21node%21node.module/function/node_query_node_access_alter/8.9.x
You might need to $query->addTag(‘project_member_access’) but from memory that tag may now be added automatically by the entity query handler.


Add taxonomy terms list to homepage Please help me to add taxonomy terms from custom taxonomy into home page. I have no idea how to do this as I'm coming from WordPress. In WordPress it is easy as calling get_terms().
I have following file as my home page: mytheme/templates/page--front.html.twig

I have more than one taxonomy type and all of them are going to queried in the home page.

How to query the taxonomy terms?

UPDATE:

I have created a new region called home_content in my theme.info.yml and I have created a view(block) for getting the taxonomy terms, added it to region in back-end and display it as {{page.home_content}}. It works but I have few questions.

I have fields for logo and text in the taxonomy. I want to list them too.
I need to customize the html. How can I do that?

Thanks for the support.

Just create a view and list out taxonomy terms. Then display the view in front page.

Need to place view in page--front.html.twig.

Use Twig tweak module.

<dd>{{ drupal_view('view_name', 'page_1') }}</dd>

For Block

{{ drupal_view('view_name', 'block_1') }}


Drupal modules to help with user story Hey my team is planning on moving our current project to Drupal and we're looking for what modules would help with our current functionalities. Here's a user story for more insight:

"User 1 has an inventory of items. Each item has a certain number of "points" attached to it. User 2 desires an item from User 1's inventory and has the appropriate amount of points to give User 1 for the item. An transaction occurs in which the desired item from User 1's inventory is sold to User 2 and the corresponding amount of points for the item are deducted from User 2's total points and added to User 1's point total."

I'm thinking we might have to end up adding our own custom code but if anyone knows of a Drupal module or anything that would make things easier, that would be greatly appreciated.

While custom code seems to be good option to achieve the transaction of item ownership, User Points module may help in transaction of items.

In custom way I would have created item as content type with user reference field for item ownership, I would have turned on revision on item content type so to get detailed report of transfer of ownership and on every transaction of item would have updated the ownership field with new owner, maintaining the revisions. User Points module provides handy api's custom integration and it also provides rules integration which looks more robust system to expand user points in future also.


Different logo on specific page / node I have a special page called www.mydomain.com/special (whcih is a page node type). Only on that specific page, I want an extra image in the header of that page (next to the logo)

The logo and sublogo's is contained in the page.tpl.php provided by the previous themer.

What I would like to add in the page.tpl.php is somthing like:

if I am on page xyz

extra logo

endif

It this possible or am I totally wrong?

If you know the node NID of this special page, it would be a quick...

<?php if ($_GET['q']=='node/NID'): ?>

extra logo

<?php endif; ?>

...in your page.tpl.php file.  You could also create a special template for this node:

page--NID.tpl.php // for Drupal 7
page-NID.tpl.php  // for Drupal 6

...and have it in there all the time.

If you want to make sure that www.example.com/special uses a special template regardless of what node/NID it is really, eg, special is really an alias for node/6 or something, then you will need to get a bit more "special" with some preprocessing to look at the path alias and check if it is special and then do things different.  And I say preprocessing because there should be as little logic in the templates as possible.


How do I know from which page the users are coming? I'm looking for a way to determine where the users are coming from to build the breadcrumb for a page.

Is there something I can do with hook_breadcrumb_alter(&$active_trail, $item), or should I use the Flag module or any activity tracker module?

If you have control over the Urls linking to your target page, append a page-specific parameter. Suppose the page you are linking to is http://www.example.com/target-page:

On the first referring page, make this Url: http://www.example.com/target-page?referer=page-1
On the second referring page, make this Url: http://www.example.com/target-page?referer=page-2

Then in your hook_menu_breadcrumb_alter function, the referer will be available in the $_GET variable, and you will be able to do something like this in the template.php file for your theme:

function mytheme_breadcrumb(&$variables) {

  if (request_uri() == '/target-page') {
    switch($_GET['referer']) {
      case 'page-1':
        $variables['breadcrumb'][] = l('First referring page', '/page-1');
        break;
      case 'page-2':
        $variables['breadcrumb'][] = l('Second referring page', '/page-2');
        break;
    }
  }
}

If you don't want to add parameters to the Url, and are not using HTTPS, you could use the approach above except with $_SERVER['HTTP_REFERER'] in the switch statement. Or alternatively, you could set a cookie on the referring pages and read it on the target page.

The example above is probably the easiest way to manipulate breadcrumbs but strictly speaking, there should not be business logic in a theme function. See these questions for more detailed info on how to manipulate breadcrumbs:

Altering the breadcrumb contents
Move user profiles under a menu item
https://stackoverflow.com/questions/10087168/how-to-add-breadcrumb


Tracking field deletion How to track user activity to find the user behind the field deletion.

As an admin, I want to track user activity so that I can find the user who deletes the field from particular content type.

I have tried with following modules but there is no option to track field.

Entity delete log.
track field changes.
Message and rule.

I recommend the Blame module, it logs all of the form submitted data of any form submitted on your website, whether that be a node form, an admin settings form, etc.


Change the used PHP version I have  PHP 5.6 and 7.1 on my system. I want to use PHP 5.6 for the Drupal 7 projects, and PHP 7.1 for the Drupal 8 projects.

I am having problems getting this setup.
In the documentation I found that I should set an alias like this in my ~/.zshrc.

 alias drush='DRUSH_PHP=/usr/bin/php56 /usr/bin/drush'

The problem is that when I start a new terminal and run drush ev 'print PHP_VERSION', it still prints out 7.1.6.

I tried to alias PHP to /usr/bin/php56 but that also did not work.

I also tried the following suggestions (and many others), but they didn't work.

Drush in a system with 2 PHP-Versions
Drush–alias to run it with another php version

I think this changed in more recent Drush versions, like version 8.1.12 I am using.

Can anyone help me find the correct way to do this in more modern Drush versions?

Did you try in your .profile:

export DRUSH_PHP='usr/bin/php56'

I think you are mixing up alias with setting an environment variable.


Where all are the hooks defined in a contributed module? What are the files in which core hooks are implemented in a contributed module?
Are they declared in .inc files? If so, what are the naming conventions for those include files containing core hooks?

The convention is to park all core hook implementations in .module.
.inc files are used to break off different groups of code like custom class definitions & administration form handlers. Some have their own naming convention for contrib hook implementations (e.g. .views.inc, .rules.inc, etc.).


How/where to change the default size of inline images? For the life of me, I can't seem to figure out how/where to change the default size of inline images (that is, images that have been inserted into the body by way of the wysiwyg editor's Insert/Edit Image button). It's likely that I'm missing something obvious here as I've only had one cup of coffee today... tragic, I know.

I would use the Image Resize Filter or Image Autosize Filter modules. These module add a filter to your input format that automatically resizes images added through the WYSIWYG editor. Image Autosize Filter allows you to set a maximum width, which seems like it would work for your case.

As a precautionary measure, you could add some CSS like this as well:

.node img {
    max-width: 450px !important;
    height: auto !important;
    border:0px;
    margin:0em;
}


how add js files to create a responsive theme? is possible to add these files http://alvarotrigo.com/blog/fullpage-jquery-plugin-for-fullscreen-scrolling-websites/ in a theme? I created from scratch and from Zen without success. some how i think the jquery and javascript files are not active.

thanks

Copy the plugin on your subtheme's folder like "plugins/fullpage/".

Edit subtheme.info file adding:

stylesheets[all][] = plugins/fullpage/jquery.fullPage.css
scripts[] = plugins/fullpage/jquery.fullPage.min.js

Check if you need to add the other js files like vendor/jquery.easings.min.js, jquery.slimscroll.min.js...

It seems that the plugin needs jQuery 1.9.1 so https://drupal.org/project/jquery_update may be helpful

More info about the plugin: https://github.com/alvarotrigo/fullPage.js


how to fetch result into array or how to fetch 'nid' out of result? Good day to everyone!

some help needed with fetching result out of EntityFieldQuery.
Have a unique value of the field. I try to get 'nid' of node by value of the field with help of EntityFieldQuery. my problem is that i dont know how to fetch result in a right way to get just 'nid'. then knowing nid i will be able to load the node and do some work with it.

$query = new EntityFieldQuery;
$entities = $query->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'order')
->fieldCondition('field_reference_number', 'value', $titleref)
->execute();
$result= $query->execute();
drupal_set_message('nid: ' .print_r($result, true));

my result is:

nid: Array ( [node] => Array ( [2250] => stdClass Object ( [nid] => 2250 [vid] => 2252 [type] => order ) ) )

how to fetch it corectly to get 'nid' out of it?

Thanks for your time

The simplest way would be:

$result = $query->execute();

if (!empty($results['node'])) {
  $nids = array_keys($results['node']);
}

There are a few different ways to get the first nid out of the array if that's what you need; personally I prefer reset() as it's non-destructive to the original array (unlike array_shift() for example).

$first_nid = reset($nids);

If you then need the node objects you can pass that array straight to node_load_multiple():

$nodes = node_load_multiple($nids);


file_save_data fails in CLI I'm trying to create a file attachment in a Drupal content node from a command line script. When I'm calling file_save_data(), passing a public://something URL as destination, it fails. I've tracked down the failure to the is_dir("public://") call in Drupal's file.inc that somehow returns false.

Attachments work from the regular Web interface - there's r-x permission on all relevant folders. The script should be running under the same user as Apache - I call it from Apache in the first place, using PHP's exec(). When I call is_dir(DRUPAL_ROOT."/sites/default/files") - that is, on the underlying filesystem folder - it returns TRUE, so it's probably not permissions. Looks as if the URL wrappers are somehow off when running under CLI. There's no open_basedir in php.ini, no safe mode either.

For completeness' sake, here's the relevant portion of the script:

//Drupal bootstrapping
define('DRUPAL_ROOT', getcwd());
require_once('./includes/bootstrap.inc');
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
$user = user_load(1);

//Some irrelevant stuff here...
$file_content = file_get_contents($file_name); //Comes from somewhere else
$file = file_save_data($file_content,
        "public://".$file_name, FILE_EXISTS_REPLACE); //Returns false! :(

And here's how I call the script from my custom module:

function mymodule_entity_insert($entity, $type)
{
    if($type == "node" && $entity->type == "mytype")
    {
        $module_path = drupal_get_path('module', "mymodule"); //That's where the script is
        exec("php $module_path/thescript.php  ".
            ">/home/me/drlog.txt ".
            "2>/home/me/drlog.txt &");
    }
}

Stupid bug. The script would change the current directory. Drupal code, it seems, assumes that it will be running from Drupal root, so the file attachment paths are relative internally. chdir(DRUPAL_ROOT) before calling file_save_data fixed it.


Help with relations in views Have been struggled with this problems for days and I wonder if someone could have a look at it? I have tried me sleepless to achieve a certain table in views between three content types which has relations between them, using entity reference. The biggest issue is that I can't wrap my head around how I should set up my relations.

Since this is driving me crazy, have I made this pdf that describes what I have now and what I'm trying to achieve.

http://themesh.se/problemDesc/problemdescription.pdf

Hope some of you have some spare time and if the simple answer is "This won't work" will that also be satisfying at the moment.

To remove the rows that you annotated with "Duplicates", you could use the Views Distinct module. From its project page:

  Relationships or other joins in Views often create "duplicate" results. For example, a node with a field that has multiple values may show up in the View once per value in the multi-value field. It's frustrating, and the "DISTINCT" SQL query option in the Views UI does not actually solve the problem because the result row is technically distinct. This module aims to give a simple GUI method to remove or aggregate these "duplicate" rows.

Assuming that would indeed remove the duplicate rows, the "What I get" should match with "What I try to achieve". So with that the setup of your relationships like you already defined them should be OK also (I can't think of any other missing piece to complete your puzzle).


Show as expanded doesn't work I am trying to make my own theme for drupal 8. but I am struggling with the menu.
my menu looks something like this

parent1
- child 1.1
- child 1.2
parent2
- child 2.1
- child 2.2

but only the parents are visible.

I used the menu.html.twig file from the classy theme.

edit:
I tried my theme on other site and there the children are displayed. so guess the problems was not because of theme. so i activated the stark theme, but also there I can't see my full menu tree.
and the checkboxes show as expanded are checked

Make sure your parent links are set to Show as expanded on the /admin/structure/menu/manage/main page


How should I implement an alternative file upload? I want to write a module for Drupal 7 to integrate http://filepicker.io's awesome functionality. It's a simple JS widget that returns a URL of where the file is hosted.

I've never written a D7 module before, though I've written several for D6.

Should I create this as a fields widget (and if so, for which fields- file/image/link?), or should I create a whole new field type for this?

In production, my intent is to mix up the types a bit with this; that is, we have lots of images uploaded already, I'd just like to upgrade the 'upload' button (in lay terms) without breaking everything.

If you want it to use http://filepicker.io's storage, it will definitely be link field. It's your own design decision if you will just add a widget (that's what I would do) or clone it and add that widget to a clone. However, don't expect seamless work from images on your own domain and images stored away of it - you can't really resize, rotate, crop, generate thumbnails, and service may become paid one with only short notice (and unavailable without any notice at all).


node--page.tpl.php not detected in Omega subtheme I created a sites/all/themes/mySubtheme/templates/node--page.tpl.php in a Omega subtheme.

I cleared all caches but it is not detected at all.

I even try with sites/all/themes/mySubtheme/templates/node.tpl.php to theme all nodes, just in case that I would have a typo error, but not working.

The base of my subtheme is omega:

base theme = 'omega'

I've also made sure that the tpl.php file exist in:

sites/all/themes/omega/templates/node--page.tpl.php

sites/all/themes/starterkits/omega-html5/templates/node--page.tpl.php

sites/all/themes/starterkits/omega-xhtml/templates/node--page.tpl.php

No node override templates will be repected unless the original node.tpl.php file is also in your theme folder.

Copy the standard template file to node.tpl.php in your theme, clear the caches, and you should be good to go.


Get form values into hook_node_insert / hook_node_update I need to get in hook_node_insert and hook_node_update the value of a field I manually added to a form.

function hook_form_FORMID_alter(&$form, FormStateInterface $formState, $form_id) {

  $form['newfield'] = [
    '#title' => 'New field',
    '#type' => 'checkbox',
  ];
}

In Drupal 7 every form field is copied to the entity and it's easy to access it as explained here Get data form into hook_node_insert / hook_node_update

Is there a way in Drupal 8 too?

Use an entity builder callback on the form, for example:

function menu_ui_form_node_form_alter(&$form, FormStateInterface $form_state) {
  // ...
  $form['#entity_builders'][] = 'menu_ui_node_builder';
}

/**
 * Entity form builder to add the menu information to the node.
 */
function menu_ui_node_builder($entity_type, NodeInterface $entity, &$form, FormStateInterface $form_state) {
  $entity->menu = $form_state->getValue('menu');
}


Customizing the node create form using a template file I have created a template file for my content type, but I don't know how to get form design in that page.

My content type name is wallpaper, and I created the page--node--add--wallpaper.tpl.php template file. How do I access the node title, or the node body, in the template file?

If you want to design the form then use hook_form_alter you will get form array. If you want to design the node page then user node--content_type.tpl.php.


Import User ID with Drupal Feeds Is it somehow possible to import the user ID with feeds. The GUID field is not the ID field, as I just found out, but I need my user IDs with my imported users to stay the same.

I don't think feeds supports that out of the box, but there's a patch for it that is reported to work.


How do you functional test your Commerce Kickstart 2.0 projects? Since Commerce Kickstart 2.0 has its own Drupal installation, I don't see how to use SimpleTest with it.  I did find this documentation for the regular Drupal Commerce, not Commerce Kickstart 2 from what I can gather.  When I try to find what it alludes to in this documentation (CommerceBaseTestCase ), this does not exist in the Commerce Kickstart install that I can find.

So, how are people testing with Commerce Kickstart 2?  Let me be clearer with my question.  I have already installed Commerce Kickstart 2 and done some development.  I now want to create products and other elements programatically using SimpleTest to do functional testing.  However, SimpleTest starts with a clean install of Drupal.  This is not possible to use with Commerce Kickstart 2.0 because it has its OWN drupal version, and its not just a set of modules that I could enable programatically.

You can install the Commerce Kickstart 2 on your local environment and it would automatic have some data. If you do not know have a development environment I would recommend you to use Lazy Dubuntu (if you wish to build it on Ubuntu computer) or Acquia Dev Desktop 2 for Mac or Windows.

If you do not want to used your local environment you can use Pantheon to test it out for free.


viewing fields with field_view_field after EntityFieldQuery doesn't work I'm using an EntityFieldQuery to load a node and try to access some of its fields, but can't seem to get any of the fields. The code is below:

$nodestoload = $query->execute();
$nids = array_keys($nodestoload['node']);
$nodes = entity_load('node', $nids);
print_r($nodes);
$output = field_view_field('node', $nodes, 'suppliername');

However, $output is returning an empty array. I can see that the node loads using the print_r. I've also tried various options (such as replacing 'node' with the actual bundle type). But nothing seems to be working... How do I access fields from a node that I loaded programmatically?

Your code will only work if there is only a single value returned by your EFQ. Whatever you want to do with the nodes, you need to put in a foreach():

$nodestoload = $query->execute();
foreach ($nodestoload as $loaded_node) {
  $nid = array_keys($loaded_node['node']);
  $node = entity_load('node', $nid);
  print_r($node);
  $output = field_view_field('node', $node, 'suppliername');
}


How to remove the containing "response" tag from GET output It seems whenever Drupal 8 generates an XML output it gets wrapped in <response> tags. I'm defining a custom rest resource (e.g. like this) and can see no way of modifying this containing tag. The service which is consuming the XML feed breaks when it encounters this tag. Is there anyway I can remove it?

Rest plugins always use the standard seralization methods, you can't really influence that for just your plugin. You could implement your own, like ?_format=my_fancy_xml.

Or, if you have very specific needs an an existing client that you need to work with, you can always just implement a normal controller and build the XML yourself and return it with a normal Response object.


Multiple page versions and caching for anonymous users Is there a standard, or well accepted, method for allowing page caching when you have multiple versions of page, that don't involve using Page Manager?

For example, if you render out different versions of a page based on IP address, User-Agent, etc., page caching renders the code-based decisions useless, so some users may see the wrong pages.

The only method that I know about involves adding code to settings.php to alter $_SERVER['REQUEST_URI'] to make the code-based decision and then to tack on extra variables, but gets messy.

$_SERVER['REQUEST_URI'] is the simplest way. The other option is to modify the key used in the cache. There is a 6.x memcache patch that I've been using http://drupal.org/node/942914

The latest version of http://drupal.org/project/authcache might be able to do it.


Dynamically update views field labels I have been searching for a while, but cannot find an answer to this. How can I get access to the field name in a view (the label used in the content type)?

I am trying to create an anchor navigation through a view that only displays a link to a field if it has content. I have a custom content type with a number of long text fields and a view, and I would like to rewrite the content of the field with its field label but I cannot figure out how to access the field label. I would like to do it programatically in case the user asks to change the name of a field.

In Drupal 7 the _field_info_field_cache() function retrieves the FieldInfo which gives you access to various field data.

function get_field_label($entity, $bundle, $field) {
  $field_info = _field_info_field_cache();
  $fields = $field_info->getBundleInstances($entity, $bundle);
  return isset($fields[$field]['label']) ? $fields[$field]['label'] : FALSE;
}

//Retrieve the tags label from an article node in a D7 Standard install
get_field_label ('node','article','field_tags');


Files security - files folder hacked For the second time in a short while my files/ folder has been hacked. Permissions are set as 755 all accross the folder.
I tried to set it up as 750, 754 but it breaks the website.

What happens is that someone manages to upload files in the imagecache subfolders. The first time an html file was upload for phishing. The next time a imagecache genrated thumbnail was replaced by an other image.

Can you give me hints on where to look at to fix this?

Thanks,
Chris

From the information given, it is impossible to give a full answer.  For instance: Are your site on a dedicated server, or on shared hosting?  What user and group "owns" the files in your Drupal installation?  What is the extension (like .php) of the unwanted files somebody places in the imagecache subfolders?  (Please edit your question and expand it with this information, it will be a great help in order to give a more precise answer.)

However, since most people use shared hosting, I'll assume that you're using that.  You can read about how to set up correct ownership and permissions for in a shared hosting environment in this article: What are the most appropriate users and permission levels for Drupal sites on shared hosting?

However, the permissions you cite, and in particular the fact that 750 "breaks the website" indicate that you must have gotten something (probably the ownership to the files in your Drupal installation) wrong.  750means rwxr-x--- while 755 means rwxr-xr-x.

In a shared environment, the web server will either:

Run as the owner of the site (i.e. you). In this case your files/ folder (upload directory) should have 700 (rwx-----).
Run as a member of the www group. In this case your files/ folder (upload directory) should have 770 (rwxrwx--).

Not under any circumstance do you want the last triplet (permissions for others) to be anything else than zero.

However, unfortunately, wrong file permissions is probably not the only reason your files/ directory has been compromised.  Both 755 and 750 only gives write permission to the owner of the files/ directory.  You haven't told us who that owner is, but its either you or the web server user.

If it is you, then your shell account has been compromised, so look for Trojans with the excecute bit set (and change your shell account password).  If it is the web server user, then you have a cross-scripting attack or a PHP-injection attack, and you need to find and fix that.