Alter keywords searched in solr I want to search phrase entered by user as

q="phrase"^21.0 OR phrase

On localhost:8983/solr/admin/form.jsp
it parses "phrase"^21.0 OR phrase perfectly! and return correct results

How can i do it in PHP. I am using Drupal 6.
Please help!!

If more information is required please let me know.

In solrconfig.xml

<requestHandler name="drupal" class="solr.SearchHandler" default="true">
<str name="defType">dismax</str>

so the request handler was "default" hence query was parsed with deftype:dismax and dismax does not parse BOOLEAN operators in the query string.

I created a new HANDLER in solrconfig.xml

<requestHandler name="sohail" class="solr.SearchHandler" >
    <lst name="defaults">
     <str name="echoParams">explicit</str>
     <bool name="omitHeader">true</bool>

Set $params[qt] = "sohail"; in the MYMODULE_apachesolr_modify_query()

Now it works perfectly!


How can I programatically change the color of node title in views results? I want to change the color of the node titles from a view (fields on table).
My first ides was to alter the title and add a span with inline css.

function views_titles_views_pre_render(&$view) {
if ($view->name == 'documents' && $view->current_display == 'page') {
    $span_open  = '';
    $span_close = '';
    $view->style_plugin->render_fields($view->result);
    foreach ($view->style_plugin->rendered_fields as $index => &$rendered_result) {
      // Add HTML markup icon on rendered title field
      $rendered_result['title'] = $span_open . $rendered_result['title'].$span_close;
    }
  }
}

Although my attempt was a success, I managed to alter the title the css rule did not alter the color of the a tag. I figured out that I should go deeper into the title. As far I can tel the dpm of the views_pre_render does not show more options.

I have experience with drupal site building, but I am not in any way a php developer.

Can someone help me figure this out?

ps: I know there other more easy ways to achieve that but I want to do it with a module.

An easier (and more maintainable) way to achieve this would be to set a class in your span, instead of hardcoding the style. Something like the following:

$span_open = '<span class="my-title">"';

You can then add a CSS file to your module, so that you can better specify the color, also overriding the a tag. For instance:

.my-title, .my-title a {
  color: green;
}

For more details about adding CSS to your module, see https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_add_css/7.x


Translation view path broken after upgrade to 8.5.1 After upgrading my site from Drupal 8.3.5 to Drupal 8.5.1, the token {{ path }} is not translated anymore in the selected language.

Does anyone have a suggestion or solution?

Because Content: Path has been removed in 8.5 version. Instead you should use Link to Content.


How can I run a SQL query from a file? I have a module that will be used as a location finder, and it needs to create a table on install that will hold zip codes and their location. That's easy to do. However, I also need to populate that table. Seeing as it's quite a large dataset, and I already have it in a .sql file, I would like to be able to run that file instead of embed the query into the module_install function.

I looked over the documentation for db_query(), but I don't see a way to run a file.

Is this doable, or do I need to pull the database username and password out and run it manually?

You can use drush sql-connect for this, so you don't need to enter any credentials and/or use mysql's command line:

`drush sql-connect` < my-sql-file.sql

The tildes tell your shell to replace the command drush sql-connect with the command's output. Therefore, when you run this line in your terminal, bash will actually see something like:

mysql --database=dbname --host=localhost --user=username --password=password < my-sql-file.sql

Check out Drush's documentation for much, much more.


Which of the following is better in terms of performance and speed? I am creating a view and then using views_get_view_result() function to get the query and print a csv file
or
Creating a query using db_select and then using it to  print the csv.
Which of the above would give me quicker results

db_select would give quicker results as it doesn't invoke the entire Views API to get that database result set. However, Views will give you the benefit of a highly configurable user interface to adjust your query which may save on development time.


How to change date_popup date format in form? I am working on configuration page for the custom module, using datepicker with date module.

When i set #date_format to 'd-m-Y' its ok, i need a day-month-year format but when i submit form and trying to get variable from variable_get(), i see only year-month-day format,

GOAL: i need this variable to show up as default value or maybe placeholder in proper date format ('d-m-Y'),

minor goal: also i want this datepicker not showing up "today" but i need date position in calendar to stick on variable from variable_get(). Thanks!

function mymodule_admin($form, &$form_state) {

$form['mymodule_start_date'] = array(
    '#type' => 'date_popup',
    '#title' => t('Start date'),
    '#date_format' => 'd-m-Y',
    '#attributes' => array('placeholder' => variable_get('mymodule_start_date'),
    '#datepicker_options' => array('maxDate' => 0),
    '#date_year_range' => '-3:+0',
    '#date_label_position' => 'above',
    '#theme_wrappers' => array('date_popup'),
    '#required' => TRUE,
);

return system_settings_form($form);

};

EDIT: my resource datepicker API

EDIT: fixed by setting up drupal date format and using datepicker_options:

$form['mymodule_start_date'] = array(
'#type' => 'date_popup',
'#title' => t('Start date'),
'#date_format' => 'd-m-Y',
'#datepicker_options' => array(
    'maxDate' => 0,
    'dateFormat' => date_popup_format_to_popup('d-m-Y'),
    ),
'#date_year_range' => '-3:+0',
'#date_label_position' => 'above',
'#theme_wrappers' => array('date_popup'),
'#required' => TRUE,

);


Cronmonitor with import-html So I'm trying to get the import-html module to import files every time there is a cron run. However, I was hoping someone could help me understand what the format of file_list, profile_id, and source_siteroot is supposed to be. Below is my interpretation of file_list and source_siteroot

function cronmonitor_cron() {
  if(variable_get('cronmonitor_enable',0)){
    $file_list = ".";
    $context = array();
    $context['profile_id'] = drush_get_option(array('profile-id'), import_html_current_profile_id());
    $context['source_siteroot'] = "sites/default/files/old-sites/.";
    import_html_import_files($file_list, $context);
  }
}

but whenever I run cron, I get

invalid argument supplied for foreach() import_html_process.inc:52

This in turn is the line

foreach ($file_list as $list_index => $rel_path) {

Which definitely means there is something from with $file_list, right? What should its structure be?
The site says it is
"an  array of simple file paths, probably selected from the file_list form.
 *   Relative to the import context settings."
But it'd help if someone gave me an actual example as the words go over my head right now.

I changed $file_list to an actual list, ["."] and source_siteroot to "sites/default/files/old-sites/" and that gave me a valid path. Also profile_id to import_html_current_profile_id();

Thanks!


How to maintain a custom block content? I have created a block using a custom module.

In the block, I have static text which will vary by time; thus, I will have to let the content manager decide when to modify the static text.

Could any one tell what is the best approach should I follow?

Note: I don't want the content manager to edit the text from the code.

have you considered adding a standard HTML block at

Admin > Structure > Blocks > Add Block ?

/admin/structure/block/add

Drupal provides a standard interface for editing the HTML block content.

Alternatively, if you have PHP code, combined with alot of static text in the block, you could load a node into it instead, and use regular node editing for maintaining that text content.

e.g, in hook_block_view

$node = node_load($nid); // Load the text content from node
// PHP logic to build some content...
// ...
$block['content'] = $data; // php content
$block['content'] .= render(node_view($node)); // node content


Creating a redirect for content type conditionally I'm new to Drupal and have inherited a fully functional system (Drupal 7.43), I've had a look on Google with no joy, so hopefully you can help.

For a specific content type it has the following fields (simplified)

URL
info1
info2

When the user clicks to read the page if info1 is empty I would like to redirect to the URL (which is an external, absolute URL) if there is content in info1 I would like to show the page as normal.

How would I go about doing this?

No problem bro, its pretty simple.  I'll write you a step by step tutorial as an edit. Standby.

You will need to create a preprocess function.  Add a folder and a file in your theme.  THEMENAME/preprocess/node.preprocess.inc with this code:

<?php

/**
 * Implements hook_preprocess_node().
 *
 * Hyjacking the nodes normal node link if an external link is specified
 *
 */
function YOURTHEMENAME_preprocess_node(&$variables) {

  $url = NULL;

  switch ($variables['type']) {
    case 'article':
      if (isset($variables['alternate_link']['und'][0]['url'])) {
        $url = (!empty($variables['alternate_link']['und'][0]['url'])) ? $variables['alternate_link']['und'][0]['url'] : NULL;
        $variables['node_url'] = $url;
      }
    break;
  }

}

My example states that In the case of a Content Type with the machine name of 'article' (yours may be different) do something.

THEN check if my field with the machine name of 'alternative_link' (your machine name will be different) has a value then do something.

It will then use the node's default $url variable.

If it is not set, it will ignore this code and leave your $url clean


How to set a value on a field collection using entity metadata wrapper I'm trying to programmatically set a value on a field collection item attached to the user entity.

The field collection field in question is titled, field_user_location.

I initially had this ($usr_wrapper being an entity metadata wrapper of the user entity)

$usr_wrapper->field_user_location->field_land_phone->set($object['Phone Number']);

However that doesn't appear to work.

How do you get data onto a field collection via entity_metadata_wrapper()? There isn't much documentation about how to do this that I am seeing.

I found the documentation for field collections confusing as well.

Field collections need their own entity metadata wrapper. So, the following code would work for your example:

$collection = entity_create('field_collection_item', array('field_name' => 'field_user_location'));
$collection->setHostEntity('user', $user);
$fc_wrapper = entity_metadata_wrapper('field_collection_item', $collection);
$fc_wrapper->field_land_phone->set($object['Phone Number']);

I hope that helps for anyone else banging their heads over this.


Would PHPLint's advice be beneficial to our community? I recently found this static PHP code analyzer called PHPLint. One of the things it can do, is look at code like this:

/**
 * @return string
 */
function getText() {
  return 5;
}

And complain that a 5, is not a string. It seems to me like this could potentially reduce bugs, and perhaps even security issues in our code. One nice thing is that I see it could give is that for return values from function, all you ever need to check is (=== null). If it's not null, then you have the data you expected.

At the surface, this seems like a possibly great addition to our codebases, core and contrib alike. But perhaps there are problems with this that I don't see?

I started applying appropriate doc-blocks to own of my own modules, and one of the issue I hit myself is that because core frequently uses arrays with mixed data in them, there are limits to what kinds of checks PHPLint can do, which causes a lot of warnings.

Edit: One concrete example of an issue that this could prevent is this notice from php 5.4. This code has always failed, it's just that no one noticed until PHP 5.4 made the implicit casting a notice. In this case the bug is relatively harmless, but more subtle errors and security problems could creep in this way.

In theory, there sure are benefits. There are however some issues with doing it, as you partially found out yourself already.

There will be like a million false warnings, might just be as hard to find the real issues as when simply reading the code.
Drupal has a quite a few custom coding standards. For example, we're currently not using type declarations in docblocks except for @return $class.

I don't know how configurable PHPLint is, maybe there are a few checks that would make sense to run on our code.

For coding style issues, it might make more sense to use http://drupal.org/project/drupalcs


How to write options lists with drush vset? When we want to pin a variable for an environment, we'll set the value in the admin, then go look it up in the database, and copy the name and value into a bash or phing script, to insure that that variable is always set to the appropriate value for the environment.

However, for complex variables, such as options lists, what should set string look like?   For example node_export_file_types looks like this in the database:

a:29:{s:4:"blog";s:4:"blog";s:10:"case_study";s:10:"case_study";s:7:"analyst";i:0;s:5:"asset";i:0;s:4:"book";i:0;s:6:"course";i:0;s:8:"download";i:0;s:8:"employee";i:0;s:19:"evaluation_download";i:0;s:4:"news";i:0;s:17:"front_page_header";i:0;s:11:"hero_banner";i:0;s:12:"landing_page";i:0;s:11:"layout_page";i:0;s:10:"news_event";i:0;s:10:"news_press";i:0;s:7:"product";i:0;s:16:"product_overview";i:0;s:17:"product_resources";i:0;s:15:"product_webinar";i:0;s:8:"workshop";i:0;s:12:"registration";i:0;s:8:"resource";i:0;s:7:"license";i:0;s:7:"support";i:0;s:16:"training_courses";i:0;s:16:"training_request";i:0;s:17:"training_webinars";i:0;s:7:"webform";i:0;}

if we wanted to set that using
drush vset node_export_file_types 'somestring'
what that 'somestring' look like?

You can use drush.

drush vget foo --pipe

The --pipe option will format the output as php code.

As far as using that with drush vset, I would recommend against that and instead set via an update hook, or directly in settings.php.


How to show thumbnail images on product pages using ubercart module? I recently installed a test of Drupal/Ubercart on one of my test servers. I added a test product and uploaded 3 pictures for the product. My problem is that the 3 pictures are displayed in Full Size on every page that the product is listed. How do I enable thumbnails for these product images? I am quite sure that I have all modules that are required installed, but I see no place to enable thumbnails on product pages.

Firstly go to [your-domain]/admin/config/media/image-styles and create image style you want to use for your product images, than go to [your-domain]/admin/structure/types and click on 'manage display' on the right (for content type that you are using for products).

You will find your image field whose format is probably 'Image' and you will see a little gear on the right, click on it and for 'Image style' choose image style that you created previously (as mentioned above).

That's it. Now the images will be shown according to image style that you created.

For the list of the product I recommend that you use Views module and again to control your display image size by choosing image style for image field in Views.


How to calculate the average Fivestar rating correctly? The anonymous visitors and registered users on my website can rate nodes through a comment with a Fivestar field. I display the average rating on the node's page. While testing this mechanism, I found out that the average isn't calculated correctly when multiple anonymous users vote with a comment. I suspect that only the last vote of a certain uid is taken into account: since all anonymous users have a uid equal to 0 - even if their name in the comment is different - they are considered as the same person.

In order to solve this problem, I did some research to how Fivestar calculates averages. All comments and corresponding votes of anonymous users are stored seperately in the database, so I can certainly use all the available information. I think that I also located the function in fivestar.module (lines 45-59) that calculates the average:

function fivestar_microdata_suggestions() {
  $mappings = array();

  // Add the review mapping for Schema.org
  $mappings['fields']['fivestar']['schema.org'] = array(
    '#itemprop' => array('aggregateRating'),
    '#is_item' => TRUE,
    '#itemtype' => array('http://schema.org/AggregateRating'),
    'average_rating' => array(
      '#itemprop' => array('ratingValue'),
    ),
    'rating_count' => array(
      '#itemprop' => array('ratingCount'),
    ),
  );

  return $mappings;
}

My situation is as follows: I use the average rating of a node in Rules and Views too, so I'm looking for an easy solution. Surely, I expect that I can calculate the correct average with Views or Computed Field, but implementing the usage of this average elsewhere could require quite a lot of adaptations.

Therefore, I would first like to ask you whether you have faced this problem as well. If so, how did you solve it? Is it possible to somehow "overwrite" the way Fivestar calculates averages programatically? I'm not familiar with how one uses schema.org or what information that website provides...

According to me, the insufficient support for anonymous voting is due to an underdeveloped Voting API (see my comment on this issue on drupal.org). Since I am not a professional programmer, I am not able to solve this matter on my own, so I looked for a workaround, using the Rules, Views and Computed Field modules. These are the main steps to solve the problem:

Create a comment View with all the comments on a node which have a non-zero voting field. Compute the average vote with aggregation.
Add a new computed field for nodes, which stores the result of the previously created View. The safest option is to add the code in a custom module (see the module's documentation).
In order to update the computed field from step 2, it is necessary to save the corresponding node again. To do that, I created a simple Rule which launches after a comment is edited or deleted.
Additionaly, if you want users to be allowed to vote only once, you can create a node Flag Reacted and Rules which (un)flag a node when (a comment is deleted) it receives a comment. Next, use HOOK_form_comment_form_alter() in your custom module to hide the voting field in the comment form when the current user has already flagged the actual node with Reacted.


How do I identify what type of data or object I have? It's a referenced entity I am new to Drupal but an experienced developer. I'm creating a DS field in which I will display a custom block chosen by the content editor. I have successfully gotten a referenced entity (two references deep) based on this answer How to get instance of referenced entity?.

Is there some data that will tell me what type of thing it is? Should I find out by looking in the UI at the block layout menu?

It would be simple to answer the question 'How do I get the block ID?' (answer: $bid = $campaignFundraisingBlock->id(); and I will fix that shortly) but the question I really want answered is 'How can I find out what type of data I have?'

The top answer (here) How can I programmatically display a block? made it clear that the type of block makes a difference in how you render it, so it seems important to be able to find out what type of data I have.

With the code (below) I am currently getting this error: Error: Cannot use object of type Drupal\block_content\Entity\BlockContent as array in Drupal\shpf_campaign\Plugin\DsField\ParentCampaignFundraisingBlock->build(), (which I will fix shortly).

Here's my code:

class ParentCampaignFundraisingBlock extends DsFieldBase {

  public function build() {
    $campaignStory = $this->entity();
    $fieldCampaignFundraiserOptIn = $campaignStory->get('field_campaign_fundraiser_opt_in')->getValue();
    $showFundraiserCta = FALSE;
    if (!empty($fieldCampaignFundraiserOptIn)) {
      $showFundraiserCta = $fieldCampaignFundraiserOptIn[0]['value'];
    }

    if ($showFundraiserCta) {
      $campaign = $campaignStory
        ->get('field_campaign_node_type')
        ->first()
        ->get('entity')
        ->getTarget()
        ->getValue();
      $campaignFundraisingBlock = $campaign
        ->get('field_campaign_fundraising_block')
        ->first()
        ->get('entity')
        ->getTarget()
        ->getValue();

  /* question: Do I have a renderable block in $campaignFundraisingBlock, or a type? How can I tell? */

      $bid = $campaignFundraisingBlock['values']->id;

  /* This next code assumes that the data I have is a block created in the interface (content block), but that seems like a big assumption that is not necessarily true. */

      $block = \Drupal\block_content\Entity\BlockContent::load($bid);
      $render = \Drupal::entityTypeManager()
        ->getViewBuilder('block_content')
        ->view($block);
      return $render;
    }
  }
}

Some background information: The block type is set to 'Featured CTA' and there are a bunch of blocks of that type available for content editors to choose from. The content editor chooses the block in the 'campaign' content type (it is an entity reference). The end user can fill out a form in which they tell a 'campaign story'. The end user can choose to include the campaign fundraiser or not. The campaign story has an entity reference to the campaign it is part of.

So, how do I find out what type of data I have?

Do I have a renderable block in $campaignFundraisingBlock, or a type? How can I tell? How do I find out what type of data I have?

I will try to address the question how to determine the type of data in this scenario with entity references and the following block of code, which uses Entity and Typed Data APIs.

tl;dr $campaignFundraisingBlock should be an entity of whatever entity type(s) is referenced by the Entity Reference field "field_compaign_fundraising_block", and this entity can be passed to its View Builder dynamically to create the appropriate render array.

$campaignFundraisingBlock = $campaign
  ->get('field_campaign_fundraising_block')
  ->first()
  ->get('entity')
  ->getTarget()
  ->getValue();

I would break down the method calls to understand this.

$campaign seems to be the entity that is injected into the Display Suite Field Plugin. I don't know much about Display Suite, but it's an entity, so some of the basic entity methods are available to determine what it is:

EntityInterface::getEntityType can get an object described by its corresponding @EntityType (or @ConfigEntityType or @ContentEntitType) plugin. This can be useful to determine the property/field definitions the entity is capable of.

$typedData = $campaign
   ->get('field_campaign_fundraising_block')
   ->first()
   ->get('entity')

The get method here returns FieldItemListInterface, and the subsequent methods are really a part of the lower-level Typed Data API (See Entity API "implements" Typed Data API quotation mine). When we get an object that is an instance of TypedDataInterface, then we have some different methods for getting definitions.

The basic interface here is very limited, and, depending on what Typed Data Data Type is being represented, then it might implement additional interfaces.

TypedDataInterface::getDataDefinition provides Typed Data Definition class that describes this Typed Data Data Type. The DataDefinitionInterface::propertyDefinitions returns an associative array DataDefinitionInterface keyed by the property name, and the getDataType method returns the plugin ID/string of the data type its representing. In this case, for Typed Data Data Type representing an entity, it's EntityDataDefinition, which calls up to the Entity Type (back in the higher-level Entity API) to get its base and bundle field definitions.

$referencedEntity = $typedData
  ->getTarget()
  ->getValue();

The EntityReference::getTarget method (really weird in my opinion) gets either a cached version of the Typed Data representation of the entity or loads the entity and returns the Typed Data representation of it.

Calling getValue on a Typed Data Data Type will return the underlying data. So in the case of primitive data types, a string scalar might be returned, or in the case of complex data types, an entity or an associative array.

Typed Data Data Types do not necessarily return render arrays or have methods that return render arrays. The Entity API has that concept for entities. This is why the entity object returned from getValue can be passed to its view builder.

Unfortunately we can't instantiate a View Builder from the Entity object or EntityType object of an entity because of dependency injection, which is why we need the EntityTypeManager to do so. However I do know the entity type dynamically because getEntityTypeId method so I can dynamically return a render array for the correct entity:

$render = \Drupal::entityTypeManager()
  ->getViewBuilder($referencedEntity->getEntityTypeId())
  ->view($referencedEntity);

So in short, again, if you don't necessarily know what entity type you're dealing with, then you can use EntityInterface::getEntityTypeId from an entity object and pass that into getViewBuilder. And hopefully the explanation about Entity and Typed Data will help to realize why that huge method chain is necessary to return the entity object.


7 Increase the "Expires" header I am trying to optimize a Drupal 7 site. I noticed the Expires header is set to just 6 hours, although according to my .htaccess file, it should be 2 weeks. Then i found out mod_expires module is not enabled. Now i have two questions:

Since i don't have the necessary rights, is there a way to set the Expires header without enabling mod_expires?
What is setting the header to 6 hours?

EDIT: Another strange thing is that the header is not there at all for some of the css files.

Also the settings in my /admin/config/development/performance is as follows, if related to this:

Cache pages for anonymous users: checked
Cache blocks: checked
Minimum cache lifetime: none
Expiration of cached pages: 1 day

Here is some boilerplate Apache rules I came up with for this question based off of the rules found in the advagg readme. The inverted files match is untested but based off this post: https://stackoverflow.com/questions/12926604/inverted-filesmatch; got what needed to be excluded by looking at core's .htaccess

<FilesMatch "(?<!\.php)$">
  # No mod_headers
  <IfModule !mod_headers.c>
    # No mod_expires
    <IfModule !mod_expires.c>
      # Use ETags.
      FileETag MTime Size
    </IfModule>
  </IfModule>

  # Use Expires Directive.
  <IfModule mod_expires.c>
    # Do not use ETags.
    FileETag None
    # Enable expirations.
    ExpiresActive On
    # Cache all files for 2 weeks after access (A).
    ExpiresDefault A1209600
  </IfModule>

  <IfModule mod_headers.c>
    # Do not use etags for cache validation.
    Header unset ETag
    <IfModule !mod_expires.c>
      # Set a Cache-Control header to 2 weeks.
      Header set Cache-Control "max-age=1209600, no-transform, public"
    </IfModule>
    <IfModule mod_expires.c>
      Header append Cache-Control "no-transform, public"
    </IfModule>
  </IfModule>
</FilesMatch>

In your case the best you can do is to use ETags.

Note: If you happen to be serving all you static file assets from a CDN then you could enable far-future headers in the CDN module. Doing it this way will route almost all static file traffic through PHP (on a origin request) so it can be extremely damaging to the sites performance if you are not using a CDN.


Storing a URL from a basic page using a custom module I created a basic page at http://example.com/[company]/[customer]?id=2. I want to store this URL in a global variable for string manipulations within a custom module.

I succeeded to retrieve the URL by using hook_form_alter() with respect to a webform but I don't know how to do the same thing for a basic page.

Which hook do I need to use?

In your custom module, try to implement the hook_preprocess_page

function my_module_preprocess_page($vars) {
  print_r(current_path());exit;
}

This will retrieve the current URL of the site.


Increase memory limit doesn't help in Fatal error: Allowed memory size of .../modules/views/views.module on line 416 I've switched from Drupal 7.14 to 7.15 three weeks ago and therefore,
I'm encountering a series of very sophisticated (for me) memory limit errors.
Those errors occur any time I'm trying to clear cache in performance or to run update scripts.

My hosting company has increased my memory limit in php.ini up to 126 M, 256 M, 512 M, and even 1024 M. But the errors still occur.
I've migrated my site from shared to VPS, But the error incredibly still occurs.
I have no way and no idea how to move forward.

Here are the errors:

Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to allocate 30 bytes) in /home/example/public_html/sites/all/modules/views/views.module on line 416
Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to allocate 108 bytes) in /home/example/public_html/includes/menu.inc on line 2736
Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to allocate 71 bytes) in /home/example/public_html/sites/all/modules/chain_menu_access/chain_menu_access.module on line 59
allocate 64 bytes) in /home/example/public_html/sites/all/modules/views/includes/base.inc on line 93

I've also been beating my head against a wall the last while with Drupal memory issues. Here's my collected knowledge on the topic:

1. Views (can) use a lot of memory

I love me some Views (and Panels and CTools and everything merlinofchaos touches with his mighty, mighty fingers), but it's possible to create configurations with multiple relationships that use a lot of memory. If you disable your Views and the memory issue goes away, it's likely a badly-constructed View causing the issue.

What to do if it is a View, and you really need that View to work? Try putting it into code (Via Bulk Exporter or Features; see below. I've hand-coded Views-like functionality in order to improve performance with very little success) for a start. Another thought is to redo the View a different way -- if ultimately what you're getting at is taxonomy terms, make sure the type of View is a Taxonomy View when creating it; don't create a Content View that uses relationships to get at taxonomy terms.

Could also be worth mentioning here that Panels also supposedly uses a lot of memory -- I haven't really benchmarked it so can't confirm this.

2. Moving stuff from database into code is a very good practice

It took me several Drupal sites to realize this, but keeping everything that's created via a UI in the database (Views and Panels configurations especially) is a Drupal worst practice. Why? It increases load on the database and cannot be version controlled. The first point is particularly problematic in terms of memory usage -- instead of just loading the content from the View from database, the site must also load the view components itself. This is exacerbated by how Drupal uses tables: by abstracting everything to the nth degree, each bit of Drupal's functionality uses a new table, resulting in some requests joining a bajillion tables together. This gives Computer Science people hernias (caveat: link is silly), but can't really be avoided with a piece of software as modular and user-friendly as Drupal is.

The solution? Use Bulk Exporter (Included with CTools) or Features to package up bits of code currently residing in the database as module code.

3. Themes can also eat memory

Does your theme have a lot of template files (I.e., files in themename/templates/)? If so, memory is consumed each time one of those files is loaded. If you're creating templates specifically to suppress bits of Drupal from  being displayed, try either:

Changing permissions so that bit doesn't show up for specific non-admin user roles.
Using CSS to hide elements.

The first choice is obviously what you want to do for stuff affecting security -- you don't want to use CSS to hide an "edit" button for certain users, only to have them then unhide it via Firebug or whatever.

4. Don't go overboard on contrib modules

While sometimes a site needs a lot of contrib modules, don't go overboard. Each enabled (note: enabled. Disabled modules don't use any memory) module uses memory. This is a bit obvious, but worth noting regardless.

5. The VPS is (sometimes) a lie

In my experience, some unscrupulous hosting companies love trying to push Drupal sites to VPS servers -- they're more expensive and it frees up shared hosting space for ever-more WordPress websites. The situation is worsened by the fact that webhosts often don't advertise (Or even willingly tell you if asked) what the upper memory limit is for shared hosting.

Alas, often if a site isn't under heavy traffic and is still crashing, the issue likely has something more to do with Drupal's configuration than anything else. Pushing a user to VPS just muddies the waters and adds more variables to deal with (Is it the webserver config? PHP config? VPS guest config? VPS host config, even?).

6. When all else fails, clone to localhost and beat it with a stick

This is a big reason why people use the dev-staging-production methodology with version control -- when all else fails, you can do a DB dump, git clone the site to a local testing server and then royally mess up the site on the testing server without worrying about actually breaking anything on the production server.

For memory issues, this generally means disabling modules one by one until the one causing the issue is exposed. It can also point to webhost-related issues -- if the site runs perfectly fine on a local install with memory set to something reasonable like 128MB, then you know your webhost is on crack.

tl;dr

My gut is that it's chain_menu_access that's causing the issue. Try disabling that and clearing the cache, see if it works.

I'll also add to this answer as I think of other things to try...


How can I change the default system message shown on form submission I've created a business card request form as an EntityForm and am scratching my head trying to figure out where in the module i can find the line - ( " The submission has been saved " ) .

This message displays after every form submission/edit/save, and I would like to get rid of it but cant figure out where its coming from !   :)

That message comes from entityform_edit_form_submit

You could try setting the translatable text string to an empty string in settings.php

$conf['locale_custom_strings_en'][''] = array(
  'The submission has been saved' => ''
);

Or else look into another way to alter drupal_set_message text.


Set the role of users when you're not the administrator user Is it possible to do this? I can't see any permission I can grant for roles. I want to let a user create other users, but only of a specific role.

See the Role Delegation module for this feature.


How to use hook_prepare to modify a field of a node before it is edited I want to modify the contents of a field of an Article node just before it comes up for editing. I have read the documentation at http://api.hostdog.gr/api/drupal-8/drupal%21core%21modules%21node%21node.api.php/function/hook_prepare/8, which states that hook_prepare will "Act on a node object about to be shown on the add/edit form." I've read lots of other stuff too.

I've tried lots of ways of naming the function:

MyModule_article_prepare()
MyModule_article_node_prepare()
MyModule_prepare_article()
MyModule_prepare_node_article()
and on and on

But the function is never called. I've tried putting these functions in both the MyModule.module file and in the MyTheme.theme file. I've read countless posts. Nothing has caused my function to be invoked (I output to the error log to tell it got called).

I simply want to look at one field in the node and possibly modify it just before it comes up in the add/edit form for the user to edit it. I feel really dumb; this has got to be dead simple and I'm just not getting it.

The code that is provided by the page that you linked to is wrong. While this hook exists in D7 and while it is possible that during early D8 core development, in alpha or beta, it existed at one point. In D8 there is no such thing as hook_prepare.

As per the list of all D8 core hooks, it looks to me that hook got replaced with a newcomer hook called hook_ENTITY_TYPE_prepare_form

/*
 * Implements hook_ENTITY_TYPE_prepare_form
 */
function mymodule_node_prepare_form(\Drupal\node\NodeInterface $node, $operation, \Drupal\Core\Form\FormStateInterface $form_state) {
  if ($node->getType() == 'article') {
    // your code goes here
  }
}

and as always, anytime you implement a new hook, for the first time, clear the cache so it gets picked up by Drupal.


How to get site url with twig in Views custom text? In Drupal 8 I try to get the absolute site url in a Views custom text field.

I added {{ url('view.frontpage.page_1') }} which gives me example.com/node

Drupal docs say {{ url('view.frontpage') }} would do it, but it just gives me wsod and throws an error like so:

AH01071: Got error 'PHP message: Uncaught PHP Exception Symfony\\Component\\Routing\\Exception\\RouteNotFoundException: "Route "view.frontpage" does not exist." at /../../docroot/core/lib/Drupal/Core/Routing/RouteProvider.php line 187\n'

Any ideas?

The documentation could be out of date. Check your router table for the name of the route. In my Drupal 8 site it is view.frontpage.page_1.


Drupal content type text value I've created a content type that contains a form. In this form, there is a textfield that i want to make only readable + a specific value on it (if user A is editing this form, he can write on all textfields except this textfield that will contains : user A)

In the other side, I've a custom module that deals with users, so I have users with users ID, usernames..ect the username is the text that I want to automatically set on the content types textfield

I can't show you any code because as I said, it's a content type

Any help is great

It sounds like you're looking for Field Permissions.

  The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.


Is this possible? Dynamically changing fieldsets on node creation (Note that I am not talking about simply hiding/displaying fields conditional upon other fields' values.)

This question about programmatically creating fields led to questions about whether it was even possible to do what I want. See, I want to create a set of webforms that I will use as quizzes. Then I want to create a node of type "answer key" for each quiz. The answer key will be connected to a quiz by a node reference field. Upon selection of a quiz from the dropdown, some AJAX will automagically go to the specified webform, find its form elements, bring them back, and add them to node submission form for the answer key.

The tricky part here is trying to save them. See, since they weren't known to the content type beforehand, they won't have been defined already with a spot in the database and all that. So, how can I store them? Can I define on the content type a text field with unlimited values and just store one form element's answer per value in the unlimited field?

The tl;dr of this is: Is it possible to save inputs on fieldsets that are different for each node of the same content type?

You probably could apply some woodoo to save the data :) But : you would have hard times retreiving it. Node displays only the defined fields, Views only show the fields and so on.

I would suggest not using webform, but simply defining those quizes as new node types and save them, together witha reference to a record about the answer (if it is important).

It might be handy to use eck instead and create an entity type and bundles for each quiz - so you dont have to deal with all the settings on node, just the fields.


How to call helper function from my_module.admin.inc file in drush command? I have some function in the mymodule.admin.inc file that i want call from a drush command and i have done the following below in the mymodule.drush.inc

function mymodule_drush_command() {
      $items['custom-cmd'] = array(
         'description' =>'some description',
         'aliases' => array('ccmd'),
         'examples' => array('drush ccmd'),
      );
      return $items;
 }

 function drush_mymodule_custom_cmd() {
     module_load_include('inc', 'mymodule', 'includes/mymodule.admin');
     _helper_func();
 }

The helper function is something along the lines of this (mymodule.admin.inc):

function _helper_func() {
    //do something
}

When i try the module_load_include function and i run the drush command i get an error similar to:

'PHP Fatal error:  Call to undefined function module_load_include()...'

I am unable to find a good resource to help me figure out why the helper function is not called from the drush command.

The module_load_include() function can be invoked from Drush; it sounds to me as if some other parts of your Drush setup might not be working properly.

Here's a sample Drush implementation, similar to what you want to do:

/**
 * Implements hook_drush_command().
 */
function YOUR_MODULE_drush_command() {
  $items['your-full-command'] = array(
    'callback' => 'YOUR_MODULE_hello_command',
    'description' => dt('Description of your Drush command.'),
    'bootstrap' => DRUSH_BOOTSTRAP_DRUSH,
    'aliases' => array('your-alias1', 'your-alias2'),
  );

  return $items;
}

/**
 * Command to download the Chosen plugin.
 */
function YOUR_MODULE_hello_command() {
  // Include your file.
  module_load_include('inc', 'YOUR_MODULE', 'includes/YOUR_MODULE.admin');
  // Invoke your function.
  _helper_func();
  // Show a message to the screen.
  drush_log(dt('Custom command executed.'), 'success');
}

You can see a working example in my custom module boilerplate.


Showing only certain product attributed in a view rather than them all in Commerce I am using Drupal Product Pricing, Product Options and Product attributed modules.

I have created a number of different attributes for products but my issue is that when including them in a view it just displays all of them.

This is an issue since I am using Billy Mail PDF module which uses a line item view. So when I include the attributes in the view it just displays them all. This includes an image and potentially alot of text which could be inputted by the customer.

I just need to include 1 of the product attributes but this does not seem to be possible as there is no option for this inside the fields settings in views.

I found a solution in the form of a patch here > https://www.drupal.org/node/1696656


Does Drupal CORE have any built-in analytics? I've always used Google Analtyics for my sites, but for one however I've forgotten to set it up.

Does Drupal have any built-in analytics, i.e. a module that comes with Drupal core, that I can look at just to get an idea of traffic volume?

The only module that comes with Drupal core is the statistics module. And by default it is normally turned off. To use it, you have to enable it. So if it was not enabled initially, you will not be able to get the stats for dates prior to the date it was enabled.


Month Displaying Earlier Than Expected I have the following code to print last month once a new month starts.

$prevmonth = date('F Y', strtotime("last month"));
print $prevmonth;

The problem I encountered recently was that last month was printed before this month (August) begins.  E.g. July was showing although it was still July 31.

Any help on this issue is greatly appreciated.

What about the timezone settings ? This could be a lead.
http://php.net/manual/en/function.strtotime.php


How can I repeat parent table field only once for a group of child table fields? I am using Drupal Views module. I have Student accounts table that can have multiple students in it. Is there a way to create a table like the following?

╔════╦═════════════╦═════════════╦═══════╦═════╗
║ id ║ Title       ║ Student Name║ Gender║ age ║
╠════╬═════════════╬═════════════╬═══════╬═════╣
║ 1  ║ Acount 1    ║ Jack        ║ Male  ║ 50  ║
║    ║             ╠═════════════╬═══════╬═════╣
║    ║             ║ Smith       ║ Male  ║ 33  ║
╠════╬═════════════╬═════════════╬═══════╬═════╣
║ 2  ║ Acount 2    ║ Ellis       ║Female ║ 42  ║
║    ║             ╠═════════════╬═══════╬═════╣
║    ║             ║ Joe         ║ Male  ║ 43  ║
╚════╩═════════════╩═════════════╩═══════╩═════╝

My current table shows the data like this:

╔════╦═════════════╦═════════════╦═══════╦═════╗
║ id ║ Title       ║ Student Name║ Gender║ age ║
╠════╬═════════════╬═════════════╬═══════╬═════╣
║ 1  ║ Acount 1    ║ Jack        ║ Male  ║ 50  ║
║════║═════════════╠═════════════╬═══════╬═════╣
║ 1  ║ Acount 1    ║ Smith       ║ Male  ║ 33  ║
╠════╬═════════════╬═════════════╬═══════╬═════╣
║ 2  ║ Acount 2    ║ Ellis       ║Female ║ 42  ║
║════║═════════════╠═════════════╬═══════╬═════╣
║ 2  ║ Acount 2    ║ Joe         ║ Male  ║ 43  ║
╚════╩═════════════╩═════════════╩═══════╩═════╝

I want to avoid the repeat of of id and title columns.
Any idea how to do this?

This is the setting for my view:

The only way I can think of doing this without custom coding is by using the Views Field View where you create two different Views Displays, one with the contextual filter, save them both, then "embed" the contextual one into the other view.

This type of database query can be very performance intense, and caching is recommended. Or avoid it if you can.

In your case you can keep your original accounts view, but remove the student fields. Add another Display (Block) that is showing student name gender and age, and add a contextual filter for the account, save the view. Then in your original views display add the field for the student info.

You may need to adjust how the labels are shown, so you don't have them duplicate/in odd places because of the recursion.


How to display list of files under a particular directory in Drupal? I've created a custom module to export node data of different content types into Excel (using PHPExcel hooks).

That will be stored into particular directory called "Reports" under site/all/files directory.

Now I would like to display the list of files exists under "Reports" directory, in a page/view in a table format.

How can I achieve that?

I found a module called Filebrowser for this.

  Allows site administrators to expose a particular file system folder and all of its subfolders with a fancy FTP-like interface to site visitors. File metainformation (via descript.ion and files.bss) is supported. The module also allows these metafiles to store special content, which can be parsed with a callback. If no callback is specified in the file, only the description will be fetched.

This is the exact module what I was looking for. Using this module I could display all my exported files. Here is the screen-shot.

Additionally we can Delete the files and also download the selected items as an ZIP archive from here itself.

Hope this post helps someone.


Why the cron is launched when I visit the website and why is it taking so much to complete? I have a site in development. It has Feeds module installed, with mandatoty Job Scheduler also installed. When I come back to the office to keep working on the site, it takes almost a minute for the webpage to complete. I have checked the log messages, and says that it is the Cron doing its tasks. The Feeds imports are switched off, and configured to launch only on submission (admin), and the cron is scheduled every 3 hours, in times different to those in which the problem appears, apparently it is the visit to the webpage what launches the Cron tasks.

How can I check what is causing the problem?

The cron can make different tasks such as check for updates to Drupal core and modules, removing temporary files, index content and cleaning up log files.

When you enter to your site the cron is executed and performs his tasks every X hours. You need enter to your site to activate the cron execution, if you want a different behavior you need read this: https://www.drupal.org/cron

There is no way for Drupal to run a cron job without bootstrapping. And the bootstrapping occurs when a visitor hits the site (Nothing happens on a server without someone or something running it). If you want really scheduled cron jobs, you have to set it up server side and this is certainly the best option, for this read: https://www.drupal.org/node/23714

Edit: I found now this article Why Drupal cron is not running as often as you think and how to fix it


How to prevent Autocomplete Caching? I have made textfield to be autocomplete field by using hook_form_alter.

mymoudle_form_alter(&$form, &$form_state, $form_id){
   $form['field_state']['und'][0]['value']['#autocomplete_path'] ='get-state-values';
}
    function mymoudle_drupal_menu() {
    $items = array();

    $items['get-country-value'] = array(
            'title' => 'Country Value',
            'page callback' => '_get_country_value',
            //'page arguments'  => array(1),
            'access arguments' => array('access content'),
            'type' => MENU_CALLBACK,
    );
    $items['get-state-values'] = array(
            'page callback' => '_get_state_values',
            'access arguments' => array('access content'),
            'type' => MENU_CALLBACK
    );
    return $items;
}

function _get_state_values($string){
    $country =$_SESSION['country'];
    if($country == 'India'){
        $state = array('Tamilnadu' => 'Tamilnadu','Karanataka' => 'Karanataka');
    }
    else{
        $state = array('NewYork' => 'NewYork','Manahattan' => 'Manahattan');
    }
    print drupal_json_output($state);exit;
}
function _get_country_value(){
    $country = $_REQUEST['valueSelected'];
    $_SESSION['country'] = $country;
    print drupal_json_output($country);exit;
}

If I select country as India and type in the state as 'n' it shows me in auto-complete as two states with n words like tamilnadu and karnataka which is correct(it runs ajax to fetch the values as shown in screenshot-1).

The issue over here is if I again change the country to 'Us' and type same 'n' it shows same set of results and it doesn't run the ajax(as shown in screenshoot-2). Its showing from cache I think for previous results.

NOTE: I want an fix for the ajax caching issue.

I have attached the screenshot of what's happening .How to avoid this issue?.Any help will be much appreciated.Thanks in advance.

Since, there is no proper way, I opted for hack (or work around) to get this working. As already mentioned by @Clive, removing/disabling caching mechanism would require more work. This solution just skips the caching part.

Step1: Copy the entire misc/autocomplete.js to your module js scripts directory.

Step2: Comment or remove the following line from the copied file

// See if this key has been searched for before.
  //if (this.cache[searchString]) {
      // We dont want some things to be cached
    //return this.owner.found(this.cache[searchString]);
  //}

Step3: Implement hook_js_alter to override it to specific pages you like.

/**
 * Implements hook_js_alter
 * @param array $javascript
 */
function MYMODULE_js_alter(&$javascript) {
  if (arg(0) == 'MYPAGE') {
    $javascript['misc/autocomplete.js']['data'] = drupal_get_path('module', 'MYMODULE') . '/js/autocomplete.js';
  }
}


How to use different mail interfaces (Mail System)? I have a newsletter (simplenews) being used from time to time and it uses SMTP server to send mail.
All other emails from my site should be sent using default interface. How do I do this?

I thought Mail System module could help me with this, but seems I'm doing that wrong thus I can only switch between interfaces, but not assign SMTP to simplenews only and left other using default one. How can I do that?

For D7 you can define a custom mail system using the $conf['mail_system']

$conf['mail_system'] = array('mycustom_module_thekey' => 'MyCustomEmailSystem');

Then you can use the drupal_mail function

drupal_mail('mycustom_module', 'thekey', $email, language_default(), $params, $from);


How to populate an Entity Reference field from a modal AjaxResponse? I have an entity ref autocomplete field (reference to bundle A) in one of my bundles (bundle B). I want to add a button below this field which will open a modal for a bundle A create form.

This code works great:

  $form['#attached']['library'][] = 'core/jquery.form';
  $form['#attached']['library'][] = 'core/drupal.ajax';
  $form['field_ref_to_bundle_a']['#suffix'] = '

' .
        t('Add New Bundle A') .
    '
';

When I hit Create in the modal, the new entity is created; but I need to assign this new entity to the field on the parent form (bundle B). I have added a #submit callback with a form alter on the modal form and in that callback I have:

  $response = new AjaxResponse();
  $response->addCommand(new CloseModalDialogCommand());
  $form_state->setResponse($response);

which closes the modal. In this call i know the NID of the newly created entity and I am guessing there must be some way to set the value on that field in the parent form.

Although i don't think it should be necessary, i have seen code suggesting i can use a $response->addCommand(new ReplaceCommand()) to swap out the entire original field with one that is populated with the default value; but i have had no luck in doing this. I have been able to use this $response call to swap out the entire autocomplete with a text string; so does seem like i am on the right path. All i really need to do is set the default value of the autocomplete field; but not sure how to do this through ajax.

Going with the idea that i need to replace the entire field (as opposed to just setting the default value); i found this code:

  $node = Node::load($nid);
  $elem = [
    '#type' => 'entity_autocomplete',
    '#target_type' => 'node',
    '#default_value' => $node,
    '#attributes' => [
      'id' => ['#edit-field-ref-to-bundle-a-0-target-id'],
    ],
  ];
  $renderer = \Drupal::service('renderer');
  $renderedField = $renderer->render($elem);

Although this does render something:

<input id="#edit-field-ref-to-bundle-a-0-target-id" type="text" size="60" maxlength="128" class="form-text" />

It doesn't have a default value set. But perhaps I am close??

Figured out it was the InvokeCommand i needed and to set "val" to the referenced entity title with id in ().

  $nid = $form_state->getValue('nid');
  $node = Node::load($nid);
  $value = $node->getTitle() . ' (' . $nid . ')';

  $response = new AjaxResponse();
  $response->addCommand(new CloseModalDialogCommand());
  $response->addCommand(new InvokeCommand('#edit-field-ref-to-bundle-a-0-target-id', 'val', [$value]));
  $form_state->setResponse($response);


Help with Canada Post Shipping Quotes with Ubercart Is there someone that can help me with Canada Post Shipping Quotes with Ubercart?  I can't find any documentation on how to set it up.  I've gotten my Canada Post account and I've put all the information into the module, but it's not showing any quotes.  I also have UPS and it's displaying quotes just fine.  I'm not seeing any errors or anything so I'm wondering if I've missed a set up somewhere?  I tried going into the Canada Online setup but quite frankly I don't understand what I'm supposed to do.  Do I have to set up every possible package size for it to work?  How would that reference back to the product?  We sell so many different products that could be a nightmare!!!  If anyone can at least point me in the right direction I would be so grateful!!
Thanks!

Make sure you have the store address information all filled out properly in the Ubercart Store Configuration and in the Shipping module.  It seems like a duplication but it helped me.


How to load one certain js before all others? We are struggling around here with SVG in IE8. Amongst other approaches we'ld also like to try the SVG Web Toolkit. In it's quick start guide they say:

  To use SVG Web, you must drop a script tag into your HTML page. This must be the first script tag on your page.

The JS is now loaded by a custom module. I tried

drupal_add_js($modulepath . '/libraries/svg.js', array(
   'group' => JS_LIBRARY,
   'weight' => -1000,
   'every_page' => TRUE));

When I vary these options it's sometimes higher, sometimes lower. The above code makes it the highest I can get it. But there still are quite a number of scripts loaded prior to it.

How can we ensure the svg.js to load first? Is there maybe a way to do it with drupal_add_js in our custom module?


Widget settings hook for Drupal 7 What hook is the equivalent in Drupal 7 for hook_widget_settings($op, $widget), used in Drupal 6?

What hook is the equivalent in Drupal 7 for hook_widget_settings_save(), used in Drupal 6?

You can use hook_field_widget_info().

Here you can give the widget settings.


How to add custom badges depending on the amount of User Points earned? In my website I have the Vote Up/Down module and the User Points module enabled and a rule (using Rules) to add user points for every vote automatically.

What is the way to add Custom Badges depending on User Points?

Let's say, if a user has 100-150 user points then the user's badge will be "Newbie". If the user has 150-200 points then the badge will be "Regular" and continues...

I have tried with the Achievements module but it seems difficult!

So what is the way to add custom badges depending on User Points?

Why not simply use the user_badges module which explicitly integrates with userpoints?

userpoints_badges
Integrates Userpoints with the User Badges module.

Check out the userpoints contrib modules list, there may be more tools in there you can use..


grabbing data and displaying it in block twig bI made a custom module and made a custom block inside of it.

In the build () I have this.

return array (
  '#theme' => 'no_athlete_match_block',
  '#title' => 'Athletes With No Matching Name in the Database',
  '#description' => 'Displays the athletes with no matching name in the database for a given sporting event.',
);

In the .module file I have this.

function no_athlete_match_theme($existing, $type, $theme, $path) {
  return array(
    'no_athlete_match_block' => array(
      'variables' => array(
        'description' => NULL,
        'title' => NULL
      ),
      'template' => 'block--no_athlete_match',
    ),
  );
}

my twig file named block--no-athlete-match.html.twig

<div>
node: {{title}} {{description}}

Only Node: shows up. If I do dump(title) I get NULL to show up. Not sure what I'm missing. I've copied other blocks and still nothing.

Because you've specified the template parameter in the hook_theme function the template file name should be exactly as specified block--no_athelete_match.html.twig. The underscores are converted to dashes only in the case where the template parameter is not specified in the hook_theme function.


Cron error: file could not be created Cron seems to complete, but I get a message stating that a file could not be created.

Do you have any idea about what is causing this?

You need to give the 777 directory permission to your temp folder. Like....
sudo chmod 777 -R /var/www/html/yoursite/sites/default/files/temp/

Please check images for more understanding. enter image description here

and command for give 777  permission to that directory like...


How do I convert a pre-existing site to a Composer-managed application? The latest Drush 9.x version recommends that Drupal 8 sites will be built using Composer, with Drush listed as a dependency. However, when you install Composer and Drush globally per step #1 on http://docs.drush.org/en/master/install and then proceed to step #2 Installing Drush Launcher and then try to run Drush on a pre-existing Drupal website (e.g. drush --version), then you will get:

  Drush Launcher Version: 0.6.0
  The Drush launcher could not find a Drupal site to operate on. Please do one of the following:

  Navigate to any where within your Drupal project and try again.
  Add --root=/path/to/drupal so Drush knows where your site is located.

How do I get around this problem, and make Drush work with pre-existing Drupal sites?

Follow
https://www.drupal.org/docs/develop/using-composer/using-composer-to-manage-drupal-site-dependencies#managing-existing-site
Copy-paste method:

Install Composerize Drupal with composer global require grasmash/composerize-drupal command;
Run cd path/to/drupal/project/repo && composer composerize-drupal
--composer-root=[repo-root]    --drupal-root=[drupal-root] where [composer-root] is the root directory of your project where .git is located and    [drupal-root] is the Drupal root where index.php is located.

Manually restructure pre-existing Drupal projects per discussion between Norman and Moshe on https://github.com/drush-ops/drush-launcher/issues/33
Rebuild the code base from scratch, see https://www.jeffgeerling.com/blog/2018/converting-non-composer-drupal-codebase-use-composer


Linking entities using EntityFieldQuery? I have several entities (content types) using node references to relate the content together.

I need to write queries which relate two or more nodes together through their node reference fields, then apply conditions based on fields from each of the entities and returning at the very least the nids that meet those conditions.

An example:
Engagement attaches to Event via node reference. I need to query for Engagement entities within a certain date range. The date field is defined in the Event CT. So what I want is to link the Engagement 'entity' with the Event 'entity', apply the date range condition to the Event entity, and return the nids of the Engagement entities meeting the condition.

This is one somewhat simple example, and there are other relationships which will require similar queries...

So far it seems I may need to extend the EntityFieldQuery class, but I'm not sure that this will get me what I want.

This effort is going towards converting a site I built in D6 into D7. I wrote a custom query builder to accomplish these queries by just manually building the queries. I'm attempting to convert these queries to use D7's query building architecture.

It may also be possible to write these queries using db_select and manually linking in the necessary tables (basically what I did for D6).

I'm at a bit of a crossroads. I'm going to need to make this happen. Any help at this point would be quite helpful. Does anyone have any experience with this type of problem or extending the EntityFieldQuery class?

Well your approaches sound ok ... an alternative might be the Relation module. You can define a relation such as "event-has-engagement" between any number of entity ids. A "relation" is just given a numerical id typically and then the endpoints go into a table.

The Relation module has already extended the EFQ class to encapsulate querying Relations; eg you can easily query for "Find me all Engagements for Event with some entity id". You can additionally attach drupal Fields to endpoints and query those fields in your EFQ-Relation query object.

I imagine you could loop through your existing database and build the necessary Relation(s) to migrate the data into "Relation" relations.

There are also Views integration with Relation .... but I personally stick with EFQ for alot of stuff.

Just my 2 cents ...

EDIT

there is a patch to allow the use of the migrate module to move Reference fields into Relations.


How to write a simple test case for users by using drupal_mail() function? I have written a custom module for sending email to registered users.
And I want simple test case for that users email module.

In this module I am taking a user from database and selected users preferred language and sending emails.

Same as I want .test file, I don't know how to write .test file for this module.

I am using the SimpleTest module, version 7.x-2.x (in Drupal 7).

Finding documentation about the SimpleTest module has never been obvious (also because using the Read Documentation link on the module's project page causes a 404-error ...).

Here are some pointers I've found so far:

The article about A Drupal Module Developer's Guide to SimpleTest (not sure right now how accurate it still is, but at least it outlines the main steps). Note this part in it: "... make a simple list of things that your module does. This list will translate directly to SimpleTest tests.".
The article about "How to: Write Automated Tests for Drupal", in one of it's comment near the bottom it says:

  As of now, it's the same API for the Drupal 7 core module and the Drupal 6 contributed module (http://drupal.org/project/simpletest), so this tutorial should work for both.

The SimpleTest Example that comes with the Examples module, and also includes a .test file (something you refer to in your question also). In other words: the best available documentation on this is "read the source".

Be aware:

Make sure to you take into account what's written in API.txt, i.e.:

  ... Provides a reference of the API changes between SimpleTest 7.x-1.x included with Drupal 7 core and SimpleTest 7.x-2.x.

  Modules that provided 2.x compatible tests are required to add the following attribute to their info file: testing_api = 2.x.

So SimpleTest requires a version number in the .info file, which you specify by adding that testing_api = 2.x in your .info file.
This module has Maintenance status: Unknown, Development status: Unknown

Note: As of D7, there is the PHP Unit Testing Framework module (namespace = testing). Refer to the Community Documentation about Testing (D7 and D8) / SimpleTest (D6) for quite some more details on all this.


How to return JSON data using Drupal 7 card.module

drupal_add_js('jQuery(document).ready(function () {

  currentRequest = $.ajax({
  timeout:0,
  cache: false,
  url: pageUrl,
  dataType: "json",
  type: "GET",
  success: function(data){
  $("#edit-field-currency-type-und-0-value").val(data.currency);

  }

});

ajax request module

$items['mccurr/%'] = array(
'title' => '',
'page callback' => 'ajax_currency_type',
'access arguments' => array('access content'),
'page arguments' => array(1),
'type' => MENU_SUGGESTED_ITEM,
);

function ajax_currency_type($ccode){
 drupal_add_http_header('Content-Type', 'application/javascript; utf-8');
$query = "SELECT countries_country.currency
        FROM countries_country
        WHERE countries_country.iso2 = '".$ccode."'";
$data = db_query($query);

return drupal_json_encod($data);
}

Is this the correct way to return json data. If not, how should it be accomplished? I would like to return the data back to car.module.

Thank You

To return $data in json format using Drupal-7's page callback output, you should return through :

drupal_json_output($data);

in your page callback function.
For more ref : http://api.drupal.org/api/drupal/includes!common.inc/function/drupal_json_output/7

Note : in your javascript in car.module, var pageUrl seems undefined. Make sure it is defined.


Adding class to form element via hook_form_alter for views exposed filter is not working I have a Views exposed filter, for which I am trying to add a class via hook_form_alter() with the following code:

$form['price']['#attributes'] = array('class' => array('price-hide'));

Outputting the form array with devel shows that this is adding the attribute fine; however I can only assume there is another hook_form_alter() running after my module that is wiping my attributes, as other attributes are being added, and mine never make it to the HTML output.

I've tried moving from hook_form_alter() to hook_form_views_exposed_form_alter() since I remember that hook running at a different time than hook_form_alter(); however, this doesn't seem to make any difference.

Did you check the actual markup after the page is rendered with Firebug or something to see for sure if another module's hook_form_alter() is overriding yours? If that is indeed the case then an easy way to get around is it by increasing your module's weight so hook_form_alter() in your module is called after other modules.

db_query("UPDATE {system} SET weight = 20 WHERE name = 'my_module'");

EDIT: I should say that this code should go in hook_install() and you should then reinstall your module to get the weight set properly.


How do I prevent the HTML markup in an item list from being escaped? As you can see in the code below, I try various ways to prevent Drupal from escaping the HTML and passing the link tags to the output, including the use of '#allowed_tags' and the Markup class.  None of these approaches are working.

$text = t('Administer books');

$markup = new Markup();
$link = $markup->create(Link::fromTextAndUrl($text, $url)->toString());

$items[] = $link . ': ' . t('Browse books and edit fields') . '.';

$text = t('Import books');
$url = new Url('mei_marc.import');

$items[] = Link::fromTextAndUrl($text, $url)->toString() . ': ' . t('Visit this page to import a book') . '.';

$array['mei_marc_list'] = array(
  '#theme' => 'item_list',
  '#list_type' => 'ul',
  '#title' => '',
  '#items' => $items,
  '#allowed_tags' => ['a'],
);

$txt = drupal_render($array);

$markup = new Markup();

$list = $markup->create($txt);

return ['#markup' => $list];

The output is the following.

&lt;a href=&quot;/mei_marc/list&quot;&gt;Administer books&lt;/a&gt;: Browse books and edit fields.

&lt;a href=&quot;/admin/mei_library/import&quot;&gt;Import books&lt;/a&gt;: Visit this page to import a book.

$items[] = [
  '#markup' => Link::fromTextAndUrl($text, $url)->toString() . ': ' . t('Visit this page to import a book') . '.',
];

$form['mei_marc_list'] = [
  '#theme' => 'item_list',
  '#items' => $items,
];

return $form;


Bibliography module url search as anonymous user I have a problem with the Bibliography Module module and its filter/search functionality.

Via URL it is possible to search for specific keywords:

/biblio?f[search]=Smith%2C%20S.

would search the publications for Smith, S.

If I am logged into D7 as an admin, this works perfectly. But if I change to another user or log our completely, this is not working anymore and shows me:

  No items found Modify or remove your filters and try again.

I tried to change some permissions, even gave user all the permissions an admin has (just for testing). And it works just, if I enable the ultimate permission:  Bypass content access control.

So obviously it is a permission issue. Any ideas, how to solve this issue?

It sounds like you've practically have solve the problem; the issue is with content display permissions. The question need to ask yourself is what access control is being restricted. Is it node type viewable permission? Is it view unpublished content permission?

If you're looking for way to troubleshoot this see How to debug permissions.


Get the views field value How to get the views field value and make a condition base on that field. Let say may views field is 'field_state'

Example below:

function my_module_views_pre_render(ViewExecutable $view) {
  //current user id
  $user_id = \Drupal::currentUser()->id();
  //load user data
  $user = \Drupal\user\Entity\User::load($user_id);
   // Get user state
  $state = $user->get('field_state')->getValue()[0]['value'];
  if ($state == Views field_state value) {
        $view->field['field_state']->options['exclude'] = TRUE; // exclude field for only this result ???
  }
  else{
    $view->field['field_state']->options['exclude'] = FALSE; // include field for only this result ???
  }
}

Is it possible on views pre-render or I need to use the different hook?

You should try hook_views_post_build(). I haven't tried this but I was looking at the views api and noticed that hook_views_post_build shows an example of modifying the exclude property of a field.


How can I programmatically delete a user? I'm new to Drupal development and am way over my head on this one. My company runs a subscription-based site offering market research to corporations. A company pays for a subscription and is granted a certain number of users. The person designated as primary user has the ability to add the remaining users themselves. We now need to add a function to allow them to delete a user who is no longer with their company. In doing so, we need the following to happen:

Delete the record from "users" database table
Change the author on any node created by the deleted user to "Anonymous"
Send an email to our internal support address letting them know that the user should be removed from other non-connected systems

The previous developer created a custom module for account management that allows adding users under several different circumstances. For example the user is completely new to the company adding it, which means they need to be added to our other unconnected systems as well, as opposed to providing a Drupal account to a user who is already in our other systems.
Currently a lot of stuff is being done with JavaScript using Drupal.parseJson to process the request based on the segments of the URL clicked. This was done for the sole reason of being able to update the page with the user list without a complete refresh. I personally don't care if this new function works that way, or if it needs to hit the server and refresh the page. I just need to find a way to do everything in the above list with a single click.

I've looked at the API and found user_delete, but it requires two params - $edit and $uid. The uid is no problem, but all I can find about $edit is that it's "an array of submitted form values." We're not using a form, though; our user lists are static text, and the actions all occur onclick of an href (at this point); so there's nothing being submitted. Is there any way I can fake the values of $edit? Or is there another way to do this? I'm reading about hook_user() and thinking that I'd call user_delete() somewhere to do the actual delete, and then my hook_user() implementation would handle the rest with the $op = delete param. But before I worry about how to get the other stuff happening, I need some guidance about how to call user_delete().

Is it even worth it to use user_delete()? Would it be less trouble to just write my own queries to delete the user record and change any content records to "Anonymous"?

This is not that hard, for D6 it would look like this:

Delete record from Drupal database users table;

user_delete(array(), $uid);

Change author on any content created by deleted user to Anonymous;

handled by the node module.
Send an email to our internal support address letting them know that the user should be removed from other non-connected systems

drupal_mail(...);

See hook_mail for details.


Retrieve contents from a JSON URL using cURL and display them in an HTML table I am trying to display contents retrieved from an external URL using JSON (the cURL method). So i wrote the below function:

function file_get_contents_curl() {
  //JSON URL which should be requested
  $gry_str = "?timezone=" . urlencode(date_default_timezone_get())  . "&dateFrom=" . date('Y-m-d') . "&dateTill=" . date('Y-m-d');

  $json_url = 'https://www.example.com/json/financial-calendar.json' . $gry_str;

  // Initializing curl
  $ch = curl_init();

  //Configuring curl options
  $options=array(CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => array('Content-type: application/json'),
    CURLOPT_URL => $json_url);

  //Setting curl options
  curl_setopt_array($ch, $options);

  //Getting resutls
  $results= curl_exec($ch); //Getting json result string
}

I want the contents retrieved to be displayed in an HTML table. So i am using this:

Have you tried drupal_json_decode? drupal_json_decode give you back a object that you can use for  print the variables.

https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_json_decode/7


Query parameters from $_GET vs. using the Drupal menu path Page callbacks can receive wildcard arguments through the Drupal (6 and 7) menu system and using this results in quite nice and clean URLs. Core uses this for things like loading the nodes by their node id. The alternative is to use straight query parameters from $_GET as usual in PHP. Core seems to use this in  a few places, for form redirects, the pager etc.

When would it be appropriate to bypass the menu system and just use a query parameter? What are the pros and cons of the two options for parameter handling?

There's a page with a logic that puts it together and that is determined by path. Core never bypasses the menu router. Parameters are somewhat orthogonal to this. For example, a page doesn't change in itself just because there's a form in it that uses a destination to redirect to said page so we do not add it to the clean URL. Pager is a little different because you could argue that path/to/some/view could become path/to/some/view/1 path/to/some/view/2 as it is paged but how do you differentiate real arguments (like a node id) from a pager? It's better to use a query parameter.


SimpleTesting-PDOException: SQLSTATE[42S02] I am in the processes of developing a module. I am trying to incorporate SimpleTest module in order to have a separate place that contains my code tests.

However, when I try to run a query against the tables in the database, which are build by me, I get:
PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'playground.simpletest311135TABLENAME
It tries to find a table simpletest311135TABLENAME while it should look for TABLENAME.
It always adds simpletest and some random number.

When I run queries against drupal default tables, like users and sessions, everything works perfect.
Any workaround?

Giannis

This behavior is correct. SimpleTest sets up a new site environment for every test case, using a table name prefix.

You probably forgot to install your module by overriding the setUp() method. Once your module is installed the query should work.


Adding a clearfix class to hook_node_view Ok, so what I want to do is to add a class of clearfix whenever Drupal outputs a node view with inline links.

I've been looking around and I figured hook_node_view() is what I need to alter.

Looking in node.module I find the following code:

$node->content['links'] = array(
    '#theme' => 'links__node',
    '#pre_render' => array('drupal_pre_render_links'),
    '#attributes' => array('class' => array('links', 'inline')),
);

$node->content['links']['node'] = array(
    '#theme' => 'links__node__node',
    '#links' => $links,
    '#attributes' => array('class' => array('links', 'inline')),
);

So I guessed I somehow have to add a third value to this array trough my template.php file, but none of the gazillion ways I tried worked.

You can do this in a hook_preprocess_node() function in your theme's template.php file:

function MYTHEME_preprocess_node(&$vars) {
  if (isset($vars['content']['links'])) {
    $vars['content']['links']['#attributes']['class'][] = 'clearfix';
  }
}

Remember to clear Drupal's caches once you've added the function so the system picks it up.


How to make a drupal site read-only I want to make a frozen copy of a drupal site (D6) and prevent users from making any changes whatsoever (except for the system adminstrator, if possible).  How can I do that?  I want to keep the usernames.

Hiding the login block is easy, but the login url is still available.  I've tried disabling all passwords by setting the hash to 'x', but still, someone could recover access via email, and login.  So, I want to prevent password recovery too.  I could alter all email addresses to something invalid, such as {uid}@example.com.  But I don't want the system to even attempt to send email to these addresses.

The site is used for a yearly campaign/contest.  I want to keep results of previous contests online, for reference, at a different url, and I don't want anybody changing anything.  Ideally, I would structure the site so it keeps previous contest results in the same database, but that requires extensive changes which I don't have the time to do.

Disable all user accounts apart from admin.
Disable new users from registering new accounts.
Edit permissions as necessary.

Now only admin can login, and anonymous users won't have permission to edit anything.


How is it possible that neither if nor else branch gets executed here? I'm developing one of my first drupal modules and stuck here:

$maxexp = db_result(db_query("SELECT max(expiration) FROM {uc_roles_expirations} WHERE UID=%d and rid=%d", $uid_befizeto, 4));
dpm('DB query finished');
dpm('me = '.$maxexp);

if($maxexp) {
   dpm('True branch');
 } else {
   dpm('False branch');
 }

This is a snippet from mymodule_nodeapi's case 'insert'. My problem is that I do not understand why do I see the following messages after saving a node:

DB query finished
me =
Node blah saved successfully

I simply do not understand if there is no error, how it is possible that I cannot see True branch or False branch among the messages..

It was a character encoding problem in the source file. I changed the encoding in my favorite  text editor, and the code started working.


After adding info an entity via hook_ENTITY_TYPE_storage_load, how do I access that data in hook_ENTITY_TYPE_view? I'm adding data to the node on the storage_load hook, and trying to put it into the $build on the view hook. However, when I try to get the data, I can't figure out how to do it. $node->get('i18nfiles') gives me a "Field i18nfiles is unknown" exception, while $node->values['i18nfiles'] cannob be accessed because it is protected. Sure miss simple stdClass objects about now. :) Code below.

/**
 * Implements hook_ENTITY_TYPE_storage_load() for nodes.
 *
 * @param type $nodes
 *   the array of nodes being loaded from the database.
 */
function hqq_node_storage_load(array $nodes) {
  $nids = array_keys($nodes);
  $result = db_query('SELECT fa.* FROM {node__field_attachments} fa INNER JOIN {node_field_data} nfd ON nfd.nid = fa.entity_id AND nfd.langcode = fa.langcode WHERE nfd.nid IN (:nids[]) AND nfd.status',[':nids[]' => $nids])->fetchAll();
  foreach ($result as $record) {
    $nodes[$record->entity_id]->i18nfiles['files'][$record->langcode] = $record->field_attachments_target_id;
  }
}

/**
 * Implements hook_ENTITY_TYPE_view() for nodes.
 *
 * @param array $build
 *   The renderable build array.
 * @param \Drupal\node\Entity\Node $entity
 *   The entity being rendered.
 * @param \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display
 *   The entity view display holding the display options.
 * @param string $view_mode
 *   The view mode for the entity.
 *
 */
function hqq_node_view(array &$build, \Drupal\node\Entity\Node $node, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, string $view_mode) {
  if ($display->getComponent('i18nfiles') && ($files = $node->get('i18nfiles')->getValue())) {
    foreach ($files as $langcode => $fid) {
      $lang = Drupal::languageManager()->getLanguage($langcode)->getName();
      $url = file_create_url(File::load($fid)->getFileUri());
      $options[$url] = $lang;
    }
    $build['i18nfiles'] = [
      '#type' => 'select',
      '#options' => $options,
      '#attributes' => ['class' => ['i18nfiles']],
    ];
  }
  if ($display->getComponent('i18noutdated') && $node->get('content_translation_outdated')->value) {
    $build['i18noutdated'] = [
      '#type' => 'item',
      '#markup' => '
' . t('This translation is outdated') . '
',
    ];
  }
}

/**
 * Implements hook_entity_field_info().
 * Returns an array of extra fields provided by the module.
 *
 * @return array
 *    The array of extra fields provided by hqq module.
 */
function hqq_entity_extra_field_info() {
  $extra = [];

  // Add the i18nfiles element, for translations of documents
  $extra['node']['document']['display']['i18nfiles'] = [
    'label' => t('Translated files'),
    'description' => t('A dropdown list of all languages in which a published translation is available'),
    'weight' => 10,
  ];

  foreach (NodeType::loadMultiple() as $bundle) {

    // Add also the 'language' select if Language module is enabled and the
    // bundle has multilingual support.
    // Visibility of the ordering of the language selector is the same as on the
    // node/add form.
    $configuration = ContentLanguageSettings::loadByEntityTypeBundle('node', $bundle->id());
    if ($configuration->getThirdPartySetting('content_translation', 'enabled')) {
      $extra['node'][$bundle->id()]['display']['i18ninprogress'] = [
        'label' => t('Translation in progress'),
        'description' => t('An indicator for if there are translations in progress.'),
        'weight' => 0,
      ];
      $extra['node'][$bundle->id()]['display']['i18noutdated'] = [
        'label' => t('Translation outdated'),
        'description' => t('A notification if the current translation is outdated.'),
        'weight' => 0,
      ];
    }
  }

  return $extra;
}

You access the property the same way you write it, as $node->i18nfiles. This goes through __set()/__get() which also supports non-fields.

That said, I'm a bit confused about what exactly you're doing. Your table name is node__field_attachments, so it looks like a managed field table, which would load the data automatically and making it available in $node->get('field_attachments')?

And since it's a field, you could then write a custom formatter for that field to display the data and get rid of those hooks.

It is also kind of a deprecated approach, if what I said is for some reason not possible, I'd recommend to either just load the data when you need it in hook_node_view() (with both node load being cached as well as rendered nodes being cached it's hard to compare what is more performant) or make it a computed field, but those are currently still quite painful to implement, see PathItem in Drupal 8.4.x.


Price lists on a site I'm creating a website for a company. One of the requirements is to have their price lists displayed on the website. All the data is in the MS SQL database. The question is, what would be the best way to:

Feed the data to Drupal (is it easier to connect directly to MS SQL database, or import data in XML or whatever else format?)
Display the data on the website (create a separate node for each separate price list and display the table it it? How to build that table?)

I'm using Drupal 7.

This really depends on the amount of data, how you have access to it and what you want to do with it in Drupal.

If you simply want to display it and if you have direct access to the MS-SQL database, have a look at the sqlsrv module, which provides a Database driver that allows to directly connect to MS-SQL databases. You can then set up the database configuration in your settings file and easily connect to it and fetch your data. To avoid performance issues, you can cache the result with the cache_get()/cache_set() functions if you need to.

That is probably your easiest solution, especially if you want to be certain that your price lists are always up to date (remember to set the cache expiration correctly).

When querying the data directly, you don't need to create nodes or another data structure, you expose them directly by implement hook_menu() and so on.

Alternatively, when importing the data into your site (could be useful if you want to integrate it more tightly with your site, like site search, views, ..), you might want to look into the Migrate project. It has both support for external databases and XML so that's not relevant. To store the data, you could set up content types with fields and then map that to your external data. What fields you want to use depends on the structure of your price lists. If they are simple key/value lists, you could look into Properties* and if it is more complex, maybe something like TableField would be useful.

Disclaimer: I developed Properties and am also (somewhat) maintaining it.


Hiding submenu items of a page in Drupal 6 Is there a way, in Drupal 6, to automatically hide all submenu pages? For example, suppose I have the following menu structure:

Sport

football
cricket

Is there a way I can enforce "football" and "cricket" to never be seen?

You can use Menu Block module to only show the top level items: http://drupal.org/project/menu_block

Make a normal menu, create a menu block using that menu and set the depth to '1' .


How do I remove a menu item on a module? So there's the course module for Drupal, and I want to remove one of the form items, $form['course']['duration'].

It's setup like this.

$form['course']['duration'] = array(
    '#title' => t('Duration'),
    '#type' => 'textfield',
    '#description' => t('Length of time in seconds that a user can remain in the course. Leave blank for unlimited.<br/>For a better experience, install the !link module.', array('!link' => l('Time period', 'http://drupal.org/project/timeperiod'))),
  );

  if (module_exists('timeperiod')) {
    $form['course']['duration']['#type'] = 'timeperiod_select';
    $form['course']['duration']['#units'] = array(
      '86400' => array('max' => 30, 'step size' => 1),
      '3600' => array('max' => 24, 'step size' => 1),
      '60' => array('max' => 60, 'step size' => 1),
    );
    $form['course']['duration']['#description'] = t('Length of time that a user can remain in the course.');
  }

How could I remove this from the module? I don't want non-admin users to be able to modify this. I obviously don't want to hack the core of the module.

Would I just rewrite the function? Is there anyway to do this?

This is an option in a form. You can use hook form alter in your custom module to hide it. For example

function my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'SOME_FORM_ID') {
    // you need to find out the form id . You can do so by adding a
    // print line or (dpm($form_id)) in the ..._form function in the Course module.
    $form['course']['duration']['#access'] = FALSE;
   }
 }


Query and print out random nodes in drupal How to query random nodes in Drupal 6 without views?

I can print out last nodes but random nodes are the problem.

Not sure where you are doing this, but this would be one dull ax way of doing it:

$query=db_query('SELECT nid, RAND() as _random FROM {node} WHERE status = 1 ORDER BY _random ASC LIMIT 1');
$result=db_fetch_object($query);

and then you can do whatever you want with $result->nid, another dull ax:

drupal_goto('node/' . $result->nid);

or

$node=node_load($result->nid);
// do whatever you want with it

etc


Product page with 2 times css Im trying to create a product page, but my boss wants different css for every next photo and text. I need 2 different css styles, that will aply on where the image is. Like the first block will have the image at the left and the second block will have the image on the right.

This is basicly what im trying to do :

I think I could do this with css and some custom classes? So that every added block with text and image will align itself properly without having to edit the css for every block everytime you create a new block. If someone could point me in the right direction on how to achieve this, that would be great !:)

If you are achieving this html by using views then set the rows even and odd patterns and do the CSS according to the even and odd class.


Change title of certain paragraphs in a form Please see the attached pictures. In one of my projects I have a taxonomy, which users can edit and add data. It has multiple tabs (see picture one) and each tab has multiple fields in which paragraphs can be added (see picture two).

We have different kinds of paragraphs with each different titles. Our problem is that we want to show each paragraph to the end-user (see the second picture, the button "Meting (decimaal) toevoegen") with a title of "meting" while maintaining the more descriptive titles for the admins and developers.

One option is changing the title for the end-user while maintaining the actual title in the DB. The other one would be changing the actual title in the DB and change it for the admins (setting the system name as the title).

and I've tried all kinds of hooks but can't wrap my head around this problem.

Solution:
Due to the structure of the site, I couldn't get any hook solutions to work. So I wrote my own module, which attaches the javascript below to the form.

(function ($) {
  'use strict';

  Drupal.behaviors.test_form_styles = {
    attach: function (context, settings) {
      var regEx = /(?:meting)/i;
      var paragraphTitles = document.getElementsByClassName("paragraph-type-title");
      Object.keys(paragraphTitles).forEach(function (key) {
        if (regEx.test(paragraphTitles[key].innerHTML)){
          paragraphTitles[key].innerHTML = "Meting";
        }
      });

      var submitButtons = document.getElementsByClassName("field-add-more-submit");
      Object.keys(submitButtons).forEach(function (key) {
        if (regEx.test(submitButtons[key].value)) {
          submitButtons[key].value = "Meting toevoegen";
        }
      });
    }
  }
} (jQuery));

If you want to change the title of certain paragraphs in the form:

/**
 * Implements hook_field_widget_WIDGET_TYPE_form_alter().
 */
function mymodule_field_widget_entity_reference_paragraphs_form_alter(&$element, &$form_state, $context) {
  if ($element['#paragraph_type'] == 'foo') {
    // insert more conditions
    $element['top']['paragraph_type_title']['info']['#markup'] = t('New title for paragraph type Foo');
  }
}


hook_views_post_execute already has rendered fields I have a view with a date field that I would like to move back a few minutes e.g. $timestamp - 60.

I run hook_views_post_execute() but, when I look at $view it already has rendered markup in it:

$view->result[0]->field_field_end_date[0]['rendered']['#markup'] ==>> '0 sec

The documentation states "This hook is called right after the execute process. The query has been executed, but the pre_render() phase has not yet happened for handlers."

What gives?

To solve this problem. I need to add/subtract from the "raw" value before it is rendered.

How can I do this?

Thanks.


Hook_view_pre_render(&$view) to alter field_title link locations I have a function in a custom module:

function mashavumodule_views_pre_render(&$view) {
    dsm($view);
}

After clearing the cache, I had a dump of $view but know my question is:

If I want to alter the location the the field_title links to, what part of the $view array should I alter and is hook_views_pre_render the best hook to use to do this?

You don't specify what type of changes you want to make, but in general, yes, hook_views_pre_render is a good place to change the way the View looks when actually rendered.

You will find the hits from views in $view->results, and that is where you will want to make changes.

Note though that you may not even need the hook, you can use replacement patterns, as in this answer to accomplish many simple, and some advanced, changes to fields.


How to display a message even when user is logged out? I'm using Drupal 7, i want to display a message drupal_set_message, when i click on a button for example.

When i'm logged it works well, but for this same button (or page) if i'm not logged in, it doesn't display any message.

This is my case : i've created a mobile application that used a backoffice. this backoffice is built using drupal. i've created a page "reset password" user can click on "reset password" from the mobile app, an email sent with a link to my custom page : reset_pwd

this page contains inputs to reset new password :

$items['reset_psw'] = array(
'title' => '',
    'description' => '',
    'access arguments' => array('administer reset_psw'),
    'file' => 'system.admin.inc',
    'file path' => drupal_get_path('module', 'system'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('reset_mdp_formulaire'),
);
return $items;

the form to reset password :

function reset_mdp_formulaire ($form, &$form_state){

$form = array();

$form['confirm_pass'] = array(
    '#type' => 'password_confirm',
);

$form['valider'] = array(
    '#value' => t('valider'),
    '#type' => 'submit',
);
return $form;
 }

the function submit :

function reset_mdp_formulaire_submit ($form, &$form_state){
$new_pass = $form_state['values']['confirm_pass'];
dsm("error");
if(strlen($new_pass) < 8){

    drupal_set_message(t('Password must be 8 characters at least.'), 'error'); <== not shown when logged out
    return;
}
 }

Just want to check if new password is less than 8 characters, and display error message

Thank you all.

Try removing the return statement at the end of your submit or even replacing it with a drupal_goto('reset_psw').

There are lots of similar questions on google and S.O., you could have a look.

UPDATE

You should use the validate handler for such a case, this simple example should get you going https://www.drupal.org/node/717740


Why is Solr throwing exceptions on unfound text files after insttalling Apache Solr Multilingual config files? I have used Apache Solr Multilingual to generate Solr config files; however after installing these files Solr throws many exceptions of the form :

Can't find resource '<text_file_name>_<lang>.txt'

For example

Can't find resource ' mapping-ISOLatin1Accent_fr.txt'

Is the configuration of such files not the purpose of the Apache Solr Multilingual module ?

Is the configuration of such files not the purpose of the Apache Solr Multilingual module ?

Seems the answer is 'no'.  I manually created 6 text files per language in my solr config and solr started without complaint.

Each language needs each of these text files:

compoundwords_<lang>.txt
mapping-FoldToASCII_<lang>.txt
mapping-ISOLatin1Accent_<lang>.txt
protwords_<lang>.txt
stopwords_<lang>.txt
synonyms_<lang>.txt

where 'lang' is the Drupal language code which can be confirmed by looking over the schema.xml kicked out by Solr Multilingual Module . for example: 'en', 'es', 'de' ...

I copied the contents of each of said files from the Solr Multilingual Module config. forms


Admin denied access to Ubercart Store when running Ubercart SSL I am running the Ubercart SSL module (not Secure Pages) for my Drupal 7.12 site.  I am unable to checkout an order as admin, and I get an access denied message when I try access my store.

Ideas?

I would go with the Secure Pages module http://drupal.org/project/securepages and I've create a small write up on how to set up Secure Pages with UC http://drupal.org/node/1586258