Showing/Hiding Content-Type Fields Based On User I have a content-type that has many fields for different translations. How do I set it up in a way that it shows the translation field based on user selection only. I mean user selects his/her language, then only that content-field appears on the post.

Appreciated...

Yeah you could do that as well, though if you have lot of data hidding things on the server side would be better. You could just override the node template page, with something like :
node--nodeType.tpl.php, then in the variables of that page you will have your node with all its Fields available, you can then do a simple check (cookie or sessions) to render appropriate language.


How do I hide the authoring information? I installed Drupal 8.2.4 and the IceMagic-8.x-1.0 theme.
How do I hide the authoring information on articles?

Edit the node type, in the "Display settings", there is a checkbox "Display author and date information", turn that off.


Control access to node by entity reference on User record Let's say I have a Content Type of fruit. I want to control access to individual nodes of type fruit by an entity reference on a user record. What is the best way to do that?

In other words, if a user record has an entity reference field which references the nodes titled "orange" and "banana", he should only have access to those two nodes of the Content Type fruit.

[Someone below suggests Node Access User Reference, but that doesn't actually apply to this situation].

The Node Access User Reference module is probably what you want. From the module page:

Gives content access permissions to users for content that references the users with User reference or Entity reference.
This is great if you want your content authors to be able to choose additional authors, or choose who can view their content, as well as being able to display the list of authors or viewers within your content, or in views displays.


Breadcrumbs for some content types I'm using breadcrumbs generally throughout my Drupal 7 site and all working well.

However, for news articles, I don't want to have to add each into the menu structure as over time, this will be a little out of control.

I'd like content of the type = news to have

Home > News > Title

with an active link back to my /news page.

Is this possible whilst still using the normal breadcrumb for other content?

Just for the record, if you want to do this with Crumbs:

Go to /admin/structure/crumbs/entity-parent.
For content type "News", enter "news" as parent path.

Likely it already works now.
If not, check the order and status of plugins on /admin/structure/crumbs.
Also check /admin/structure/crumbs/debug, where you can simulate breadcrumb-building for specific pages.


How to set the public file path to migrate site files and images through Migrate Drupal UI I am working on migrating a drupal 7 site to drupal 8 site that has image fields in content types, as well as some pdf files that I am trying to migrate through the Migrate UI. None of those files are in private directories. I have run the migration through the core Migrate UI many times and the content, taxonomy, redirects, alias patterns all have been coming through flawlessly. I cannot however seem to get the path right for my public files to migrate at all.

I am using Acquia Dev Desktop, which by default sets the file path for the D8 site to sites/"your-website".dd/files in /admin/config/media/file-system as they have essentially 2 paths to get to your site files. I have changed this in the settings.php to sites/default/files which did not fix the problem. The Drupal 7 site files are on my local machine, and that site is a dev site also on Acquia dev desktop. The Drupal 7 site has the path set to sites/default/files in /admin/config/media/file-system.

When using the full local path :C:\Users\user\Documents\mywebsite\sites\default\files I am getting the following pattern, which makes me think that the files are not being recognized properly in the directory as I am not seeing the slashes in the path:

Source ID 1701: File &#039;//sitesdefaultfilesschematicsimagesah-00-3.5.JPG&#039; does not exist

When using sites/default/filesor sites/default/files/I am getting a double slash in the path when it shows the results sites/default/files//*

Source ID 1701: File 'sites/default/files//schematics/images/ah-00-3.5.JPG&#039; does not exist

Here is my question. What path should I be using, and is the Migrate Drupal UI designed to get the files and move them just by setting the public path for source files, or should i be manually moving the files (copy/pasting) into the D8 directory in conjunction with setting the source file public path in the UI to properly reference them?

I would really like to sort out if it's possible to migrate my files through the UI as I am not very savy with drush.

So it turns out though I had difficulty understanding them, the directions are "correct". The difficulty I had is partly because of my inexperience, but it's also partly because of a slightly confusing UX in Migrate Drupal UI. The label is asking for your "Public files directory", but what it really wants is your absolute docroot path. The directions state this: "To import from you current Drupal Site,enter a local file directory containing your site (e.g /var/www/docroot), or your site address (for example http://example.com)"

This means when the source files UI is asking for the "public files directory", the sites/default/files portion is already assumed by Drupal Migrate and is not needed, nor is it welcome. I used
 C:\Users\user\Documents\mywebsite and it worked the first try, where repeated attempts that included \sites\default\files path failed.

Also, the unique settings in settings.php from Acquia dev desktop for the public file path for the new Drupal 8 site were not a factor.  I left those settings as they were by default when I executed the migration.


Using different .inc files with same function names in .module file In our project, we have this module meant strictly for our custom API endpoints for our mobile applications to use. Currently, this is handled in a single .module file like so:

my_project_mobile_api.module

<?php

function my_project_mobile_api_menu() {
  return array(
    'api/v1/user/register' => array(
      'page callback' => 'account_register',
      'access callback' => 'user_is_logged_in'
      'type' => MENU_CALLBACK
    ),
    ...
  );
}

function account_register() {
  ... logic to create an account
}

Up until now, this has worked great for us, but now we need to add a V2 of the API. My idea was to extract all of the page callback functions (like account_register) into their own .inc file. This would look like this:

my_project_mobile_api.module

function my_project_mobile_api_menu() {
  return array(
    'api/v1/user/register' => array(
      'page callback' => 'account_register',
      'access callback' => 'user_is_logged_in'
      'type' => MENU_CALLBACK
    ),
    'api/v2/user/register' => array(
      'page callback' => 'account_register',
      'access callback' => 'user_is_logged_in'
      'type' => MENU_CALLBACK
    ),
    ...
  );
}

my_project_mobile_api.v1.inc

function account_register() {
  ... logic to create an account
}

my_project_mobile_api.v2.inc

function account_register() {
  ... logic to create an account (this logic differs from that of V1)
}

How can I make sure that my .module uses the right account_register function from the correct .inc file? Is there a way to specify the file in  the api/v1/user/register array?

You can use file key in your menu like:

I assume you have a includes directory contain both files my_project_mobile_api.v1.inc and my_project_mobile_api.v2.inc and both files contain account_register function.

Your hook_menu should be like the following.

function my_project_mobile_api_menu() {
  return [
    'api/v1/user/register' => [
      'page callback'   => 'account_register',
      'access callback' => 'user_is_logged_in',
      'type'            => MENU_CALLBACK,
      'file'            => 'includes/my_project_mobile_api.v1.inc',
    ],
    'api/v2/user/register' => [
      'page callback'   => 'account_register',
      'access callback' => 'user_is_logged_in',
      'type'            => MENU_CALLBACK,
      'file'            => 'includes/my_project_mobile_api.v2.inc',
    ],
  ];
}

You can also use 'file path' if you files not in the same module take a look at this example.


Contextual filter in views I have a form on my site. Each time a user submits the form they are directed to a confirmation page like this;

  eform/help-request/confirm?entityform_id=1

I want to create a view that has a contextual filter that picks the last form submitted by the user and displays the fields from that form only.

I have a view that shows the field content from the form as it was submitted by the user but i cannot get the view to only display the latest form submission from the user...
As i have it my view is displaying all the forms the user has ever submitted ... which i don't want.

Any help appreciated. I know I am close (ish)

Sort the view by created desc.

Then limit the view to only show 1 row.

The remaining item will be the last form submitted.


Database password changed and I am not able to access my site I am using xampp for the hosting for my drupal site
I started with no password for the database root, and I used this database in the installation process of my drupal site where user name is root with no password.
Then I changed the password of the root from the xampp local host. Now I am not able to access my drupal site any more, and I don't no from where I can configure the password of the database for drupal.
How can I solve this problem?

You can edit settings.php (located in sites/default) to change database information like username and password.


Getting 401 / 406 error from node creation with authentication I am trying to create nodes with authentication with the services module enabled. So far I have done following things:

Get services token from http://localhost/drupal/services/session/token.
User authentication: I did trigger login web service and in return I got session name, id and complete user information. I called this web service by passing X-CSRF-Token which I got from previous web service. (http://localhost/drupal/myendpoint/user/login.json`)
Node creation: I want to create article content type node. I am passing fields values in JSON and CSRF token and session information as following. (http://localhost/drupal/myrest/node.create)

Body (application/x-www-form-urlencoded)

{
   "title":"Created through service",
   "type":"article",
   "body": {
      "value": "
test
\n",
      "format": "filtered_html"
   }
}

Headers

X-CSRF-Token: bla bla bla
`SESSion name: bla bla bla

The response I received from node create web service is the following:

  Status Code: 406
     Date: Fri, 04 Dec 2015 23:43:31 GMT
     X-Content-Type-Options: nosniff
     Server: Apache/2.4.9 (Win32) OpenSSL/1.0.1g PHP/5.5.12
     X-Powered-By: PHP/5.5.12
     Content-Type: text/html
     Cache-Control: no-cache, must-revalidate, post-check=0, pre-check=0
     Connection: Keep-Alive
     Keep-Alive: timeout=5, max=100
     Content-Length: 0
     Expires: Sun, 19 Nov 1978 05:00:00 GMT

Could you please let me know what I am doing incorrect while triggering node create web service?

Change the URL to http://localhost/drupal/myrest/node, the application type to  application/json, and the request method to POST; then, it should work.


Views to show user referenced to node I'm trying to show user info in node where this user name is set in User reference field.

I have content type where is User reference field (field_customer).

I have Views:

Show: Users
Contextual filter: (field_customer) Content: Customer
Relationship: User: Customer (field_customer) - reverse

In Contextual Filter I have: When the filter value is NOT available = Provide default value User ID from URL
In Relationship I have: Require this relationship

And I have fields like User: Email, User: Name etc.

I created node and set one user to User reference field.

Views does not work as it should. It shows all users. I tryed to play with Views settings but just could not find proper settings.

What I am doing wrong here?

EDIT

I also created another Views.

Show: Content
Contextual Filter: Content: Customer
Relationships: Content: Customer

In Contextual Filter I have: When the filter value is NOT available Hide view
In Relationships I have: Require this relationship

And it shows nothing on node page. Also tryed with different settings but no luck.

It sounds like you need to reference the relationship you created down in the filter criteria.
In the example below I have a views where I want to display all documents of the current logged in user.

I created the views showing all documents first. Get your view working the way you want it too first.
Create the relationship - I want documents that are related to who authored them
Filter your view by the author relationship. So in the example below my view is filtered by the current user - and it shows all documents in which the current user is the author.
Once your view is sorted you can work out the user reference part.

Hope this helps


How do I extend the xmlsitemap module to include the google news / images and videos formats The xmlsitemap module covers the standard google xml site map. However, https://support.google.com/webmasters/answer/178636?hl=en is the information for the google image search and the specific markup for creating a sitemap for image content. Likewise https://support.google.com/webmasters/answer/80472?hl=en is for video content. I don't think that the xmlsitemap module supports these additional types.  (Google news sitemap is another one). Can anyone offer any more information about extending the module or if there are any patches that will achieve the above.

For news there's the Google News sitemap module

  The Google News module generates a Google news compatible sitemap feed from your Drupal site's content.

I don't think there are existing modules for images/video (I've looked for the same thing before myself and ended up hacking something together).

There's a feature request in the XMLSitemap module's issue queue for exactly this, but it's currently postponed. There are a couple of links on that thread pointing to how others have achieved it, those might be worth a look.


Translation server suggests translation with old date in admin/config/regional/translate/settings page, i had Check for updates set to never and translation server to Drupal translation server and local files.

i recently updated my site drupal version to 8.6.17.

after check for translation update manually i get a update available for drupal core translation with 2018 date for one of languages and i can't find .po file with this creation date.

my questions are:

how drupal check for available translations?
is it possible that it    suggests translation for a older drupal version?
and most important    is it safe to delete .po files from translation folder on my site manually and run check again?

i didn't find answer for none of my questions but at least find a solution:

after testing clear cache without luck i did these steps:

user interface translation->setting->change translation source to 'local file only'->check update translation manually

and old translation suggestion was disappeared.

now with changing translation source to Drupal 'translation server and local files' i get related translation suggestion for my Drupal version.


Use data from one textfield to populate other textfields in drupal 7 form I am new to drupal. I have a drupal form having fields Customer Name, Address and Phone. Is it possible to populate Name and Address Field automatically from database when the phone number is entered?

I am using Drupal 7.

Please help me and treat me as a beginner. Thank you...

Computed Field

  Computed Field is a very powerful field module that lets you add a
  custom "computed fields" to your content types. These computed
  fields are populated with values that you define via PHP code. You
  may draw on anything available to Drupal, including other fields, the
  current user, database tables, you name it. (Feeling the power yet? :)
  ) You can also choose whether to store your computed field values in
  the database with other content fields, or have them "calculated" on
  the fly during node views. (Although you should note that Views use
  requires database stored values.) This field is literally the Swiss
  Army knife of fields. So start cooking up your PHP based values!

OR

You can do it by using hook_form_alter then define copy_field_value.js create behavior:

(function($) {
  Drupal.behaviors.moduleNameCopyFieldValue = {
    attach: function (context, settings) {

      // Repeat this for all fields as needed
      $('#source', context).on('blur', function () {
        // above you can use change instead of blur if element is not changed by another js
        if (!$('#destination').val() || 0 === $('#destination').val().length) {
          $('#destination').val($(this).val());
          // wrap line above in "if no value" like I did, or other condition you like
        }
      });
      // end of "repeat this"
    }
  };
})(jQuery);


Image Migration from Drupal 6 to 7 fails Happy New Year everyone,

I am fairly new to the Migrate Module and have come to a halt concerning image migration. To begin with, my problem currently is that when I run my migration, drush outputs: "New object was not saved, no error provided".

Now all I want is to get the images relating to a specific content type (educational_activity) and copy them over to my destination folder.

CODE:

class EduActFile extends EduMigration {

public function __construct() {

parent::__construct();

#Define variable for the default user id (user="grammateia") wherever it is used (uid, revision_uid, etc.).
$user=36;

// Describe the class for the Migrate UI

$this->description = t('Migrate files');

$query = Database::getConnection('default', 'migrationDB')
           ->select('node', 'n');
//$query->leftJoin('content_field_filename', 'fi', 'n.nid = fi.nid');
$query->leftJoin('content_field_images', 'fim', 'n.nid = fim.nid');
//$query->leftJoin('files', 'fil', 'fil.fid = fi.field_filename_fid');
$query->leftJoin('files', 'file', 'file.fid = fim.field_images_fid');
$query->fields('n')
      //->fields('fil', array('fid', 'filename', 'filepath', 'filemime', 'filesize', 'timestamp'))
      ->fields('file', array('fid', 'filename', 'filepath', 'filemime', 'filesize', 'timestamp'))
      ->condition('type', "educational_activity",'=')
      ->groupBy('n.nid');

$this->source = new MigrateSourceSQL($query, array(), NULL, array('map_joinable' => FALSE));

// Specify that we want to create files from the source data

$this->destination = new MigrateDestinationFile('');

// Remember what source record created each destination object and track migration status and allow rollback with MigrateSQLMap class

$this->map = new MigrateSQLMap($this->machineName,
    array(
      'nid' => array('type' => 'int',
                       'not null' => TRUE,
                       'description' => 'Node ID',
                       'alias' => 'n'
                      )
    ),
  MigrateDestinationFile::getKeySchema()
);

$this->addUnmigratedSources(array ('fid','filepath', 'filemime', 'filesize', 'timestamp'), t('Source fields that we will not be migrating'));

$this->addUnmigratedDestinations (array('timestamp', 'destination_file'));

$this->addFieldMapping('uid')
  ->defaultValue($user);

// For each source row to be processed define data mappings to the destination field from source field

$this->addFieldMapping('value', 'filename');

// Specify the location of the source folder to find the files

$this->addFieldMapping('source_dir')
     ->defaultValue('C:/xampp/htdocs/protovoulia.org/sites/default/files');

// Specify the location of the destination folder to place the files

$this->addFieldMapping('destination_dir')
     ->defaultValue('C:/xampp/htdocs/testpaideia/sites/default/files/educational_activity');

// Use existing files

$this->addFieldMapping('file_replace')->defaultValue('FILE_EXISTS_REUSE');

// Ensure files are not deleted during rollback

$this->addFieldMapping('preserve_files')->defaultValue(TRUE);

}//construct ends

}

Do I need to use a different class to migrate files? Is my query wrong? Thanks in advance, your help will be greatly appreciated.

This has been answered by me in another question I made.
It can be found here: Migrating Multiple Files in a Node


What is good way to hide update.php file? I will like to know what is the correct/better way to hide update.php file on the production server.

Currently when you try to access update.php file, Drupal shows default access denied page with info about how to edit settings.php file which I think is bit more revealing than is required.

Any suggestions or best practices ?

You can add the following line:

RewriteRule ^update.php$ - [R=404,NC,L]

to your .htaccess file so the web server returns a 404 rather than bootstrapping Drupal to show access denied.


Redirect user to same page on login I know there are a couple modules other there that handle login redirects like Login Destination, LoginToboggan, Login Redirect and Rules.  However, they all seem to only allow strict URLs.  I would like users to be redirected to the same page they logged in on.  The default behaviour of Drupal appears to redirect users to the previous page on login.

Since I am using a login modal, redirecting people to the previous page doesn't work well.

How can I redirect users to their current page when using a login modal that handles the login through AJAX?  I would appreciate a solution that could be placed in template.php maybe using hook_user_login()

Take a look at the implementation in user_login_block(), particularly this line:

$form['#action'] = url(current_path(), array('query' => drupal_get_destination(), 'external' => FALSE));

This will add the destination parameter to the URL, which takes precedence over any other arguments passed to drupal_goto() (like $form_state['redirect']).
Depending on how you create your modal, the easiest way would therefore be to simply append the destination argument for the current page to the form action.


How to apply FILE in views field I like to make a custom view for the module entity browser. For some reasons I do not want to install the module entity browser empamples.
But I make the experience as I created the view that there are no file options to select only content options.
Can anybody help?

When you create a new view, you can choose on which entity the view is based on. In the first picture the view is based on File, in the second picture it is based on Content (nodes).

You only see the fields of that source you have selected.

Another method to get the fields from File would be to configure a relationship using a reference field. But this is then additional, you get fields from both tables by doing this.


How to show a message “field is required” from webform validation? When a webform is validated it does not send the Drupal message "X field is required", it creates only the red border around the field.

How would I show the Drupal messages from triggering during validation? It is a block view of webform in drupal 7.

Webform Validation module can be used to add validation in field of webform.


How to give custom function in D8 custom field widget class? I have created custom fields using field,field widget and field formatters.
One of the field I have created is a button. What I need is to write the submit handler for that button.

This is my CertfieldDefaultWidget.php

namespace Drupal\certfield\Plugin\Field\FieldWidget;

use Drupal;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
/**
 * Plugin implementation of the 'CertfieldDefaultWidget' widget.
 *
 * @FieldWidget(
 *   id = "CertfieldDefaultWidget",
 *   label = @Translation("Certfield select"),
 *   field_types = {
 *     "Certfield"
 *   }
 * )
 */
class CertfieldDefaultWidget extends WidgetBase {
  /**
   * Define the form for the field type.
   *
   * Inside this method we can define the form used to edit the field type.
   *
   * Here there is a list of allowed element types: https://goo.gl/XVd4tA
   */
  public function formElement(
    FieldItemListInterface $items,
    $delta,
    Array $element,
    Array &$form,
    FormStateInterface $formState
  ) {
      //print_r($items[$delta]->cert_fqdn);
      //exit();

 $element['cert_fqdn'] = [
      '#type' => 'textfield',
      '#title' => t('Fully qualified Domain Name'),
      '#value' => isset($items[$delta]->cert_fqdn) ?
          $items[$delta]->cert_fqdn : null,
      '#empty_value' => '',
      '#placeholder' => t('Fully qualified Domain Name'),
    ];
    $element['privatekey'] = [
      '#type' => 'textfield',
      '#title' => t('Private Key'),

      // Set here the current value for this field, or a default value (or
      // null) if there is no a value
      '#default_value' => isset($items[$delta]->cert_key) ?
          $items[$delta]->cert_key : null,

      '#empty_value' => '',
      '#placeholder' => t('PrivateKey'),
    ];

    // City

    $element['csr'] = [
      '#type' => 'textfield',
      '#title' => t('Certificate Signing Request'),
      '#default_value' => isset($items[$delta]->cert_csr) ?
          $items[$delta]->cert_csr : null,
      '#empty_value' => '',
      '#placeholder' => t('Certificate Signing Request'),
    ];
    $element['cert_crt'] = [
      '#type' => 'textfield',
      '#title' => t('Server Certificate'),
      '#placeholder' => t('Server Certificate'),
    ];
    $element['create_cert_btn'] = [
      '#type' => 'submit',
      '#title' => t('Server Certificate'),
      '#placeholder' => t('Server Certificate'),
    ];

$element['create_cert_btn'] = array(
    //'#name' => implode('_', $element['#parents']) .'_create_cert_btn',
    '#type' => 'submit',
    '#value' => t('Create/Renew Cert'),
    '#callback' => '_certfield_button_action'
        );

    return $element;
  }

} // class
?>

In my certfield.module OR CertfieldDefaultWidget.php file I have a function like as below

function _certfield_button_action(&$element, $form_state, $button){
}

But none of them is called when clicks on the Button .Please help me to find out a solution .

Because this is your custom widget, you don't need to create a custom submit function.

Just add WidgetBase::massageFormValues method to your class:

class CertfieldDefaultWidget extends WidgetBase {
  ....
  public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
    // manipulate with $values where $values is an array of your fields defined in your formElement.
    return $values;
  }
  ....
}


How to theme a Quiz in Drupal 7? - part 2 Trying to customize the look and feel of my quizzes in D7 - and getting overwhelmed. I have the Skeleton base theme installed.

Calling this Part 2 because - this is an extension of How to theme a quiz in D7?.

Help sought: Which CSS files specifically to target to change the Quiz Take page?

I have added the quiz-single-question-node.tpl.php file - and rendered the $question_node->content['body']. And now the quiz works fine... (but without my desired changes yet).

My problem is that the 'body' from above is a fully formed HTML Form of the quiz question. SO, where exactly should I look to:
a. change this body to perhaps add a CSS class?
b. where should I add the CSS class itself?

Would really appreciate some detailed hand-holding.

Thanks in advance.

\sites\all\modules\quiz\Quiz.css --> this is the place to change.

CSS class definition to be created for: "quiz-question-body" - this is for the question itself.


How to create groups and assign users to them? I want to allow the administrator and manager roles to be able to create groups (for example different jobs within a company) and be able to assign users to the groups. I want this to be a one-to-many relationship so that user1 can be assigned to job1 and job2 (or no job) but user1 can't be assigned twice to the same job.

How would I go about starting this or what is a good module and/or resource to utilize?

This sounds like a clear use case for the Organic Groups module. Organic Groups is great if you have a need to create a container for content and then associate users with that container.

However, if you don't have a need for any content-oriented aspects of OG (such as access control), then maybe all you need to do is make the associations visible, rather than a part of the site's information architecture. In that case, it sounds like you might want to use the Content Profile so you can leverage CCK Node Reference fields, which can be one:many arrangements, and using the bundled content_permissions module or Field Permissions, restricted to roles with specific permissions for editing the field.


direct acces image url I searched but cannot find an answer to my question.

I'm using Drupal 7 and created content with image. The path of the content is http://example.com/page/content

My problem: I want to share the URL of the image to facebook.

http://example.com/sites/default/files/image01.jpg

But the request URL shows "404 not found".

I have set the media to show in public.

Did I miss something?

If that file does actually exist within /sites/default/files/ then your link should work.

Have you messed around with the .htaccess file in the root of your site? Or it could be the hosting package your on as there's a rule in that htaccess to not go into drupal if the file exists in that directory


Ubercart Amazon Payments for drupal 7 How we can integrate Ubercart Amazon Payments for Drupal 7?

There is a module for Drupal 6 here.

It seems like AMAZON Payments module is not available for Drupal 7. No discussion about D7 port also happening.

If you are interested in writing D7 port for commerce module below article will help you.

http://www.drupalcommerce.org/developer-guide/utilizing-core-apis/writing-payment-method-module


Age gate not showing on home page I am working on a client's website and need to implement this age gate on it. The problem is it only shows on a specific url/page but not on other pages. Been looking for solutions since past 2 days but couldn't find anything on google about it.

This is what I did:

Added the shown below in html.html.twig and uploaded the relevant css and html. But the age gate popup only shows on www.xyz.com/?AvpClearCookie=1 but not on the www.xyz.com

I was trying to show it on home page but with the very limited knowledge I have about drupal it seeming difficult for me to get it done. Really appreciate if anybody could show me some light on this.

Maybe it's a cache issue, so you can try to externalize your script and call it with random parameter

<script type="text/javascript" src="path/to/my/script.js?itok=1561313215" defer="defer" async></script>

You can generate a random value with php with microtime by sample

Try it and let us know if helps you


Get users by display name on reference autocomplete field I need a list of users for a reference autocomplete field. I know about the realname module, but I haven't installed it, neither will I as long as it remains an RC (and I don't need all it provides). Anyway, I copied the code I needed from it and adapted it accordingly.

My users have a first_name and last_name fields. Here is the query I came up with in order to return the JSON for my autocomplete field:

$sql = "SELECT u.uid
        FROM users u
        INNER JOIN users_field_data ud ON u.uid=ud.uid
        LEFT JOIN user__field_first_name fn ON fn.entity_id=u.uid
        LEFT JOIN user__field_last_name ln ON ln.entity_id=u.uid
        WHERE CONCAT_WS(:separator, fn.field_first_name_value, ln.field_last_name_value) LIKE :text OR ud.name LIKE :text";

$uids = \Drupal::database()->queryRange($sql, 0, 10, [
    ':text'      => '%' . db_like($input) . '%',
    ':separator' => ' ',
])->fetchCol();

Do I have an alternative to this? I would rather not reference individual tables.

A potentially cleaner/easier way to do that would be to leverage the JSON API.  After you install that module, you should able to make a call to the /jsonapi/user/user endpoint (see the "GET user accounts section on https://www.drupal.org/docs/8/modules/json-api/fetching-resources-get), and parse out the UIDs into the array.


How do you give the content of a node a margin/padding without using html within the node? How would you go about giving an entire node (the content) a margin or padding to the edge of the node - without using html within the node - in drupal?

Is there a module for this?
If not - how do you do so using CSS?

it varies per whatever theme you use. it's typically something like div.node or div.node div.content as an example. tools like Firebug and Chrome developer tools can show you what classes a piece of content has in your HTML page. Using DisplaySuite for example you could provide additional classe(s) to any piece of content within view_mode -- but the basic markup exists per theme to target a nodes output on the screen.

It not only varies per whatever theme your using, but if your theme is HTML5 vs HTML4 (why in this day in age, i dunno) it may be article.node as a CSS selector because article is a new HTML5 element type, vs say a plain old div.node in older versions of HTML.


How to use taxonomy fields with Views and avoid duplicates? I have content type 'sports venue' which is related to taxonomy vocabulary 'activity'. So a simple View of venues and activities might look like this:

Park : football, hockey, running
Pool: swimming, diving
Stadium : athletics, running

I add an image field to the taxonomy terms to show an icon for each activity. Then I want the same View as above, but showing the activity icon instead of the term name.

In the View I add a relationship to the taxonomy vocabulary and add the taxonomy icon field.

Now the View has duplicates; 3 entries for park, 2 entries for pool etc. I only want a simple list as above.

Sometimes I can get close by using grouping and aggregation settings, but it gets quite messy. Am I missing something obvious here?

Note: This comment from Merlinofchaos is relevant, but refers to D6. Now that we can add fields to taxonomy terms in D7 core, I wonder if there are more options?

I don't know if this will help, but it seems similar. (Drupal is still pretty confusing to me, so I am sorry if this is not helpful.)

I eliminated duplicate rows in my view by changing the filter criteria. I could filter with two different criteria and get the same view, but one view had duplicates and one didn't.

The filter criterion that gave me duplicates was "Content: Producer_category (taxonomy vocabulary 5)."  Producer_category is the name of a field. With this filter, if the content had multiple terms of the vocabulary applied, it appeared multiple times.

The filter that worked was "Content: has taxonomy term". After choosing this, I was prompted to select a vocabulary, and then to select term(s). I used the dropdown to display the terms. Also, Since I only selected one term for my display, i did NOT check "reduce duplicates", but I guess if you choose multiple terms you should.

Also, FYI, I was getting multiple errors when using Views since updating to Drupal 7, and I figure I probably did something wrong in the update process; all my Fields disappeared, among other things. So I ended up re-building the View from scratch. It seems like there are a bunch of new settings and options, and my view had some old, obsolete settings, and it just seemed better to start over and eliminate any hidden errors.

Good luck.


How to add 'not equal' condition in form #states In my form, there are 3 selection list  A, B and C.

I wanna show or hide C based on values of A and B selected.
C should be shown if A's value = 'all and B's value != 'all'

How to set the #state condition in this case?

 $form['C'] = array(
        '#type' => 'select',
        '#title' => t('C'),
        '#states' => array(
            'visible' => array(
                ':input[name="A"]' => array('value' => 'all'),
                ':input[name="B"]' => array('value' => 'all') //???how to set !='all' here?
            )
        )
)

This code should work:

':input[name="B"]' => array('!value' => 'all')


Elements not showing in $form object I have a webform with some fieldsets. Within each fieldset is a set of input elements that are the same for each fieldset, and each set of elements has the same machine name.

One of the elements is a "Select options" as a set of checkboxes. I want to conditionally make some checkboxes readonly or disabled for all of the fieldsets.

My problem is that I have spent hours looking at how to do that, and I cannot find the elements within the $form object in order that I may alter them. The form is a multi-page form, so that may cause some problems, as I don't know if all of the elements show up in the submitted array until you have reached a specific page or not. I don't know how that works.

Part of my form has something like this:

outer_fieldset
-- count
-- fieldset_1
-- -- name
-- -- date
-- -- group
-- -- checkboxes
-- fieldset_2
-- -- name
-- -- date
-- -- group
-- -- checkboxes
-- fieldset_3
...

I used die('<pre>' . print_r($form['submitted']['outer_fieldset'], TRUE) . '</pre>'); to look at the data. $form['submitted']['outer_fieldset']['fieldset_1'] exists, but it doesn't have any elements inside it for the checkboxes or anything.

All the existing SE pages I have looked at give basic answers like $form['submitted']['element_name']['#attributes']['disabled'] = TRUE;, but I cannot use something like that unless I can find the element objects...

Could the fact that the inner controls all have the same machine name be causing a problem with that? The webform was created using the Drupal interface, and it allows controls to be added this way. I'm relatively new to Drupal. Any help on how to find and alter the attributes of these elements would be great. Thanks.

I found the checkboxes. I was printing the $form variable in the wrong hook function. I needed to do my modifications to the form in hook_form_alter.

I ended up using something like this:

unset($form['submitted']['outer_fieldset']['fieldset_1']['checkboxes']['#options'][$option]);


Upload images in external server I work between two servers, and I use one for development and the other for deployment. It’s very easy because I can tell the development one to use the database of the deployment sometimes. What I can't do is upload the images to a third service so both the sites will see the same images.
Do you know any workflow in which this is possible?
Are there any modules that allow you to upload images to an external service?

In my one of my setups I have a main server and a backup server.
They are separate small virtual machines on different physical boxes.
The entire Drupal install including file uploads is copied over from the main server to the backup server using rsync.

Rsync is an excellent command line *nix tool for copying, syncing files both locally and remotely. There are many configurations you can use. You can then configure a cron job to run it every so often. Here is one of the hundreds of threads

https://unix.stackexchange.com/questions/67539/how-to-rsync-only-new-files

In your case you could just rsync over the /sites/default/files folder.
Just one solution to your problem, but there are many.

Other Drupal module soltions using 3rd party services (like you suggested) are Media mover, CDN and Storage API, all take a bit of configuring but worth it.


How to show loader image before popup screen of color box module in drupal 7 I used color-box module in my current drupal project for showing user details in popup after click user image. It will take some time to show details so I want to show loader images before this. I tried to override this using drupal.behaviors but cannot get proper output. If any idea how to handle this situation then please help me for same.

Thank you.

Hope this will help you,

You can use Colorbox Callbacks

onOpen : Callback that fires right before Colorbox begins to open
onComplete : Callback that fires right after loaded content is displayed

jQuery.colorbox({
........
  onOpen:function(){
    //show loader
  }
  onComplete:function(){
   //hide loader
  }
});


Changing 2 Elements on Ajax Callback I have an element $form['elements']['manufacturer']. On change, I want to change $form['elements']['form_factor'] and $form['elements']['model'].
Currently I have:
$form['elements']['manufacturer']['#ajax'] = [
    'callback' => 'formChanged',
    'wrapper' => 'form-factor',
    'event' => 'change',
];

which works and changes the form-factor. But, I want to change the model as well.
Iniside formChanged return form-factor in the callback function, so I can't return model element.
function formChanged(array &$form, FormStateInterface $formState){
  $form["elements"]["form_factor"]["#value"] = 0;
  return $form["elements"]["form_factor"];
}

Reading from past posts, one option was to return the whole form inside formChanged (return $form), but this doesn't seem like a good approach.
I can't do something like, having 2 callbacks:
$form['elements']['manufacturer']['#ajax'] = [
   [
    'callback' => 'formChanged',
    'wrapper' => 'form-factor',
    'event' => 'change',
   ],
   [
    'callback' => 'anothercallback',
    'wrapper' => 'another-one',
    'event' => 'change',
   ]
];

Instead of returning a single render array (of all or part of your form) from your callback, you will need to return an AjaxResponse that contains a  ReplaceCommand for each piece of the form you want to replace:
For example, in your callback:
$response = new AjaxResponse();
$response
  ->addCommand(new ReplaceCommand('#edit-form-factor', $form_factor_element))
  ->addCommand(new ReplaceCommand('#edit-model', $model_element));
return $response;

See the guide:
https://www.drupal.org/docs/drupal-apis/ajax-api/basic-concepts#sub_form
And the Ajax commands reference:
https://www.drupal.org/docs/drupal-apis/ajax-api/core-ajax-callback-commands


Validating a Webform with CAPTCHA locally before submitting to an external URL I have the following setup

Drupal 6.x
Webform 6.x - 3.17
reCAPTCHA 6.x - 1.17

I also have the following custom module

function webform_to_data_repo_form_alter(&$form, &$form_state, $form_id)
{
if ($form_id == 'webform_client_form_765')
    {
        $form['#action'] = url('some-external-site.com', array('external' => true));
        $form['#method'] = 'post';
    }
}

As it is now, the form is able to communicate with the external website. It cannot however validate entered values before it submits.

This lack of validation is a problem for several reasons because

The CAPTCHA field can be left blank, which defeats its purpose.
Any field that I specifically made mandatory can now be left blank, again defeating its purpose.

I've also read on multiple occasions that once you use $form['#action'], any attempts on validation will cease to work.

I was wondering if there was a way I could prioritize the validation of forms over $form['#action'] and if so, how?

If you could just point me to the right direction, in terms of what my custom module is missing, I'd appreciate it.

Thanks in advance.

If you want to validate form, you need to leave action intact. Then, you can send it's content to external server in it's save handler using it's api or drupal_http_request().

The point is - action tells the browser where to send the data. If you make it send data to external server, your Drupal will never get it, so it will have no opportunity to interact with it. Of course you might try to implement validation in browser too, using JavaScript, but that's unreliable and shouldn't be used as an only way of validation.


What is best method to use for multiple databases on one server? Do you create an extra database for each site running on same drupal core or use replication, what is the best practice at the outset for setting up multisite databases on a vps centos server?

This question is dangerously off-topic, but as far as Drupal is concerned there are two primary things to consider.

True multisite (multiple independent sites running our of the same DOCROOT) versus multiple sites on the same server don't really come into play.  In fact, you could also apply this to multiple sites using the same database server instance.

Running multiple sites out of the same database catalog is used when

You only have one catalog to use and need to share it (eg, shared hosting).
You want to share some tables between instances.

However, as those state, this isn't a good idea.  Apart from the stability issues with sharing tables, you also have the security issue of an exploit in one site potentially getting at the data from another site.

Ideally, each site should have its own catalog in your database server, and each of these should have a unique user associated with it that has full access (minus GRANT) with connections limited to where the site is running from (either localhost or the IP address of the webserver).  This is the username/password that you should use in your settings.php

Database replication doesn't really factor into the decision here.  It is use for performance and/or redundancy reasons.  Drupal has some support for master/slave arrangements, but it is not really transparent.


Add additional fields to select list on Webforms In Webforms type field of Select options looks something like this:

But what if I need to add extra fields per each select option? Fields that are drop-down and you can select amount (number) of quantity.

So what it does is that user fills the form for a product query. They select products from the select list and select the quantity for each item. But how do you do that with Webforms?

Had to create a fieldset per each select option with only one select option available and then just play around with CSS and it looks like one select list with separate quantity fields.


Avoid a revision is automatically published I currently have new revisions created whenever a page is edited, but I don't want it to be automatically published. Instead, I want to have to go into the revision tab and click revert for the latest revision. Is this incorporated in Drupal 7 or do I have to download a module?

Please have a look at Revisioning module, this is probably what you are looking for.
There is simpler module Revision Moderation, but it has no D7 version


How to configure REST server to create new node from URL parameters? Drupal   7.23
Services 7.x-3.5

I've followed the instructions for setting up Services module, including https://drupal.org/node/1699354. I got the endpoint setup successfully. I am able to retrieve index of nodes using ...endpoint/node and specific nodes using .../endpoint/node/#.

Now how can I create new nodes via Service through an URL? The Services manual gets really confusing at this point, is outdated and full of errors. The sample code they provide here https://drupal.org/node/1334758 ... am i supposed to put this in a custom module in order to be able to POST? If so, it turns my whole site blank right after adding this line:

// cURL
$curl = curl_init($request_url);

Also, there's an issue with CSRF validation, as showing in the Firefox Poster tool. The Services forum is a madhouse so I come here in hopes that someone can guide me in the right direction. What other modules do I need to get this to work? Why does my site go blank after adding the code above?

A simple solution would be the following:

domain/endpoint?title=test&url=http%253A%252F%252Fwww.example.com

and produce a new node of nodetype with a title and URL.

In order to create the node you must use the POST HTTP request so you can't do something like domain/endpoint?title=test&url=http%253A%252F%252Fwww.example.com(it's GET HTTP request). You can do the following to solve your problems:

First you need to make the Services 3.0 work with Firefox Poster tool. You can go Testing with REST Server for checking all the basic function in case you forgot to set the permissions or forgot to enable resources.
After you find out how to communicate with Services 3.0. You can use drupal_http_request to build your own POST/GET HTTP request. An example will be here Making authenticated requests to REST Server.


extra fields in views module I am using hook_form_alter to add few extra fields in a node. I have also managed to expose those fields in user interface using hook_field_extra_fields. All good until now but I can not see those exposed fields in views module? any suggestions?

In order to expose your field to Views, you need to implement Views API:

http://views-help.doc.logrus.com/help/views/api

This can be made much easier if you implement your field as a proper field, rather than a form alter. The Examples project has some examples, notably Field Permission Example.


How can you find out in which module your code runs? I often face the issue that I need to have module metadatas (such as relative path)  and in the standard Drupal way I seem to be enforced to hardcode the module name like this:

\Drupal::moduleHandler()->getModule('my_module')->...

Is there an official way or a workaround to able to tell anywhere in your code (so not just .module) which module you are in (if it is module at all)?

As Clive mentioned, a constant is your best bet. When I start up a new project, typically one of the first things I do is create an interface that contains constants that are applicable to the entire project. Usually the very first constant is for the module's machine name. I then use these constants, and not strings, throughout the project.

Here's a simplified and obfuscated version from one of my projects: (this file would be located in the folder my_module/src/MyModuleInterface.php)

<?php

namespace Drupal\my_module;

interface MyModuleInterface {

  const MODULE_NAME = 'my_module';
  const SERVICE = 'my_module.foobarbaz';
  const TAX_VOCAB_FOO = 'foo';
  const TAX_VOCAB_BAR = 'bar';
  const TAX_VOCAB_BAZ = 'baz';

  const PERM_ADMIN_FOO = 'administer foo';

  /**
   * Returns TRUE if the specified module is enabled.
   *
   * @param string $module_name
   *  The machine name of the module to check as enabled. Defaults to this
   *  module's machine name.
   *
   * @return boolean
   *  TRUE if the specified module is enabled.
   */
  function isModuleEnabled($module_name = self::MODULE_NAME);
}

The benefits to this approach are:

Consistency through your project as well as for any other projects
that might want to call on your module; they can also utilize the
constant.
Reduction of errors due to typos.
If you use an IDE such as PHPStorm, you can take advantage of auto-completion, which is convenient and speeds code writing.


with limit(20) it runs only the first 20 values of DB In this lines of code it selects only the first 0-20 but i want the first time select the first 0-20 and then the other(20-40) and other(40-60) and so on. How I can solve this problem?

 function something_cron()
      $query = db_select('watchdog', 'wa')
        ->extend('PagerDefault')
        ->orderBy('wid')
        ->fields('wa', array('variables', 'type', 'severity',
      'message', 'wid', 'timestamp'))
        ->limit(20);
      $result = $query->execute();

      // Loop through each item and add to $row.
      foreach ($result as $row) {
        someother();
      }

The common pattern is to store the last ID processed in a variable, using variable_set(). Then you can retrieve it using variable_get() with a default of 0 before running your query, and add a condition to the query for wid being greater:

$last_id = variable_get('mymodule_last_id', 0);
...
->condition('wid', $last_id, '>')

...
$last_id = value from row
variable_set('mymodule_last_id', $last_id);


Trouble displaying different info for same role/node type In D7 I am trying to display different information to different users with the same role. The 2 types of roles are 'Renter' and 'Landlord'. I've tried creating different views, but currently all renters and all landlords can see all renter info and all landlord info.  I've tried Display Suite, Views, References, Entity References, all with no luck. :(

Ideally Larry Landlord would be able to see a list of all of his tenants (renters) with their addresses, rent amount, date of last rent payment, if the payment was processed, and if the rent is overdue. But currently he can see his info, and the info for the other landlords and renters.

Any thoughts?

Thanks!

After creating views and setting up an Entity Reference field, I am still having difficulty displaying the views I need. I'm trying to tie a renter (tenant) to a landlord, which would be a 1:1 relationship, and allow that one renter to see their history with their landlord. I am able to display all landlords and all renters, but when I try to create the 1:1 relationship that's where it falls apart. I may need another view, but I'm not sure how to connect the various views.

Any thoughts?

If you don't already have one, create a View of Users to filter on.

In the Displays section of that view, add a new Display of type "Entity Reference" (where you would add one of Block, Page, etc.).

Now, you'll see in this new View Display the Format is called "Entity Reference List". Go to the settings for this formatter and add a field to search by (in this case, you'll want to use 'User: Name', most likely). Add a Filter Criteria here to only include Users of a specific Role (Tenants).

Now, go to Admin > Configuration > People > Account settings > Manage fields

Add an EntityReference field called "Tenants".

On the Field Settings page, change the Target type to User. Then change the Mode to "Views: filter by an EntityReference View". You'll see your list of "Tenants" here.

Still with me?

You'll want to make this field widget a Checkbox, probably, so that multiple values can be selected.

Okay, save on that screen and then on Field Edit page, change the number of accepted values to Unlimited. (it defaults to one).

Now, logged in as a Landlord, go to that Landlord's profile and select the Tenants off the checklist now visible on their profile.

You probably created a 'Page' by default with your Tenants (User) View, so now go to that page's View Display settings.

Add a Contextual Filter of User: UID. Set this to a 'Provide a Default Value' with type of "User ID of logged in User".

Now you can Utilize Fields on this Page View--Display content of "Field Tenants" and it will show whoever is selected in that field for the currently logged in user. You can tweak the settings here--if you want to show more information you can display them as "Rendered Entities" and then use any of the View modes for that user you've set up, you'll need to mess with "Multiple Field Settings as well to get it how you want, probably.


Structured layout in Drupal I'm having trouble understanding how to approach layout in Drupal. I want to create a structure where (authorized) users with no designing skills can add content by simply adding content selecting a particular content type.

So e.g. I want to have one type of page that consists of a number of sections (rows) with an image on one side (should be possible to alternate which side) and a heading and text on the other side. If the heading and text is on the right, the heading should be just above the text, and not above the image to the left.

An arbitrary number of sections/rows should be possible to add.

I've managed to do something like this with panels and mini-panels. But it seems like I'm trying very hard to achieve something that feels rather basic... In any case, what I did was I added a page selecting panels with the 1-column layout. This allows me to add rows arbitrarily. First problem here is, the end user would have to select this on their own, I would have liked to have a preset content type with this.

Secondly, I created some mini-panels with content that can be added to the sections of the panel page. More problems: to create these mini-panels and make them lay out as described I have to create mini-panels of a 2-column format, omit the title, add only an image to one of the columns using add custom content selection - no title, and add a title and some text to the other column.

All of this is rather complex just to achieve this layout. It makes me think it would be much easier to just use a wysiwyg editor and lay it all out manually instead. But that is just what I'm trying to avoid. End users would come up with all kinds of layouts, creating a site that does not have a structured feel at all...

Previously I have only done sites in php and CodeIgniter framework, where I naturally have full control and can just add the divs I want, using something like 960 or blueprint to help with layouts, and style it individually with css. But that is dependent on doing it all yourself or at least with only others who know at least some web design. I don't know if modules based on 960 or something like that would help, since I need to be able to add sections etc arbitrarily? All I've seen for this is panels, but maybe I'm wrong?

So how do you approach this in Drupal? Any help will be greatly appreciated, because I'm really having a hard time understanding the basic thinking of layout in Drupal...

Edit:

this is a good example of the type of layout I'm referring: http://www.teamworkpm.net/features

First of all, I'm a big Panels fan, so I definitely think you should be using it, but I'm not sure it's the best for the task you are trying to achieve.

Some options, in what I feel is descending order of usefulness to you.

Since it sounds like it's necessary for you to mix several fields into a single render element, you could implement a Ctools "content type". How does one create a new ctools plugin should be helpful here. This easily allows you any custom logic in rendering the fields on a per entity basis. You should still separete the logic from the rendering, by declaring your own template. See Correct way to render a modules output through a template?
If the output you describe above completely dominates the page, then perhaps it would make sense to move the rendering up a level. A panels "layout"-plugin could be useful instead. The plugin link from above is still the source for more information.
If it makes sense to work with individual fields, which I doubt in your case, a custom field formatter could be what you are looking for. See How do I make the output of field X look like Y?
This one is mostly speculcation, I haven't attempted it, but if you are working with a Field collection, it being an entity, perhaps you can use Display suite to control it's output, and then have Panels render it inline. Or you could skip DS and directly template the FC entity.


Cant make profile2 fields visible to other users How can you make a profile (from the profile2 module) visible to all visitors?

I've given all users permission to "View user profiles". When viewing a user's page the fields from core are visible (username and picture). However the fields I've added with the profile2 module are not visible.

The profile2 fields are only visible when a user looks at their own profile, or when the administrator views users profiles. This seems like a permissions issue but I cant see what permission to change.

Profile2 module separates core drupal user profile by adding a separate profile entity to it.The permission "view user profile" you are adding is related to drupal core user management not with profile 2 module.

Here is a screenshot for working permission set for a profile created using profile2 mdoule. The profile name is common

The roles in the screen shot are anonymous, authenticated administrator cutom_role.

As a tutorial this video can help.


How to disable persistent database connections for Drupal 7 / PostgreSQL I have a Drupal 7.2 + CentOS 5.6/64 bit + PHP 5.3 + PostgreSQL 8.4.8 (servicing unix domain sockets only) web site which often goes down on peak times because of too many postmaster processes started.

On the advice from PostgreSQL mailing list I have installed pgbouncer at "port" 6432 with the following config:

[databases]
pref = host=/tmp user=pref password=XXX dbname=pref

[pgbouncer]
logfile = /var/log/pgbouncer.log
pidfile = /var/run/pgbouncer/pgbouncer.pid
listen_port = 6432
unix_socket_dir = /tmp
auth_type = md5
auth_file = /var/lib/pgsql/data/global/pg_auth
pool_mode = transaction
server_check_delay = 10
max_client_conn = 200
default_pool_size = 16
log_connections = 0
log_disconnections = 0
log_pooler_errors = 1

And forced Drupal 7.2 to use it by changing  sites/default/settings.php to:

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'pref',
      'username' => 'pref',
      'password' => 'XXX',
      'host' => '/tmp',
      'port' => '6432',
      'driver' => 'pgsql',
      'prefix' => 'drupal_',
    ),
  ),
);

Here an excerpt from /var/log/pgbouncer.log during peak times:

2011-06-20 17:32:48.591 23883 LOG File descriptor limit: 1024 (H:1024), max_client_conn: 200, max fds possible: 230
2011-06-20 17:32:48.591 23883 LOG File descriptor limit: 1024 (H:1024), max_client_conn: 200, max fds possible: 230
2011-06-20 17:32:48.592 23886 LOG listening on unix:/tmp/.s.PGSQL.6432
2011-06-20 17:33:48.593 23886 LOG Stats: 36 req/s, in 3346 b/s, out 57238 b/s,query 74605 us
2011-06-20 17:34:48.593 23886 LOG Stats: 43 req/s, in 3167 b/s, out 54435 b/s,query 68969 us
2011-06-20 17:35:48.593 23886 LOG Stats: 25 req/s, in 3391 b/s, out 42060 b/s,query 95764 us
2011-06-20 17:36:48.593 23886 LOG Stats: 25 req/s, in 3370 b/s, out 103636 b/s,query 72986 us

Also I've been advised to disable persistent database connections and have done it for my own PHP scripts.

But I don't know how to do it for Drupal, what would be the best spot for that?

Thank you!
Alex

Drupal does not use persistent connections.  See https://drupal.org/node/1079892.  You may need to lower the number of web server processes (e.g. Apache MaxClients).


Anonymouse users can't see Openlayers Data Overlay I have a map view displaying the Openlayers Data Overlay. It's displaying a list of GPS tracks from a "Map Feature" content type I made.

Logged in with the Administrator, I can see all the tracks on the map fine. The preview for the Data Overlay shows all the data coming through great.

When I few the map as an Anonymous user, not logged in, none of the GPS tracks show up. The map displays on the page but none of the data from my Data Overlay.

I've looked all over the place trying to find content permissions that are wrong that are screwing things up but I can't find anything.

Why is the data on the map showing for the administrator and not Anonymous users?

The pages were cached for anonymous users. I went into Performance -> Caching  and cleared the caches and it worked. I had cleared my own cache but not on the site.


I cannot upload an image - 404 ajax error When I try to upload an image, image is not generating and I always get ajax error.

I cannot upload an image.

I get a 404 ajax error.

I use Drupal 8.54

php.ini:

memory_limit = 254M
upload_max_filesize = 20M
post_max_size = 20M
max_execution_time = 90

No error - Recent log messages.

The files directory ( sites/default/files ) permissions - 777

I don't find any solution or references about that.

Edit:

I can't upload file.

When I want to upload more than 8KB files, get ajax error.

This part of the AJAX error message can be helpful for you:

  the requested url /@custom was not found on this server

This may have the following root causes (including but not limited to):

.htaccess settings
Your settings.php


Separate statistics on sites from Domain Access Is it possible to separate statistics (like number of views) on shared node on few sites while using Domain Access module, so the same node can be viewed like 50 times on site1 and like 80 times on site2, etc.?

I haven't actually tested this but you could maybe use separate database tables with different prefixes for the tables that the statistics module provides (accesslog, node_counter).

So your tables might be something like:

site1_accesslog
site1_node_counter
site2_accesslog
site2_node_counter

The domain_prefix module handles that. This module was a sub-module included in the main domain access module for Drupal 6 but was separated in Drupal 7.

There is also an issue here which seems to indicate you can use a small snippet of code in a custom module for this instead of using this drupal.org module, which is seemingly not well supported currently.

Keep in mind this is a fairly advanced usage of Drupal so I advise caution and lots of testing. Having said that though the tables you want to split are low risk compared to say the node or users tables.


corporate intranet portal with drupal 7 I am new to drupal. I need to develop a corporate intranet portal using drupal 7.
I have features like,

Employee profile creation

Announcement (Internal announcement, internal opportunities, display
new joiners with their      photo and info)

Employee birthday celebration

Awards

Discussion board

Survey

LMS

Event calendar
and many more.

I would like to know whether corporate portal can be built with drupal.
Please let me know if there any modules for the above requirement or any opensource for this .
Thanks.

I would like to know whether corporate portal can be built with
  drupal.

Yes it is possible.

  Please let me know if there any modules for the above requirement or
  any opensource for this.

The question cannot be answered properly without knowing the exact requirements and then digging very deep. The result would be mostly writing a book.

To be honest as you are new to drupal and the way your question "sounds" to me" you are likely to fail with the project. Therefore I would recommend you check out how far open atrium (Drupal 6) or other install profiles / distributions meet your requirements and try to sell one of these (plus customization) to your client. Or at least first look how the authors of open atrium, Drupal Commons and others do things and then ask specific questions.


How to set up component on another site? I've been tasked with setting up a simple gallery component on a global site.

The component exists and works on a sub-site, but I want to move it to the parent site and ensure it's available globally.

I found the component's files in the sub-site and moved them to the same directory in the global, parent site.

The good news is that I can now see the component when I go to add it to a panel. But I can't access it to set it up. Clicking on it does nothing.

Does anyone know if there are any other steps I need to take to do this?

Here's what I did:

Transferred component files from one site to the other to the same directory.
In the components.module file (which for me was up a couple of levels from the place I dropped the component files) paste in any hooks the correspond to the component (my component was an image gallery which used Masonry, so there were some hooks there).
Ensure the render function is relating to the right theme. See my other issue here for more info.
Clear caches, rebuild registry.

It's not the best response, but I hope it helps someone.


How can I create a custom view other than content types? How can I create a view that's based on a custom table from a custom module.

Actually in creating views path I can see options of view types as:

  View type:

  Node: Nodes are a Drupal site's primary content.

  Comment: Comments are responses to node content.

  File: Files maintained by Drupal and various modules.

  Node revision: Node revisions are a history of changes to nodes.

  Term: Taxonomy terms are attached to nodes.

  User: Users who have created accounts on your site.

But when selecting the node option I can only select from node table and selecting user I can select from the user table for displaying the data from these tables. But if I need to display data from the custom tables how can I select that table on creating the query and display them on the view pages?

You need to implement hook_views_data to tell Views about your tables and how the data in your tables relates to other tables defined to Views (if it does).  Here's a good tutorial to get you started:
http://www.grasmash.com/article/demystifying-views-api-developers-guide-integrating-views

Depending on the nature of your data, you may, alternatively, consider defining your custom data as a custom entity type.  If you do that through the Entity API module, then it will provide Views integration "for free".


What are my options for a url based cache tag? I have a controller that serves a path, /get-messages, which requires a query argument, path. An example request to this path will look like /get-messages?path=/about/team.
I have a content type, Message. Each message has a textarea field that allows the editor to enter paths that the message should appear on. Example content:
/about/team
/about/*

With javascript, on page load, I make a request to my controller, e.g. /get-messages?path=/the/current/path, to get all messages that should be displayed on the current page.
This all works fine and is no problem. The issue I'm having is with how to cache my responses correctly.
With core's default caching options, I might setup a cache render array like:
[
  'keys' => ['my_module_get_messages'],
  'contexts' => ['url.query_args'], // or `url.query_args:path`
  'max-age' = Cache::PERMANENT,
]

I can even add any message entities as cache dependencies to make sure their cache tags get added and the cache is broken if they're edited. This also works fine.
The issue I'm having is if someone adds a new message that should display on a path that's already cached, by default, creating the new entity won't clear the cache for any already existing cache entries.
I think I need a cache tag based on my url. Is there an existing cache tag I can use, or do I need to create/manage my own custom tags (as described in Implementing Custom Cache Tags)? Or an alternative caching approach?

You could add a listing cache tag for the content type:
  'tags' => ['node_list:message'],

This cache tag was introduced in Drupal 8.9. See the change record Added an ENTITY_TYPE_list:BUNDLE cache tag.


How to use Drush for Particular Project? In my loalhost there are few drupal 7 sites installed.

Suppose I have projects A,B and C then how to use for A,B Or C etc.

How to use Drush by project wise?

Goto each project folder to run drush command as project wise.
If you are using multi-site goto the project folder under sites directory and execute your drush command.


user/ content management/ membership I am just researching something for a client and membership functionality

Rather than allowing visitors/ unregistered users the ability to see a teaser and then full access to content if they register we would like visitors to see say 3 articles and when they click on the 4th they then have to register.

SO rather than restricting content by type or category the restriction is quantity before you have to register.

Does anyone know of any modules which deal with this type of functionality?

Thanks in advance

You'll need to install the ACL and Content Access modules as well as uc_node_access.

Every site is different, but the general workflow goes something like this:

Create a new content type, and use the content access features to make nodes of this content type inaccessible to users by default
Create your 'paid content' node using the new content type. These nodes will not be viewable by site users by default.
Create a node of type 'product' (an ubercart node type). Users who purchase this product will gain access to the 'paid content' node.
Add a feature to the product node of type 'node_access' (Edit the product node, click the features tab, and add a node_access feature). Here's where you specify the node that purchasers of this product will gain access to.
Repeat steps 2 thru 4 for each node that you want to offer for purchase.
If you've done everything correctly, then users who purchase the product node will gain access to the corresponding 'paid-access' node.

I've used the D6 version of uc_node_access on a few sites, and it works flawlessly for me. Can't speak for the D7 version of uc_node_access, but I'm guessing it works equally well. Takes a bit of setup, but it does work.

For track anonymous viewing the only thing I know is use the browser's cookies, but that method will only work in the actual session if the user do not registers and clear his browser's caches then he can see 3 nodes again, I think you should look for alwasy force the user to register, or show only a teaser of the nodes for anonymous and force them to register for see the full node, then you can only let registered users see 3 nodes, then they have to pay, that way is possible and better. Its just a suggestion


Writing image value to field_collection object I'm creating a field collection item  and saving it via entity_create, and it all works great as long as I don't have an image tied to it. As soon as I do, I get an error, and it looks like this in the watchdog table:

    a:6:{s:5:"%type";s:12:"PDOException";s:8:"!message";s:516:"SQLSTATE[23000]: Integrity constraint violation: 1048 Column &#039;fid&#039; cannot be null: INSERT INTO {file_usage} (fid, module, type, id, count) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4); Array
(
    [:db_insert_placeholder_0] =&gt;
    [:db_insert_placeholder_1] =&gt; file
    [:db_insert_placeholder_2] =&gt; field_collection_item
    [:db_insert_placeholder_3] =&gt; 50
    [:db_insert_placeholder_4] =&gt; 1
)
";s:9:"%function";s:16:"file_usage_add()";s:5:"%file";s:43:"C:\xampp\htdocs\mysite\includes\file.inc";s:5:"%line";i:663;s:14:"severity_level";i:3;}

My code looks like this:

$values = array(
    'field_name' => 'field_bp_images',
    'field_bp_image_title' => array( LANGUAGE_NONE => array(array('value' => $title)), ),
    'field_bp_image_file' => array( LANGUAGE_NONE => array(array('value' => $fid)), ),
    'field_bp_image_photographer_name' => array( LANGUAGE_NONE => array(array('value' => $photographer)), ),
    'field_bp_image_photo_flag' => array( LANGUAGE_NONE => array(array('value' => $is_photo)), ),
  );
}

$field_collection_item  = entity_create('field_collection_item', $values);
#Attach to the node
$field_collection_item->setHostEntity('node', $node);

// # Save field-collection item.
$field_collection_item->save();

My $fid is definitely populated, but I am still getting that error telling me my fid cannot be null. I'm guessing I need to provide more elements to the array, but not sure what keys to give, or how many. Any thoughts?

The column name for an image field is fid (not value), so you just need to change this bit of your $values array:

'field_bp_image_file' => array( LANGUAGE_NONE => array(array('fid' => $fid)), ),


Link formatter to display link title, image and summary I know I've seen a module that does this at some point in the past but can't seem to find it right now. In Drupal 8, I have a link field. I want to fetch that link's metadata so I can display the link's title / summary / image via a formatter (think of how facebook displays links). I don't remember if this worked server-side, storing the info in the drupal db or client-side via javascript (and for the prototype I'm putting together, I doesn't matter).

I'd appreciate any help before I decide to go and write it myself.

You can do a lot with Custom Formatters and Tokens, also check out Field Formatter if you need to wrap the link around an image field.

For most control create one yourself, there are different tutorials for that, start here: Create a custom field formatter


Can the Drupal 6 search function also index block content? I have a site where much of content has been entered into blocks instead of Pages, Articles or Blogs.  The blocks have then been enabled to show up on specific pages, creating the desired effect for the site.

However, as content as been added to these blocks, the search feature of Drupal won't find the pages that have that content on it.

Are there any options to adjust the search engine features for something like this?  Is there a hook that can be used to customize the search results?

No, block content is not searchable by default.
Have you tried the Block Search module? Seems that is what you need.

edit: After reviewing the module, I now see that the search functionality inside block content is done for only administrators, so that module probably doesn't help.


Disabling CKEditor in comments Does anyone know of a way to force plain text mode in comments for all roles?

Edit: is it in any way possible to do so through CSS? Thanks!

Try

function MYMODULE_form_alter (&$form, &$form_state, $form_id)
{
  // comments
  // http://api.drupal.org/api/drupal/modules--comment--comment.module/function/comment_form/6

  if ($form['#id'] == 'comment-form') {
    $form['comment_filter']['format'] = array(); // nuke wysiwyg from comments
  }
}


IP blocking doesn't prevent requests I am getting a lot of bad requests from a crawler at a specific IP Address non-stop. I added the IP to the blocked list and cleared the cache, but I still see more requests in the dblog coming in from the IP:

HTTP response: Bad Request. URL: https://valid.url.example.com/api/123456>; rel="canonical",<https:.json.

Why can they still send requests? Is there a way to prevent these?

Flood control is just for failed login attempts and some other stuff like forms being filled out.  It will not keep your bad bot from the site.

Assuming you have an Apache server, you can modify the .htaccess file in the root of your site to block specific ip with the DENY FROM {ip} directive. E.g. adding something like this to the top.

order allow,deny
deny from 255.0.0.0
deny from 123.45.6.
allow from all

If you don't have Apache / .htaccess support, the process will be different.


How do I filter on day & month from a date field? Hello I'm still fairly new to drupal and views,

I'm trying to create a Birthday notifier which checks "today" in a view block.
Now users can turn in their birthdays on their profile using the date field which is set as: yyyy/mm/dd.

Now the simple thing was to create a filter on the date today, but because of the yyyy field it wil not show up on today's date.

What I'd like is to filter mm/dd on today. So for example if someone's birthdate is 1993/07/03, he'd be notified as today is this persons birthday.

Is there a way to do this or to create a work around for this?

Maybe you could conjure up something with the Regular expression inside the Date Filter, but that is usually not a nice path.

I haven't tried it but maybe you can do it with Contextual Filters (Under Advanced settings in the third column in Views). There is a separate Contextual filter for month, and for day:

node.field_date (month) and node.field_date (day)

Configure them with Default values Current date.


How to pass a field value from a parent node to its entity referenced children nodes when saving the parent node form Drupal 8
Here is the scenario
I have a Company > Department > Employee… in that hierarchy.
Companies are already created previously.
On the Department node add form, there is an entity reference field to reference a Company. On that same Department node form, there is another Entity Reference field that leverages Inline Entity Form to add + reference Employee nodes on the fly. These Employee nodes also have a Company entity reference field.
The goal is to pass the Company field value from the Department node to the referenced Employee nodes when the Department form is saved.
I figure this may be accomplished with the Business rules module, and/or a hook form alter. Tried both without any traction. Any tips?

One option is to use hook_ENTITY_TYPE_update() and hook_ENTITY_TYPE_insert().
// Top of .module
use Drupal\node\NodeInterface;

function MYMODULE_node_update(NodeInterface $node) {
  _MYMODULE_set_department_employee_company($node);
}

function MYMODULE_node_insert(NodeInterface $node) {
  _MYMODULE_set_department_employee_company($node);
}

function _MYMODULE_set_department_employee_company(NodeInterface $node) {
  if ($node->bundle() == 'department') {
    $dept_company_id = $node->DEPARTMENT_COMPANY_FIELD->target_id;
    foreach ($node->DEPARTMENT_EMPLOYEE_FIELD->referencedEntities() as $employee) {
      // Only update the employee company if it's different.
      if ($employee->EMPLOYEE_COMPANY_FIELD->target_id !== $dept_company_id) {
        $employee->EMPLOYEE_COMPANY_FIELD->target_id = $dept_company_id;
        $employee->save();
      }
    }
  }
}


How can I get a list of all active enabled contexts on drupal site with drush? I can list all enabled modules by calling drush pml.

I can also used flags to only return certain kinds of modules, based on where they are enabled or not and so on:

Show a list of available extensions (modules and themes).

Options:
 --type                                    Filter by extension type. Choices: module, theme.
 --status                                  Filter by extension status. Choices: enabled, disable and/or 'not installed'. You can use multiple comma
                                           separated values. (i.e. --status="disabled,not installed").
 --package                                 Filter by project packages. You can use multiple comma separated values. (i.e. --package="Core -
                                           required,Other").
 --core                                    Filter out extensions that are not in drupal core.
 --no-core                                 Filter out extensions that are provided by drupal core.
 --pipe                                    Returns a space delimited list of the names of the resulting extensions.

How can I list all the contexts enabled on a site in a similar fashion, so I can rype something like drush context-list

i would say something like this:

drush php-eval "print_r(context_active_contexts());"


Send report of all changed or updated content in past day? Trying to use Rules to do this but I think it's a bit too complicated.

I want to specify a time interval - say 24 hours - and generate an email report that lists all of the content that has been changed or created.

I can do this for individual items quite easily, but I'm looking for an aggregate report that someone could look at in the morning or evening to get a general overview of all the content changes.

I did stumble across the Views Rules module, which is interesting. It would allow me to create a view containing all the new content or updated content in the past xx hours and present that data to Rules. But it seems that would still just allow me to loop over the data and send out individual emails.

I could of course just write a small module to do this as well, but I'm wondering if there's an existing solution?

Have you loooked at message notify?
Have a look at the blog post by gizra
or watch the video, message notify allows you to use view as the body of the email.


How to list the uploaded files (image file) of unsaved nodes? From the question What happens if a user uploads an image but doesn't save the node? and its answer, there is a table called file_managed and for any uploaded file (an image in my case), it sets 0 in status column, and if the image node is saved, it is set to 1. During each cron run, all files with 0 status will be removed.

I am using bulk_file_nodes module to upload the images. Unfortunately, this module sets the status 1 for uploaded files and no matter if their node is saved or not.

I need to accomplish what Drupal core does for unsaved nodes of uploaded files. To do so I have to list those files. There are about 30000 images and about 2500 nodes in my website that are uploaded by people and it is growing very fast every day.

The brute force method is to check the entire fid column of field_data_field_image table of the database for every file (in fact for every fid of file_managed) to see if that file is attached to a node or not, I think it is not a good solution at all.

Is there any way else to handle this?

thanks

The short answer is that there isn't really a way to do this.

The longer version is that you could make some SQL to find all candidates. The issue is that you can see if a file is used somewhere (on entites) on the file_usage table, but some files wont be "used in that manor. This means that finding a file "not being used" is not the same as it's safe to delete it.

A solution could be to make a cron job, that only checks images that has just been uploaded, but you still have the issue that you might end up deleting files that shouldn't have been deleted.


Get date of last update for a view Is there an easy way to check when I last made changes to a particular view or views display?

No, unfortunately there isn't.  If you look at the views_view and views_display tables in the Drupal database, that information simply isn't stored.

I even checked whether you can get to info like that if you're using the Features module with views, but even that only lets you know if a view has been updated since your last created feature, but gives no information about the date of any changes...


Check for Feed id in hook_feeds_presave I have a module that is using hook_feeds_presave. I want to only run specific parts of this function based on the feeds importer that is running. How can I check for the ID of the feed? These are standalone feeds and don't use node forms.

Try printing $source->id ( even if $source seems empty ). This should return the machine name.
It's what I always use.


Views 3 filter on academic year Using Drupal 6, Views 3. I am trying to build a view that will include events for the current school year. So this year the view would include everything from September 2014 through June 2015. Once we got to July 1st 2015 the view would show the next year (Sept 2015 - June 2016).

I'm thinking this might be accomplished with arguments but I'm not sure.

Any kick in the right direction would be greatly appreciated.

Les Z

There is a Date filter inside views that can be set and customized easily to satisfy your needs. You need to enable the Date module first. Here:

https://www.drupal.org/project/date

If you find implementation using Date module difficult, you can achieve the same result using the straight forward Views between dates filter module:

https://www.drupal.org/project/views_between_dates_filter


How can I create a new page template for the user registration page? I am a beginner in Drupal. I need to create a new page template for the registration page. Because in my website almost all pages have different layout.

Currently all pages are rendering through page.tpl.php.

Any suggestions?

There are so many ways to theming your registration page.
You can create user-register.tpl.php

To know about how to create user-register.tpl.php refer below links.

https://www.drupal.org/node/1211520

https://api.drupal.org/api/drupal/modules!user!user-profile.tpl.php/7

https://www.drupal.org/node/1195754

If you want to know how to create tpl files.

Page template suggestions are not working


User warning: Incorrect key file for table I am getting the following error and I don't know why this is happening.

  User warning: Incorrect key file for table
  './edubridge/watchdog.MYI'; try to repair it query: INSERT
  INTO watchdog (uid, type, message, variables, severity, link,
  location, referer, hostname, timestamp) VALUES (6,
  'imagecache', '404: Unable to find %image ',
  'a:1:{s:6:\"%image\";s:64:\"sites/all/files/pictures/cactus_flowers_beauty_Funzug.org_12.jpg\";}',
  3, '',
  'http://edubridge/sites/all/files/imagecache/members_87/pictures/cactus_flowers_beauty_Funzug.org_12.jpg',
  'http://edubridge/assignment/list/8223/556',
  '192.168.99.171', 1317211007) in _db_query() (line 149 of
  /var/www/html/edubridge/includes/database.mysql.inc).

Does anyone know how to fix it?

Two quick things you can try.

First, make sure the disk on your server isn't full.  MySQL can behave very weirdly when this happens.

Second, take a backup of your database (like with Backup and Migrate).  Then, from mysql CLI, MySQL Query Browser, or something similar do

CHECK TABLE watchdog;

and see if there is anything weird.  If so, you can do

REPAIR TABLE watchdog;

The MySQL docs will have more info on CHECK TABLE and REPAIR TABLE.

Sometimes, though, when a database gets wonky it is just best to restore a backup and move on.


Deleting Content Manually If I were to delete the latest row of the node table in the database would all traces of the latest added content be gone from my site without errors from core modules after clearing the cache?

If you delete a row directly from the node table you can expect:

At best - you will just have a bunch of orphaned data in the system. Tables containing this orphaned data include, but are by no means limited to,

node_revision
taxonomy_index
url_alias
search_node_links
Any number of field_data_FIELD_NAME and field_revision_FIELD_NAME tables

Those are just a few of the core tables that can be affected; there are others, and many contrib modules will install tables to store node-related data. Those will also potentially contain orphaned data.
At worst - there's no telling how this could affect your site, it completely depends on how it's configured. You might get lucky and experience nothing but the orphaned data, but I wouldn't advise counting on that. Before you do anything, take a backup of your data.


Using base_path and directory variables in twig template I'm creating a Drupal 8 theme. I have overriden the menu.html.twig... and I need to add an image to the first menu item.

In the page.html.twig I have used {{ base_path ~ directory }} to get the url of image like this:

But I'm trying to insert an image in themes/(my_theme)/templates/menu.html.twig like this:

But is in this file, I can't print these variables:

{{ directory }}
{{ base_path }}

or

{{ base_path ~ directory }}

How can I print the base URL for use in my image?

You can expose the base_path variable to all you templates by implementing hook_preprocess() in your theme .theme file.

e.g.

/**
 * Implements hook_preprocess().
 */
function mytheme_preprocess(array &$variables, $hook) {
  $variables['base_path'] = base_path();
}

where mytheme is the machine name of your theme.

You can use {{ active_theme_path() }} to get the path to the active theme.


How can I restore author and post information for nodes? When I create a content type, I disabled showing "author name" and "posting date"; then, I created nearly 100 nodes from that content type.

Now I want to show the posting date in the node content.

When I edit the node, and enable the posting dates to be shown, everything is OK; when I edit the content type, and enable the posting date, I can't see it in node page.

It is hard to edit all nodes to show the posting date. Is there a better way?

Regarding both date and author info:
If you are not comfortable updating the Post date directly in the database, then I suggest you take a look at Views bulk operations, which is capable of performing mass manipulation of your sites content.

If the data doesn't show up as expected, it's always a good idea to switch to stark, to see if it's a theme issue.


How to find out if an entity type is provided by core or a contrib/custom module? How can I find out which module is providing a particular entity type? I'm implementing hook_entity_type_alter() in a custom module, and I want to identify the entities that are provided by core. Is there a way to get information about the module that implements an entity type, so that I can gets its origin (set in core/lib/Drupal/Core/Extension/ExtensionDiscovery.php) or its package (set in module.info.yml)?

You can make use of module handler to get path to extension info file.

/**
 * Implements hook_entity_type_alter().
 */
function example_entity_type_alter(array &$entity_types) {
  $module_handler = \Drupal::moduleHandler();
  foreach ($entity_types as $entity_type => $entity_type_info) {
    $provider = $entity_types['block']->getProvider();
    $module = $module_handler->getModule($provider);
    $info_file = $module->getPathname();
    drupal_set_message("$entity_type ---> $provider ($info_file)");
  }
}


improve drupal 7 multisite performance I think this has to be performed when the project is starting and not when the project is running, but, I don't decide that. I'm only the developer. I read a lot about performance in Drupal 7, and I saw modules like (Boost, Devel...) but I'm not very experienced with this.

Devel isn't working for my project (when I enter here admin/config/development/devel the page only stay await for a couple of seconds and return a problem with the server [The connection was reset] and nothing happen). AS of yet, I have not tried Boost.

I want to make performance improvements not only for Drupal way but also for Apache+MySQL. I read something and some guys talked about jMeter to make some stress test and other thing. buy, I want to know what you think, what you use and your experience dealing with performance.

(One answer will be: CACHE, but I'm looking something more than a cache).

So much thanks guys!

Drupal
When it comes to multiple sites, you should consider what would be effects of managing multiple sites. Having a separate MySQL database for each Drupal site would means that your could do the following without disturbing others

take one Drupal Site offline
load new content into one site
alter contents of one site

Consequences

Upgrading Drupal content for one site may possibly affect others that are still running previous versions
Doing an Upgrade requires a full shutdown of all sites
Features for improving performance of one site (such as Boost Cache) may hurt performance for other sites

MySQL
When it comes to MySQL, you will have to consider one of two things

Using MyISAM Storage Engine
Using InnoDB Storage Engine

MyISAM and InnoDB have strengths and weaknesses.

MyISAM only caches Index Pages
InnoDB caches data and index pages
InnoDB can also be configured to have InnoDB bypass OS caching
InnoDB can be configured to access multiple cores/CPUs
There are some instances where MyISAM can be as fast or faster than InnoDB
As of MySQL 5.5, only MyISAM supports FULLTEXT indexing. MySQL 5.6 will introduce FULLTEXT indexing to InnoDB

Please see my past posts about other Pros and Cons:

May 03, 2012 : Which is faster, InnoDB or MyISAM?
Sep 20, 2011 : Best Of MyISAM and InnoDB
Jun 07, 2011 : How do I convert a database from MyISAM to InnoDB?
Apr 15, 2011 : https://drupal.stackexchange.com/questions/1715/what-would-be-the-optimal-mysql-configuration-for-a-drupal-7-site/2367#2367
Apr 14, 2011 : What are the main differences between InnoDB and MyISAM?


How to change the text of the "checkout" button in Drupal commerce cart? How can I change the text of the "checkout" button in Drupal commerce cart?

I need it to be "continue" instead.

thanks

   function rooms_form_alter(&$form, &$form_state, $form_id) {
      dsm($form_id);  // print form ID to messages
      switch ($form_id){
            case 'views_form_commerce_cart_form_default':
                $action['#value'] = 'continue';
            break;
      }
    }

By using the hook_form_alter() function, you can change the text of the buttons. It would be something like

$action['#value'] = 'continue';

Please provide us with more code so I can work out a decent example.


8 - Change taxonomy field's link text in view In drupal 8 when creating a view for taxonomy terms and add a field I enabled

  Link to the Taxonomy term

option. The pathauto module is enabled so it gives following link:

Taxonomy Term

But I want something like this:

Read More

I have created a twig file views-view-field--my-region--name.html.twig as following:

{{ output -}}

I cannot go into more deeper with this setup. Can you help me to change the anchor text OR just get the taxonomy term url?

In your view just add the field 'Taxonomy term: Link to Taxonomy term' and change the 'Text to display' to Read more.


Creating an Editor Role and Reusing the Admin Menu and Overlay in Drupal 7 I, like so many other Drupal users, wish to add an Editor role into my website.  I have already done this.  I want the Editor to be responsible for editing and publishing certain content, as well as create certain types of content.

I use the Admin Menu module so I get that very nice flyout-menu administrator toolbar.  Well, I want the editor to be able to use the same menu, only with certain items missing.  Not only do I want them to use the same menu, but I want it to appear in the same bar.  I also want the editor to be able to use the overlay as well, just as it appears for the administrator.

How do I do this?

Cheers.

Assuming you have the Administration menu module enabled, under People > Permissions check the following boxes:

Administration menu

Access administration menu

Node

Bypass content access control (note though, this gives the user permission to delete all content; if you don't desire this then you can micro-manage the permission on the individual content types, it's more box checking but also more secure)

System

Use the administration pages and help
View the administrative theme

Those are the core permissions that you need to have in order for a role to view the administration menu as well as menu items pertinent to managing site content.

Now, in order to make sure that the role is more or less secure, I would always uncheck every box whose label begins with "Administer...", as these permissions would be for administration roles.


How to convert date format on view? I have created a View. Its display format is grid.One of field is Time.

It is displayed as "Time: 1300". I need to get it printed as "Time: 1:00 pm".
I am using Room Reservations module and in my reservations tab time is displayed.

Can it be done with GUI or code needs any modification?

To convert date format in Views, you have to go the settings field which you are added to view. In settings, there is a Date Format select list field. You can choose the default time format provided or you can make your  custom date format by selecting the Custom from select list. A new textfield will appear "Custom Date Format". In this field, you can make your own custom date format using the link PHP Manual link provide in the description of this field.