Wordpress comment form in Drupal? Wordpress comment form contains a text field where visitors can enter a link to their website. Is there any module ( or simple way )to achieve the same thing in Drupal ?

What I'm really looking for is a solution that:

adds a new field to the comment form that needs to be validated as a link
when the comment is displayed , the username needs to link to the website entered in the form , not to the user profile as it does by default.

This is indeed very simple. You can add fields to the comment entity.
Have a look at these explanations of how o achieve this:

http://kps3.com/thots/adding-new-fields-to-comments-in-drupal-7

https://www.ostraining.com/blog/drupal/entities/


Views node count Taxonomy term as a field There are a few other posts about this in general but none of them explain how to make this a field so i can keep my other fields such as Title and Image.

I am making a video site, and the taxonomy 'category' has an image attached to each term. Therefore i want the number of nodes tagged with a specific category to show but also have all the other fields i use.

I tried solutions found here: Views and node count for taxonomy terms

The above suggestions seem to ignore my image and title fields i currently have styled

hope this makes sense

https://www.youtube.com/watch?v=w22Utjm-chs

This video explains the process.

I found my old fields didn't work anymore once i added aggregation so, you might want to remember and fields and styling you have made because you might have to rebuild the fields once aggregation is turned on.

add a relationship (under advanced tab) 'Taxonomy term: Content with term'.
turn on aggregation (advanced tab at the bottom).
create a field 'Taxonomy Term: Name'.
add any other fields associated with the taxonomy such as image or any others you created.

Style everything and done!


Alter field value before render In Drupal 8, I was thinking that's a simple task but it's not :

function hmytheme_preprocess_field(&$variables, $hook) {
    $element = $variables['element'];
    if (isset($element['#field_name'])) {

        if($element['#field_name'] == "bar"){
             element['#items']->value ="foo";
             //or
             element['#items']->set(0,"foo");
        }
    }
}

this is not afecting the render.
How to ?
I don't whant to save the altered value

It's too late to change the field object, because the field is already prepared for rendering. You have to find the field value inside of the render array, for example in #markup, and change it there. Where you find the value depends how your field display is configured in the view mode.

  While possible, there's often a better way. You could make your own
  formatter that returns the structure that you want. #text is a
  formatted text field, you could make a filter that transforms the text
  the way you want. Depends on what you want to do exactly.

(Comment from @Berdir)

See the drupal docs how to create a custom field formatter:

https://www.drupal.org/docs/8/creating-custom-modules/create-a-custom-field-formatter


How can I make a response cachable by browsers? I am working on a Drupal Controller implementation that would return a generated image as response. I used Symfony's Response and I was trying to add ETag header to it:

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class MyController extends ControllerBase {

  public static function viewGraph(string $id, Request $request) {
    $response = new Response();
    $response->setEtag($etag); // some etag genrated from $id
    if ($response->isNotModified($request)) {
      return $response;
    }
    // ...
    return $response;
  }

}

I expected to see the "ETag" header in my response. But there is nothing. I've even tried CacheableResponse and it didn't work as well.

What's wrong with my approach? What is the right approach to it?

FinishResponseSubscriber overwrites the ETag header, unless your response meets certain conditions. That is it has to be cacheable and provides a custom Cache-Control header. When testing the code make sure you have browser caching enabled (in the performance settings).

Example:

  public function view() {
    $response = new CacheableResponse();
    $response->headers->set('Cache-Control', 'public, max-age=60');
    $response->setEtag('123');
    return $response;
  }

Besides browser caching you might also want to set Drupal caching data to invalidate the cached response when the content becomes outdated, see for example Invalidate cache on a REST endpoint.


I need to prevent the translation of admin + toobar interface Hello I am using Internationalization module. I want to keep the admin and the toolbar in English despite the language variable, despite the node translation operation. Is it possible?

You can use the Administration Language module:

  This module lets the administrator see all administration pages in her preferred language.

  You can use this to display the frontend of the site in one language and still keep most of the backend in English (or another language of your choice).

  You can use the standard Languages page to choose the language of the admin pages.


Omega Subthemes, Modernizr, and Javascript placement I am embarking on a new project and have decided to use Omega as as my base theme.  I have a few related questions to overriding html.tpl.php in my subtheme.

I normally use Modernizr for HTML5 feature detection and to provide the HTML5 Shiv functionality.  Are there any problems with replacing the conditional HTML5 Shiv with always including Modernizr?  Are any of the features incompatible with the Javascript that Omega provides (like the Media Queries extra)?

Second, I normally place Javascript at the bottom of the page.  Will this interfere with any of the JS that Omega relies on?

I have now done a few Omega based sites, and have some answers about these.

I have not run into any problems with moving the print $scripts to righe before the  closing </body> in html.tpl.php.  That said, this question on SO has a good discussion on wht this may be outdates advice.

I have also had good results replacing the HTML5 shiv in html.tpl.php with

<?php if ($modernizr): ?>
<script src="<?php print $modernizr; ?>"></script>
<?php else: ?>
<!--[if lt IE 9]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
<?php endif; ?>

and using this in a template_process_html

if (theme_get_setting('mytheme_use_modernizr')) {
  $vars["modernizr"] = "/" . path_to_theme() . "/js/modernizr-2.0.6-min.js";
}

and then wiring up a custom theme variable in theme-settings.php

$form['mytheme'] = array(
    '#type'          => 'fieldset',
    '#title'         => t('mytheme settings'),
);

$form['mytheme']['mytheme_use_modernizr'] = array(
    '#type' => 'checkbox',
    '#title' => t('Use Modernizer instead of HTML5 Shiv?'),
    '#default_value' => theme_get_setting('mytheme_use_modernizr'),
);


Hook to add new field to node form I have a blog content type which has a field for authors- (these are pull from a separate content type). multiple values are allowed.
i am trying to develop a module that will pull the authors email address and display it next to the authors name when ever a new author is added in the blog create form so users can edit the email on the fly while creating a new blog post.

i need some pointer as to the right hooks to use for these.
Thanks in advance.
See screenshot below of what am trying to archive

I've never used it myself -- but see Inline Entity Form which should allow you to reference an existing author, or implement that modules form controller class to show an author and email field to create the new author as needed.

  Provides a widget for inline management (creation, modification,
  removal) of referenced entities. The primary use case is the parent ->
  children one (product display -> products, order -> line items, etc.),
  where the child entities are never managed outside the parent form.
  Existing entities can also be referenced.

From the README

Integrating with Inline Entity Form
-----------------------------------
An entity type can add support for this module by declaring the
inline entity form controller class in its entity info:

$entity_info['commerce_line_item']['inline entity form'] = array(
  'controller' => 'CommerceLineItemInlineEntityFormController',
);

The controller needs to extend EntityInlineEntityFormController and at least
override entityForm() to provide a function entity form.


Where is views exposed form's submit handler located? When views exposed form is submitted without ajax it redirects to somepage like http://example.com/reports?taxonomy=tid&date=27%20F6%20f2005 etc.

I am curious to know ,in views module,inc file where it's submit handler is located,where is ajax callback?

I tried for some hours but no luck.

I know about hooks like form alter but that's not a concern.

I have no specific requirements,just for drupal learning :)

All of its functions are handled in programmatic way. You can look all functions are declared in theme.inc file located at module/views/theme/theme.inc location. Its hard to understand that core functions. But if you want to play with these functions then you will have to use the hooks .

NOTE: Never try to change any core file.


Hiding the previous instance in a Multi value field collection embedded widget I have a multi valued nested field collection with many field in it like checkboxes ,image etc.

Now when adding/editing a node looks clumsy when multiple values added for that field collection.

So I decided to hide the previous instance when add another is clicked , which i achieved by hacking and preprocessing the theme_field_multiple_value_form in the core field.form.inc by not passing the item to drupal_render(), but now what I get is empty draggable row that is not good.

So i managed that by just render a markup there which is not an issue now.

now the values entered to the field collection is not saved if it is hidden.

so what I'm technically asking is how to hide a field but still process it on saving the node.

OR may be is there any alternate ui for multi value nested field collection?

Note : I have tried hide(), #access & skipping from drupal_render.

I think the solution is within the theme layer. By extending the admin theme (i.e. creating a sub-theme) you could create the desired behaviour using CSS and JS.


How to reference a image field and get it's file URI? I have a paragraph type rn-accordion (rn-acc.html.twig), that has a entity reference revision to rn-accordion-section which houses a bunch of different fields. One of which is an image field (bp_image_field); however I am unsure how to reference this field in my twig file. So far I have tried:

but the output is always

Can someone help steer me in the right direction?

I would suggest not doing this, as you lose the benefits of image styles (the built-in image manipulation feature).

Suggesting you make a hook for this template, pick out the url from the source field, render an image with Drupal APIs, and make the result available as a variable on the template.


Add a taxonomy term to many vocabularies Is there is any way to add one term to many vocabularies with the same name and same id in drupal 7

I don't think it's possible. It's always one to one relationship between vocabulary and term...

If you see taxonomy_term_data table which stores term id and vocabulary id reference below..

tid is primary key which means always unique. So, you can't have another row which points to different vid.

Below schema definition in taxonomy.install confirms same..

  $schema['taxonomy_term_data'] = array(
    'description' => 'Stores term information.',
    'fields' => array(
      'tid' => array(
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'description' => 'Primary Key: Unique term ID.',
      ),
      'vid' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
        'description' => 'The {taxonomy_vocabulary}.vid of the vocabulary to which the term is assigned.',
      ),
      'name' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
        'description' => 'The term name.',
        'translatable' => TRUE,
      ),
      'description' => array(
        'type' => 'text',
        'not null' => FALSE,
        'size' => 'big',
        'description' => 'A description of the term.',
        'translatable' => TRUE,
      ),
      'format' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => FALSE,
        'description' => 'The {filter_format}.format of the description.',
      ),
      'weight' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => 'The weight of this term in relation to other terms.',
      ),
    ),
    'primary key' => array('tid'),
    'foreign keys' => array(
      'vocabulary' => array(
        'table' => 'taxonomy_vocabulary',
        'columns' => array('vid' => 'vid'),
      ),
    ),
    'indexes' => array(
      'taxonomy_tree' => array('vid', 'weight', 'name'),
      'vid_name' => array('vid', 'name'),
      'name' => array('name'),
    ),
  );


How to open the view and edit page inside the colorbox? I am using an full calendar with event as a node.

I have disabled the overlay module.
In the full calendar settings->colorbox options, I have enabled 'open events in a colorbox'

Now when I click on any events in the full calendar it opens the node view page in colorbox which has two tabs view and edit .

When I click on edit tab , it opens into a new page instead of loading inside the colorbox.
How can I achieve loading of view and edit tab inside the colorbox and prevent the redirect which occurs when clicked on edit page? .

You need to specify more precise which html elements of the destination page (the page containing the event) should be rendered.

i guess changing the id selector to

#content .content

will do the job.


How can i override all node book/book_alias usng alias How can i override all node "book/book_alias" using View
when i tried "contextual filter" not provided for alias
i must use a node id rather then book_alias.

Any Solution to override a multiple node using alias ?

Quick and fast method for D7 by using Pathauto 7.x-1.2, VBO 7.x-3.0 and Admin Views 7.x-1.0:

drush dl views_bulk_operations
drush en views_bulk_operations
drush dl admin_views
drush en admin_views

Go to /admin/content, edit the view with contextual menu on top right of view.

Then Click the "Bulk operations: Content" field. Then click the "Update node alias" checkbox and save.

Go back to /admin/content and select all nodes

Choose an operation, then select "Update node alias", then execute!

===================

Although pathauto in 6.x-1.x provides a utility to "bulk generate paths", this one-off action fails on thousands of nodes, and does no "batch" processing.
This results in timeouts, memory overruns, and failure. (Pathauto token generation can be expensive, and becomes painful over thousands of nodes)

This "batch" issue is being addressed in 6.x-2.x & 7.x

Until then, you still have an alternative, and it's better!
The pathauto 6.x-1.x module already exposes the pathauto path-rebuilding function as a node operation that can be applied through the content management screen, or if using "Views Bulk Operations" - as a bulk operation there.

This means you will be able to select only and all nodes of a desired content type, and do them all in a "batch" mode without processing overruns.
Get Views Bulk Operations

See the project itself for install and configuration options.

Once enabled, a new action "Update URL alias" becomes available as an available action within VBO. (when editing the view, and the Style: Bulk Operations settings)
You will want to turn that on.

At the same time, ensure that VBO will use "batch mode" ( To execute operations: "Use Batch API" )

Once that is on, the update task will show up on the VBO screen, and you can, for example, choose to regenerate updated alias paths for 3000 'Article' type nodes without doing the same for 15000 'Image' type nodes.
Advanced usage

The global pathauto settings do not allow for any extra logic, though sometimes you want to to different things to different content (especially if working with bulk imported content, or re-architecting)

You can set the pathauto settings to agressively discard or overwrite any existing paths, then trigger the bulk update over a selection of pages you have defined through VBO. (ones you really need to rewrite)
After that you can change the global pathauto settings to just 'update' or 'leave existing aliases' for other content from then on. Or vice versa or something else.
Without VBO, you could do one or the other of these updates, but not both.
It takes a few more steps, but it's possible.


Illegal choice error in log file I got this error in my log file.  It was on a select element for an exposed View filter:

Illegal choice 24alert(0) in field_item_type_tid element.

Is it someone trying to hack my site?

Someone (or something) is trying to submit a value for field_item_type_tid that isn't in the list of allowed options for that field (as prepared by the form API prior to rendering the form/element).

The FAPI is objecting to that attempt (as it should; it's a security feature), so the user will receive the standard "Illegal choice" error message.

It might be an attempt at a hack, it might be something weird instigated by a user/browser extension, or it might be the result of some javascript trying to change the allowed values on the client-side, without informing the backend that the options need to change.

Without analysing the page and all the involved parameters it's only speculation, though. It might be being caused by any of the above, or perhaps some other external factor.


Got error message from Deleting Vocabulary I'm trying to delete one of the Taxonomy's Vocabulary on Drupal 7.26. It would not allow me to delete and turn out an error message. How can I fix this and be able to delete Vocabulary?

  Fatal error: Call to undefined function drpual_static_reset() in
  /sites/all/modules/metatag/metatag.module on line 271

Please see this post https://drupal.org/node/1719600 as it explains that the function has a typo. I would recommend updating to the latest version of the metatag module.


Adding assets (css/js) for a custom module block (and withstanding a cache enabled install) I've created my own block which calls a hook_theme implementation which then prepares some data and then renders myblock.tpl.php

All of the above is working fine but my module does have some required assets, specifically some css & js files, currently I was doing drupal_add_css/js in my hook_block($delta = 'view') but I've discovered that both the hook_block and hook_theme do not get called when the Admin > Config > Performance - Enable Block Cache has been turned on.

Obviously when I clear the cache the first load of a page (with my block included) loads all assets properly, but anon-users etc do not see any of my assets.

How should I be including these assets in a way that would withstand caching and only add assets on a page which includes my block?

Thanks!

Modules can report how Drupal should cache the output of a module, through the use of a set of constants.

The constants should be used as in the following example of hook_block():

function mymodule_block($op = 'list', $delta = 0, $edit = array()) {
  if ($op == 'list') {
    $blocks[0] = array(
      'info' => t('Mymodule block #1 shows ...'),
      'weight' => 0,
      'status' => 1,
      'region' => 'left',
    );
    // BLOCK_CACHE_PER_ROLE will be assumed for block 0.

    $blocks[1] = array(
      'info' => t('Mymodule block #2 describes ...'),
      'cache' => BLOCK_CACHE_PER_ROLE | BLOCK_CACHE_PER_PAGE,
    );

    return $blocks;
  }
  // …
}

The constants that can be used are:

BLOCK_NO_CACHE: The block should not be cached.
BLOCK_CACHE_GLOBAL: The block is the same for every user, in every page it is shown.
BLOCK_CACHE_PER_ROLE: The block could change basing on the roles the user who is watching the page has.
BLOCK_CACHE_PER_USER: The block could change basing on the user who is watching the page.
BLOCK_CACHE_PER_PAGE: The block could change basing on the page being viewed.

You could use some of the constants together; for example, if the block changes basing on the page, and the user who is watching the page, you can use BLOCK_CACHE_PER_PAGE|BLOCK_CACHE_PER_USER.

In Drupal 7, those constants have been renamed, and a new constant is added; this is the list of the constants used in Drupal 7:

DRUPAL_NO_CACHE
DRUPAL_CACHE_GLOBAL
DRUPAL_CACHE_PER_ROLE
DRUPAL_CACHE_PER_USER
DRUPAL_CACHE_PER_PAGE
DRUPAL_CACHE_CUSTOM

The last constant is used to report to Drupal 7 that the module uses its own cache. For Drupal it has the same effect of using DRUPAL_NO_CACHE.


Is it possible for the front page view to use a different image style for each teaser item? Im trying to build a complicated grid ui with a different image size and aspect ratio for each consecutive item in the list. How can I select a different image style for each item?

First, you need to go one level up, don't think about image styles, think about enity view modes. Then you can control which image style is used for each view mode.

The reason for that is that entity output is cached by view mode. You could theoretically alter each entity and switch out the view mode, the data might actually even be available there, but it will fall apart when the same entity is suddenly in a different position but still cached.

You could try to implement preprocess or another views hook to change the view modes programatically in the render array. That will however not be configurable if that is a requirement.

What we build for our project is a views display plugin that allows to not select a single view mode but one for each entity that is being displayed.


drush --quiet cron generates watchdog notices We have started using drush cron to manage our basic Drupal sites' scheduled tasks. I set this up using the guide at http://docs.drush.org/en/master/cron/ and it seems to be working well, except that these messages are generated on every run:

 [notice] WD Periodic: No periodic processes to run.
 [notice] WD cron: Cron run completed.

despite passing the --quiet option.

Is there a way to silence this output while still being made aware of any issues that come up with the cron task in future? We can redirect these two lines to standard out and filter on them but I wanted to find out if there is something about our Drupal setup that is causing the lines to be generated.

Our cron line is almost identical to the one in the article, but for the sake of completeness I've included it below:

0 * * * * apache /usr/bin/env PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin COLUMNS=72 /bin/drush --root=/path/to/our/drupal/site --uri=our.drupal.url --quiet cron

The drush version is 9.0-dev. Drupal version is 7.50.

Thanks for any suggestions you can provide.

drush cron simply calls the Drupal cron function. Drupal is initiating the watchdog messages; Drush implements system_watchdog() to convert these messages to drush log entries (Drupal 6 and 7).  If you set the option --watchdog=0, then these messages will not be printed by Drush.

If there is a problem with cron, then $? should still be set to a nonzero value when drush cron exits, and the watchdog messages will still be available in the Drupal Watchdog log (visible via drush watchdog).

If you need a finer level of control over the error behavior of Drush cron, please submit a feature request in the issue queue.


Change the default password encryption The default password encryption in Drupal 6 is MD5. Is it right? I want to change it to something more difficult like crypt and sha1.

Is there any module for this purpose, or do I have to hack the core myself?

Yes, you can look for the Secure Password Hashes module.

This module stores password hashes securely.
The default password hashes in Drupal 6 (and before) are rather insecure. MD5 is easy to crack, should an attacker find a database dump or gain access to your database. This module implements secure password hashes using the phpass password hashing method - multiple rounds of hashing and salting that make reversing the hash significantly more difficult to break by brute-force attack. This is the same approach that is used for Drupal 7.


Where is links__node__node() defined? I'm trying to figure out how I can alter the theme for read more links. This is what goes on inside the node.module ~ line 1380.

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

I know where are several ways to remove the read more links and add your own, but I just want to know where that theme function is stored and how I can override it like it can be done with fields using theme_field().

The "links__node__node" theme function is not defined from any Drupal module. If a module defines a theme function matching that name, then Drupal will use it; otherwise, the function that is going to be used is theme_links().

In your theme, you can define both the theme functions. The difference is that theme_links() is generally used, while the other theme function is used just in a specific case.

function themename_links__node__node(&$variables) {
  $links = $variables['links'];
  $attributes = $variables['attributes'];
  // …
}

function themename_links(&$variables) {
  $links = $variables['links'];
  $attributes = $variables['attributes'];
  $heading = $variables['heading'];
  // …
}


How to delete a taxonomy term with a broken URL I was trying to change the URL pointed to by a taxonomy term so that clicking on it would take the user to a map. However, after changing the URL I am no longer able to go into the term to edit the value.
How can I switch the URL back, or delete the term altogether when I can't access it's edit screen?

To solve this I was able to open up the database and view the url_alias table.

From there I simply changed the url back to the automatically generated url that I overwrote.


How to create Dummy Content with certain data restrictions (specific date ranges, users, values, ...) I know about the Devel Module's capability to generate random content (BUT almost no control over the data entered) and also about the D7 Devel script which is a possibility, but i'd like to have a module and not a script. The Dummy Content Module creates the content only upon installation, thats why it does not help me either cause i want to create it via a menu option like it is with the Devel Module.

I searched high and low but could not find a module that gives me that option, can anybody give me a hand here?

Problem

Creat Dummy Content with specific ranges for

date fields: e.g. between "now" and "now +10 day"
number fields: e.g. between 10 and 20 step 2
...

Quick solution that worked best for me in the end:

The solution i gave before was indeed the best one to have a general solution and use the mechanisms that were used in the devel module, but what worked best for me in the end was to just use the HOOK_node_presave to validate the nodes that were created by the devel module.

function MY_MODULE_node_presave($node) {
  // only do this for my_type, and only for nodes created by the devel module
  if ($node->type == 'MY_TYPE' && isset($node->devel_generate)) {
    // apply the limitations, e.g. use values between 2 and 8 in our field
    $node->field_my_field["und"][0]["value"] = mt_rand(2, 8);
  }
}

In case a node of the type MY_TYPE is generated by the devel module (verified by checking the devel_generate property) we give the field field_my_field a value between 2 and 8. This is not possible with the devel module, but we can apply this custom restrictions here and modify the node before it is saved.

So the devel module will create the node as usual, but the function above will modify its values to our needs before it is being saved to the DB.

This has the desired effect although it is hard coded in our custom module, it does the trick.


hook_node_access() doesn't work for anonymous users I am new to Drupal 7, I am still unable to understand hook_node_access operation
I am trying to give view access to the basic content types nodes for anonymous users but it is not working. It is still giving access denied.
function modules_session_node_access($node,$op,$account) {
  $type = is_string($node) ? $node : $node->type;
  $is_anonymous = !user_is_logged_in();
  if ($op == 'view' && $is_anonymous && $type='basic') {
    return NODE_ACCESS_ALLOW;
  }
  return NODE_ACCESS_IGNORE;
}

There is a typo in the code. The code would grant the access to anonymous users when the operation is view, but for any content type.
  if ($op == 'view' && $is_anonymous && $type='basic') {
    return NODE_ACCESS_ALLOW;
  }

The last part of the if() statement (&& $type='basic') always evaluate to TRUE.
That apart, hook_node_access() implementations aren't invoked for pages showing more than a node and when:

The user accessing the node has the bypass node access permission
The user accessing the node doesn't have the access content permission

In the first case, the user has the permission to access the node even if one of the hook_node_access() implementations doesn't give the user the permission to access it. In the latter case, the user doesn't have the permission to access the node even if all the hook_node_access() implementations give the user the permission to access it.
Even if the anonymous users would have the access content permission, a single hook_node_access() implementation giving them the permission to see a node isn't sufficient for anonymous users to see it. It's enough another hook_node_access() implementation returns NODE_ACCESS_DENY for anonymous users, and the anonymous users won't access the node.
The function invoking hook_node_access() is node_access(), which contains the following code. (Comments are mine.)
// Users with the "bypass node access" permission always have access to the node.
if (user_access('bypass node access', $account)) {
  $rights[$account->uid][$cid][$op] = TRUE;
  return TRUE;
}

// Users without the "access content" permission will never have access to the node.
if (!user_access('access content', $account)) {
  $rights[$account->uid][$cid][$op] = FALSE;
  return FALSE;
}

a comment after the invocation of hook_node_access() make clear in which case the access is granted.

We grant access to the node if both of the following conditions are met:

No modules say to deny access.
At least one module says to grant access.

Then, if a node is unpublished, anonymous users cannot access it. Only the user who created it can view it, if the user has the view own unpublished content permission, which isn't checked when the author is the anonymous user.
// Check if authors can view their own unpublished nodes.
if ($op == 'view' && !$node->status && user_access('view own unpublished content', $account) && $account->uid == $node->uid && $account->uid != 0) {
  $rights[$account->uid][$cid][$op] = TRUE;
  return TRUE;
}


How do I hide title of a node? I have tried doing this in hook_node_view or  hook_node_view_alter with no luck:

I have tried things like:
     unset( $node->title); or
      $node->title ='';

note: my node was created using panel nodes

The Exclude Node Title module has that functionality if you'd prefer a non-code solution.

  This module handles a very simple functionality, decide whatever to exclude a node title from full node page or node teasers.


add Global PHP code field to Views on condition I want to add PHP field to View based on condition that certain logic field in content item is checked. How can I check that it is checked in PHP code?

More concisely: how can I check if some product's field is checked in Views?

The View is just showing list of contents

I think you have not followed a correct way, these are the steps to create a custom field on the basis of value of an existing text field are :

Add a field in any content type on basis of whose value you want to
display a custom field.
Add contents of that content type filling value of newly created
field say its a checkbox having 0 or 1 as its value.
Create a view of that content type.
Add fields and a custom field having some value, say ;

<?php
echo 'Astha Chauhan';
?>

in output code field.

Then add a filter of type Global:PHP and add a filter code
accordingly:

  <?php
      if ( $row->field_test_field == '2') {
       return $row->php;
      }
      else {
       return 'null';
      }
   ?>


Custom actions kicktart commerce cart Hi I've been struggling with this issue for a while, look for it from google to the official Drupal Commerce documentation without any luck. So i have a cart and I am customizing the looking and the behaviour, tpl and preprocess function have been my friend until now.

I need to custom the bottom actions of the cart

But I haven't been able to look for a tpl and I still don't know how to change the behaviour of this actions if you can give a hint of how to:

Change the value of the  of both of this action
How to add more actions.
How to change the behaviour of the items.

BTW. I look for it on the setting of the Views without any luck, but I'm kind of noob in drupal. Thanks!

You need to create a custom module and use hook_form_alter to modify the form.

That particular form id is views_form_commerce_cart_form_default, so in your custom module, you could have something like this:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  //cart form
  if (strpos($form_id, 'views_form_commerce_cart_form_default') === 0) {
    //change the value
    $form['actions']['submit']['#value'] = "New Update cart value";
    $form['actions']['checkout']['#value'] = "New Check-out Value";

    //add additional callback functions on the checkout button
    $form['actions']['checkout']['#submit'][] = 'mymodule_callback';

    //replace callback functions on the checkout button
    $form['actions']['checkout']['#submit'] = array('mymodule_callback');
  }
}

Refer to the Form API Reference to see what else you can do.


How copy file field data from one file field to another using Views Bulk Operations? For example, you want to copy the data for a file field with the machine readable name field_pdf into field_attachment

I been following the examples, but there is not an example for this action.

Is this possible with VBO and if so what is the code?

I would very much like to resolve this problem for myself and update the page on d.o

Here is a pure site-building approach:

Install File Field Rules
Define a new Rule Component (an "Action set"), named e.g. "Copy file"

Define at least one input/parameter, e.g. node_source
Define optionally a second input/parameter, e.g. node_target

Configure your Rule component to perform a "Copy file field contents" action, with the following settings:

Source entity => e.g. 'node_source'
Destination entity => e.g. 'node_target': This depends on your case, you may even want to copy a file inside the same node, between different fields. You can in that case, use 'node_source' again as your target entity.
Select the Source and Destination fields
Save our component and you are done with Rules configurations.

Back to your View and VBO field configuration, you can now select the "Copy file" action.

I tried this and was able to copy an image file between two different article nodes, hope it works for you too.


Adding a CSS, JS and HTML code to a block Using Drupal 7.2 I've successfully added a Google Adsense banner to my website by creating a new block with admin/structure/block/add and puting Google's code as "raw HTML" (added that "raw HTML" format first in admin/config/content/formats/add) there:

Now I'm trying to add another block containg a Like-button by the russian social network Odnoklassniki.ru:

My problem is - they want me to add:

Head:

<link href="http://stg.odnoklassniki.ru/share/odkl_share.css" rel="stylesheet">

Body:

0

And call:

How could I do it the best way please? (it would be good not to have it updated every time I update the Drupal version)

When I just try to put all 3 pieces listed above into a block (as I did for Google banner) - the button doesn't work.

The link and the script can be added through drupal_set_html_head() head

drupal_set_html_head('<link href="http://stg.odnoklassniki.ru/share/odkl_share.css" rel="stylesheet">');

On clicks are not good practice in drupal. Behaviors are used in stead.

So in your block you can output

  0

You can then set a couple of behaviors in your own script, which you can put in a file and add using drupal_add_js()

 Drupal.behaviors.my_module = function (context) {
   // This will load on page load
   ODKL.init();
   // This will attach a click handler to the links
   $('.odkl-klass-stat').click(function() {
   ODKL.Share(this);
   return false;
   });
 };


Default entity ID for _entity_view in routing.yml I've a custom content entity (created using Config pages module) which is used as a welcome screen / dashboard. Privileged super editors can edit those content entities, normal editors can only view it.

The config pages module itself does not provide routes to view modes (only to edit forms), so I used the core's generic _entity_view to create routes for the normal editors myself:

This is my_module.routing.yml

my_module.view_config_pages:
  path: '/admin/config_pages/{i_dont_want_no_parameter}'
  defaults:
    _entity_view: 'config_pages.full'
  requirements:
    _role: 'authenticated'
  options:
    _admin_route: true
    parameters:
        i_dont_want_no_parameter:
          type: 'entity:config_pages'

This works with URLs like /admin/config_pages/1, /admin/config_pages/2 etc... But I want to create nice, parameter-less, named routes to specific entity IDs. Something similar to my dummy-code below

my_module.view_welcome:
  path: '/admin/welcome'
  defaults:
    _entity_view: 'config_pages.full'
  requirements:
    _role: 'authenticated'
  options:
    _admin_route: true
    parameters:
        yeah_no_parameter:
          type: 'entity:config_pages'
          id: 1
my_module.view_stats:
  path: '/admin/stats'
  defaults:
    _entity_view: 'config_pages.full'
  requirements:
    _role: 'authenticated'
  options:
    _admin_route: true
    parameters:
        yeah_no_parameter:
          type: 'entity:config_pages'
          id: 2

Can this be done with _entity_view in YAML files without coding a custom controller?

The default ID can be set in the defaults section, here is an example:

my_module.view_dashboard:
  path: '/admin/dashboard/{my_entity_id}'
  defaults:
    _entity_view: 'my_custom_entity.full'
    my_entity_id: 123
  requirements:
    _role: 'authenticated'
    my_entity_id: ^[0-9]+
  options:
    _admin_route: true
    parameters:
      my_entity_id:
        type: 'entity:my_custom_entity'

my_module.view_stats:
  path: '/admin/stats/{my_entity_id}'
  defaults:
    _entity_view: 'my_custom_entity.full'
    my_entity_id: 456
  requirements:
    _role: 'authenticated'
    my_entity_id: ^[0-9]+
  options:
    _admin_route: true
    parameters:
      my_entity_id:
        type: 'entity:my_custom_entity'

This solution creates nice URLs without any controller.


How to pass argument in service with dependency injection In a custom module, I have a custom service that uses GuzzleHttp\Client service.

mymodule.services.yml:

services:
  mymodule.mymodule_call:
    class: Drupal\mymodule\MyModuleCall
    arguments: ['@http_client']

The MyModuleCall is using dependency injection and start like:

namespace Drupal\mymodule;

use GuzzleHttp\Client;

class MyModuleCall {

  protected $client;

  public function __construct(Client $client) {
        $this->client  = $client;
  }

}

As explained in the GuzzleHttp documentation (http://docs.guzzlephp.org/en/latest/quickstart.html), we can pass an argument to the Client constructor to set the base_uri.

Like so:

use GuzzleHttp\Client;

$client = new Client([
    // Base URI is used with relative requests
    'base_uri' => 'http://httpbin.org'
]);

How do we set the 'base_uri' in the constructor when we use dependency injection to instantiate a class?

While it would not be possible to use the http_client service it is possible to use the factory service (or create your own factory service if you choose not to rely on core methods).

The http_client_factory service provides a fromOptions method.

The Symfony2 documentation has a section on using parameters:

  Use the parameters section of a config file to set parameters:

parameters:
  mymodule.http_client.config:
    base_uri: 'http://httpbin.org'

services:
  mymodule.http_client:
    factory: '@http_client_factory:fromOptions'
    arguments: ['%mymodule.http_client.config%']
  mymodule.mymodule_call:
    class: Drupal\mymodule\MyModuleCall
    arguments: ['@mymodule.http_client']

Now the MyModuleClass will use Guzzle with Drupal's default configuration and custom configuration.

Note: it is also possible to provide your own factory service for Guzzle and to use that directly. This would be useful if you need to use your own overridden Guzzle\Http\Client class (I do this in a contrib module). This would probably be necessary to inject custom configuration such as handler stack (OAuth1).


How to add a view of product fields to a product display so that it changes when add-to-cart form is updated via ajax? In Drupal 7/Commerce, I would like to display a view of product fields attached to a product so that when the add-to-cart selection is updated and product fields are updated via ajax, the view is also updated (as with typical product fields).

In my case, I want to create an entity reference field ("included hardware") referencing other products attached to a product and use a view to display the result. This must happen at the product level, and not with the product's display node.

I have tried EVA. These fields don't appear on Product Display View Mode configuration.

I have attempted Display Suite (block field). When I select a display template for the product I see the fields on the product type display, but they don't show up on the Product Display node.

Can anyone point me to a solution for displaying a view within a product display that changes when a new product is selected?

The fields that change on a product display as different variations are selected on the Add to Cart form are updated via a series of Ajax commands returned by the form's refresh handler. It's about as complicated as the Forms API gets, to be honest, but it lets us do things like render the related fields and return them with instructions to the JavaScript client on where to place the HTML snippets to reflect the updates.

Because your View isn't associated with the product in the same way, you really need to trigger a refresh of its contents yourself. I'm not aware of any modules that will do that for you unless you can try / rule out Views Field. That may work with the product refresh system to support replacing the View alongside other fields.

That said, that's kind of overkill and would require a rearchitecture of your product displays. I would just hook into hook_commerce_cart_attributes_refresh_alter() yourself, re-render the View using the product ID stored in $form['product_id']['#value'], and return a command to drop it into place similar to how the other product fields are updated.


How to get the nid of current node I need a function to return the nid of the current node that the current user is watching.
Can you help me?

If you are insisting on a function then you are looking for arg function.

arg(0) will return 'node' and arg(1) will return node nid.

Provided you must be inside a node.

[Updated Answer]

if (arg(0) == 'node' && is_numeric(arg(1))) {
  $nid = arg(1);
  if ($nid) {
    $node = node_load($nid);
    /** do something **/
  }
}

Alternately

you can get nid from node object $node->nid


How to re position the breadcrumb on the product detail page? I am a bit confused, I was wondering how do you re position the breadcrumb to the top of the page. Please see image example below. When I see the default layout of Drupal Commerce Kickstart, the breadcrumb is located on the top of the product. I even replaced the css with the default css and there was no changes.

I figured this issue out, I had to look into the Block configuration and adjust the region.


Import CSS stylesheet only for specific content type? I want to use materializeCSS for my Blog content type. Problem is, when I import the stylesheet (I have set up my content type to process all HTML tags), it does not affect only the area of content of that content type, but it "leaks" to the rest of the theme, and changing overall theme look where CSS classes overlap (like default styling of H2 element in Materialize changes the whole look of the theme). Is there a way/module to have imported CSS stylesheet only affect the content it is imported to, but not the rest of the theme? I tried several modules that deal with context and CSS on sites, but neither of them works.

You can add your css only on Blog node pages so it does not impact site wide. Sample code

function MYTHEME_preprocess_node($vars) {
  if ($vars['#node']->type == 'blog') {
    drupal_add_css(drupal_get_path('module', 'mymodulename') . "/css/materializeCSS.css");
  }
}


Where does drush store the different module versions for a multisite installation? I wonder where the different module versions are kept on a multisite installation.

Before I (re)discovered drush, I had several more sites sharing the core code
 and sites/all/modules a symlink to a common modules dir.

On upgrading core I set that link in the new sites/all dir.

And then I started using drush. So when I do drush up in the sites/my1stsite dir and it updates the modules, how can the other my2ndsite still have the old modules? (and be able to drush up-date itself?)

If you are using a multisite installation with shared modules stored in sites/all/modules, then Drush pm-update will also put the new modules in this same shared directory.  This means that you must also run updatedb on all of the other sites that share the same module code, as all of the sites will need to be upgraded at the same time.

It is far more convenient to use a single-site installation, and give every site their own complete copy of Drupal core + contrib modules, as you will then be able to update each site independently.  Fortunately, splitting up a multisite install is as easy as cloning your Drupal files, and changing your web server virtual hosts configuration file to point at the new site's location.


Theming Views problem to print view fields I was trying to edit my view theme with php in the file
views-view-field--homepage-banner--block--field-site-image.tpl.php
and try to print view fields, but values come's empty. any ideas?

Code example:

<?php
$link=$fields['field_site_image_link']->content;
$src=$fields['field_site_image']->content;
$link2 = '/' . strip_tags($fields['field_site_image_link']->content);
print $src;
print $link2;
?>
<a href="<?php echo $fields['field_site_image_link']->content; ?>"><?php echo $fields['field_site_image']->content; ?>

1- clear cache
2- take the views-view-field.tpl.php source as a starting point for doing what you need also have a look at documentation at the top of the file


'Change email' form on custom page I would basically like to display the form/field that is used for changing the user's email address on a custom page with my own layout and things.

Ideally, I would like to make it so that if Javascript is enabled, the email address would appear as text with a 'Change' link next to it. The link would make a text box appear in place of text so that the user can change the address. Obviously, all this would happen without refreshing the page, and if Javascript is not enabled the email address should appear in the text box immediately like normal. If anybody can provide me with at least some, or all of the code that I need, that'd be so awesome.

Thanks in advance

If you've enabled the PHP Input Filter, you could add the following into your node/page. The javascipt won't execute if disabled, leaving only the input field :)

<?php
    drupal_add_js('misc/jquery.js', 'core', 'header');
?>

<?php
function userEmail_form() {
    global $user;

    $form['email'] = array(
        '#type' => 'textfield',
        '#default_value' => $user->mail
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit'
    );

    return $form;
}

function userEmail_form_validate(&$form, $form_state) {
    if (!valid_email_address($form_state['values']['email'])) form_set_error('email', 'Invalid Email Address');
}

function userEmail_form_submit(&$form, $form_state) {
    global $user;
    db_query('UPDATE {users} SET `mail` = "%s" WHERE `uid` = %d', $form_state['values']['email'], $user->uid);
    drupal_set_message('Email updated');
}

echo drupal_get_form('userEmail_form');
?>


Custom permission always denying access? In my module:

function mymodule_menu() {
    $items['reports'] = array(
    'page callback' => 'reports',
    'type' => MENU_CALLBACK,
    'access arguments' => array('access content', 'hr functionality')
    );
    return $items;
}

function mymodule_permission() {
  return array(
    'hr functionality' => array(
      'title' => t('HR functionality'),
      'description' => t('Do things only HR are allowed to do.'),
    )
  );
}

I set HR to have "HR functionality" permissions. I logged in as a user with HR role, and I get access denied to my reports page. I tried clearing cache, etc. If I remove the "hr functionality" access argument it lets me in.

Even if I log in as admin, I get access denied.

What am I doing wrong here?

EDIT: The method I ended up writing per accepted answer:

function multiple_permission_callback() {
    global $user;
    $permissions = func_get_args();

    if (empty($permissions))
        return false;

    foreach ($permissions as $permission) {
      if (!user_access($permission, $user)) {
        return false;
      }
    }
    return true;
}

The default function for the access callback is user_access(), which has the following signature:

function user_access($string, $account = NULL)

This is the function that will receive your access arguments.

It only takes one permission string at a time, so the second string you're passing in is being used as the $account object. This will cause problems in the user_access() function and is probably why it's returning FALSE all the time.

If you want to test two permissions you could provide your own access callback:

function mymodule_menu() {
  $items['reports'] = array(
    'title' => 'Reports',
    'page callback' => 'reports',
    'type' => MENU_CALLBACK,
    'access callback' => 'mymodule_reports_access'
  );
  return $items;
}

// Potentially accept an account object to make the function more re-usable
function mymodule_reports_access($account = NULL) {
  if (!$account) {
    global $user;
    $account = $user;
  }

  return user_access('access content', $account) && user_access('hr functionality', $account);
}


Mark only Event's start date on calendar? I am using calendar module, I created a view of calendar type that showing the event start date and end date. I just only want to mark the start date of event (Like change the background color.). How to do that?

Currently showing like this :

Try setting the end date the same as the start date


HTTPS Links behind AWS Load Balancer I really tried many Solutions to get my site work on Amazon AWS. There is only one last thing i can not solve. Some of my links are still "http://"-links and i dont know how to get them right.

My Setup:

Drupal 8.6.10 running on an EC2-Instance managed via Beanstalk
the Load-Balancer is managing the access and has two open ports (http/80 and https/443) directing to the ec2-instance via http (port 80)
the ssl-certificate is configured
my domain has the correct dns-config directing to xxx.eu-central-1.elasticbeanstalk.com
settings.php includes the following lines

     $settings['reverse_proxy'] = TRUE;
     $settings['reverse_proxy_addresses'] = array($_SERVER['PROXY_ADDRESS']);
     $settings['reverse_proxy_proto_header'] = 'https';
     conf['https'] = TRUE;
     $_SERVER['HTTPS']='on';

$_SERVER['PROXY_ADDRESS'] is assgned to 'xxx.eu-central-1.elasticbeanstalk.com' by beanstalk
.htaccess includes the following lines:

     RewriteCond %{HTTPS} off
     RewriteCond %{HTTP:X-Forwarded-Proto} !https
     RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

The affected places are:

in a twig: url('')
in a php-file: fileentities->url();

All other links are nicely rendered as 'https'-links. I would be really thankfull for any advice you could give me.

Best Regards,

FirstSanny

Try the folling setup:

In settings.php:

if (PHP_SAPI !== 'cli' && !empty($_SERVER['REVERSE_PROXY_ADDRESSES'])) {

  $settings['reverse_proxy'] = TRUE;
  $settings['reverse_proxy_addresses'] = array($_SERVER['REVERSE_PROXY_ADDRESSES']);

  $settings['reverse_proxy_header'] = 'X-Forwarded-For';
  $settings['reverse_proxy_proto_header'] = 'X_Forwarded-Proto';
  $settings['reverse_proxy_port_header'] = 'X-Forwarded-Port';

  // HTTPS behind reverse-proxy
  if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
    $_SERVER['HTTPS'] = 'on';
    // This is hardcoded because there is no header specifying the original port.
    $_SERVER['SERVER_PORT'] = 443;
  }
}

In your .htaccess:

RewriteCond %{HTTP:X-Forwarded-Proto} !https
#RewriteCond %{HTTP_HOST} !^(.*\.)*localhost(.*)$ [NC]
RewriteRule .* https://%{HTTP:Host}%{REQUEST_URI} [L,R=permanent]

(change $_SERVER['REVERSE_PROXY_ADDRESSES'] to $_SERVER['PROXY_ADDRESS'] for your setup)

This worked fine for me.


How to make a View of role? I need to make a page with the list of the roles (I have 10 roles in the site) and the possibilities of changing their name,I tried to use views but was not possible.
I want something like the drupal's role page, but just with the modify button.
Some ideas?

In views you cannot access to a list of roles, only to the user entity.

I suggest you to get this list of the roles by a drupal function

Try with user_roles()


Understanding ctools_modal_form_wrapper I am trying to get a handle on Ctools ajax modals and I am reading a lot of tutorials. In one of the tutorials (on https://gist.github.com/mrconnerton/1979037), I see the following code:

// Create a blank node object here. You can also set values for your custom fields here as well.
$node = (object) array(
'uid' => $user->uid,
'name' => (isset($user->name) ? $user->name : ''),
'type' => 'mytype',
'language' => LANGUAGE_NONE,
);

$form_state = array(
'title' => t('Add my content type'),
'ajax' => TRUE,
);

$form_state['build_info']['args'] = array($node);
// change this to your type node form
$output = ctools_modal_form_wrapper('mytype_node_form', $form_state);

I don't understand the function ctools_modal_wrapper. What exactly are the two parameters?

On the ctools API, it says they are $form_id, &$form_state but I'm not sure what

a) the form id is and where it comes from and

b) what a form state means? This might be a question on the forms API itself, and if so, please guide me to understand how this all works.

I found a better explanation here so I'm not going to explain much about the $form_state itself here.

To present a form, you have to use drupal_get_form() function that returns a render-able array of the form.
To build the form, you need to give a form ID (to get the form API arrays) and the state of the form. Form State ($form_state) becomes handy when you need to store arguments, previous step values, and many more (see the linked post above).

Ctools modal forms has many basic features.

Detecting whether JavaScript is available in the user's browser.
Falling back to normal HTML forms if JS is not enabled in the browser.
Keep form validation and submit functions working in the popup form.
Executing certain functions when the form is submitted.

Here is an example of a full Modal form menu router item. Note that I'm not using %ctools_js menu loaders to make this simple:

function quotes_editform_ajax($form, &$form_state, $quote){
  ctools_include('ajax');
  ctools_include('modal');
  $form_state = array(
    'ajax' => true,
    'title' => t('Edit quote'),
    'is_ajax_update' => TRUE,
    'quote' => $quote,
  );

  $output = ctools_modal_form_wrapper('quotes_editform', $form_state);

  if (!empty($form_state['executed'])) {

    // Add the responder javascript, required by ctools
    ctools_add_js('ajax-responder');

    // Create ajax command array, dismiss the modal window.
    $output = array();
    $output[] = ctools_modal_command_dismiss();
    $output[] = ctools_ajax_command_reload();
  }

  print ajax_render($output);
  exit();
}

Explanation:

  ctools_include('ajax');
  ctools_include('modal');

These functions will include specific ctools plugins for our use.

  $form_state = array(
    'ajax' => true,
    'title' => t('Edit quote'),
    'is_ajax_update' => TRUE,
    'quote' => $quote,
  );

Here we build the $form_state to pass to the form builder function (drupal_get_form(). ctools_modal_form_wrapper() calls drupal_get_form()).

$output = ctools_modal_form_wrapper('quotes_editform', $form_state);

Here, we build renderable array of the form. But the difference between drupal_get_form() is that it's actually in Ajax response form.
quotes_editform is a function that returns a form array.

function quotes_editform($form, &$form_state) {
  $form['name'] = array(
    '#title' => t('Name'),
    '#type' => 'textfield',
    '#default_value' => !empty($form_state['quote']->title)
       ? $form_state['quote']->title
       : '',
  );
  return $form;
}

In this $form_state array, ajax and title keys are ctools-specific. The title will be the popup's title and ajax is required to Ajax-ify the form.
Pay attention to the #default_value of the above snippet. If we are going to show an edit form, we need to know the existing values. So we send whatever we have to the form builder function.

Node forms are a little complex that there is a base form and child forms for each form.
This form ID is same as what you receive as the third parameter in hook_form_alter($form, $form_state, $form_id) hooks.

You are free to store whatever in this $form_state array.
$form_state array is passed to submit and validation functions so any of those functions can make use of those data.


Drupal Errors after Installation I'm new to drupal, and just trying to get it up and running smoothly.

I installed it manually on my Go Daddy account, but I'm getting these errors when I click on the customization links at the top of the screen:

I can still do things (add content, etc.) but since I'm new, I have no idea if there is anything not being shown to me because of these errors. I just did a fresh install and I'm still having the same problems. Any ideas?

From the screenshots I could see that you are using acquia marina theme, and these errors are related to that theme.

Please make sure that, you installed/configured the theme properly.

Related issue in acquia marina theme issue queue - http://drupal.org/node/1057002


Form element is not rendered I am trying to render the form element below in telisim module but it's not working, no output (see the screenshot).

The telisim.module file looks as follow:

//hook_menu

function telisim_menu() {
    $items['simcodes'] = array(
    'title' => 'SIM CODES',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('telisim_examples'),
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

/**
* Implements hook_element_info().
*/

function telisim_element_info() {
  return array(
    'telisim_notepad' => array(
      '#input' => TRUE,
      '#process' => array('porta_teslisim_notepad_process_callback'),
      '#theme_wrappers' => array('telisim_inline_form_element'),
    ),
  );
}

function porta_teslisim_notepad_process_callback($element, &$form_state, $complete_form) {

 $element['#tree'] = TRUE;

  // Normal FAPI field definitions, except that #value is defined.
  $element['areacode'] = array(
    '#type' => 'textfield',
    '#size' => 3,
    '#maxlength' => 3,
    '#value' => $element['#value']['areacode'],
    '#required' => TRUE,
    '#prefix' => '(',
    '#suffix' => ')',
  );
  $element['prefix'] = array(
    '#type' => 'textfield',
    '#size' => 3,
    '#maxlength' => 3,
    '#required' => TRUE,
    '#value' => $element['#value']['prefix'],
  );
  $element['extension'] = array(
    '#type' => 'textfield',
    '#size' => 4,
    '#maxlength' => 4,
    '#value' => $element['#value']['extension'],
  );

   return $element;

  }

  function _telisim_element_theme() {
  return array(
    'telisim_inline_form_element' => array(
      'render element' => 'element',
      'file' => 'telisim.module',
    ),
    'telisim_checkbox' => array(
      'render element' => 'element',
      'file' => 'telisim.module',
    ),
  );
}

function telisim_examples($form, &$form_state){

  $form['a_form_example_element_discrete'] = array(
    '#type' => 'telisim_notepad',
    '#title' => t('Discrete phone number'),
    '#default_value' => variable_get(
      'form_example_element_discrete',
      array(
        'areacode' => '999',
        'prefix' => '999',
        'extension' => '9999',
      )
    ),
    '#description' => t('A phone number : areacode (XXX), prefix (XXX) and extension (XXXX).'),
  );

   dsm($form);
    return $form;
}

I see two problems:

1) Your hook_theme() implementation is named incorrectly, meaning it will never be called. This:

_telisim_element_theme()

Should be this:

telisim_theme()

2) You haven't implemented theme_telisim_inline_form_element(), so there is no HTML for the form element to render.

You need to create this function, and output the relevant HTML for your form element inside the function.


Webform: send uploaded files as attachments Hi i'm using SMTP module to send uploaded inforamation into mail using webforms.so i'm getting below information to my mail fine but in place of upload Your Cv link i need attachment .

 The following application was received from the website.

==Contact details==
     Title: demo1
     First name: demo
     Surname / Family Name: demo
     Tel (Daytime): xxxxxxxxxx
     Email address: demo@gmail.com
     Currently living in: london
     Prepared to relocate: Yes

==Career choices==
     Job type: Permanent
     Current salary: 200
     Min. salary required: 200
     Were you referred by a friend?
     Upload your CV:http://xxxxx/system/files/webform/uploaded_cvs/demoresume_4.doc

This requirement cab be done using MIME module and Mail System but it's take more time to submit form.

Please help me i'm new to drupal.

Thanks in advance.

All sorted in the end with host entries on the server,I have updated
host entries for sending email and added domain name as host entry
then webform very fast to submited .it's works for me


Impossible to create content or edit image styles after Backup/Restore I'm having difficulties with a website that's running 7.14.
I did a backup with backup & migrate, installed a new instance of Drupal (7.40), installed the latest versions of all the modules used in the original website
I then restore the database (using backup & migrate also) but I can't create content or create/edit image styles. Whenever I try, I get this error message:

  The website encountered an unexpected error. Please try again later.

Any ideas on what causes this error? Or how to solve it?

How To Update Drupal Core

Follow these instructions:

Make a backup of your Drupal instance (database).
Download the latest release of your current Drupal version.
Extract the [tar ball or zip] Drupal package.
Set your site on maintenance mode
Delete all the files & folders inside your original Drupal instance
except for /sites and its sub-folders. This assumes that all of your
custom work - including themes - is in the recommended spot - the
/sites folder tree. If you have made custom changes elsewhere you
will need to either preserve them or plan to replace them later.
Copy all the folders and files except /sites from inside the
extracted Drupal package [tar ball or zip package] into your
original Drupal instance location.
Some updates do not include changes to setting.php and some do. See
There is a way - Comment below for more on this. If the update
release includes changes to settings.php you will need to replace
your old settings.php in .../sites/default/ with the new one, and
then edit the site-specific entries (eg database name, user, and
password) in the setting file.
If you have modified files such as .htaccess or robots.txt re-apply
those changes to the new files.
If you have a favicon.ico file that was deleted replace it too
Login to your site as administrator or as user no 1
Run update.php by navigating to
 http://...yourdrupalsitename/update.php and follow the process to
 update your Drupal instance
Disable maintenance mode


Base theme no longer recognized I recently inherited a Drupal 7 (7.39) site using an old version of Omega 4 (beta7) and a custom subtheme. All was well until this morning, when cron got stuck. It unstuck itself before I could start work, but now Drupal no longer recognizes the Omega base theme, so classes and other theme variables are not inserted properly, and the display is a mess.

To clarify,

I have cleared all caches from admin_menu and Devel many times (we are on shared hosting and there is no shell/Drush access).
There are no unusual errors or warnings on the status report or watchdog.
There have been no configuration changes within Drupal or on the server, which is running PHP 5.5.29 and Percona 5.6.28.
There are no Omega- or other theme-related modules installed except CiviCRM Theme, which I have disabled to no effect.
The files are all still present in /sites/all/themes/omega and /sites/all/themes/oursubtheme , and completely untouched as far as I can tell (no changes in file sizes or date stamps for as far back as we have snapshots).
As it's shared hosting, all files are owned by the account user with permissions set to 775. Again, this is not something that has changed.
the subthemes (both Ohm, the bundled subtheme, and our custom one) show up on the /admin/appearance screen just fine, but Omega itself does not.
I can get to the settings screens for the subthemes, e.g. /admin/appearance/settings/ohm, just fine. But browsing /admin/appearance/settings/omega returns an Access Denied error.
But Drupal must know that Omega is installed, because when I look at /admin/reports/updates or /admin/appearance/update, it shows up on the list of themes with updates available.
The pending updates for Omega are not security-related, so I don't think that it is a situation where it is being disabled or disallowed by a security mechanism

Naturally, the timing could not be worse for this to happen to the client, so I would appreciate any ideas as to what could cause Drupal to "lose" a theme like this, or how we might jog its memory.

I ran _system_rebuild_theme_data() but that didn't seem to improve the situation, so I checked the theme status in the system table; the base theme had been disabled. There lay the rub.

How or why the base theme became disabled remains a mystery. At the time this site was built, it was not required for a base theme to be enabled for the subtheme to access its functions; this changed, but I hadn't touched the theme in the month I've been working on this site, other than rebuilding the cache, so presumably it had been enabled before.

Since Omega was disabled, it was not supplying the right theme variables for our custom subtheme (though .tpl.php files did seem to get found), thus the broken display this morning.

Because Omega 4 is designed to be built and configured programmatically, perhaps, the base theme is hidden by default, and there was no way to enable it from the UI. I had to edit the .info file so that it was no longer hidden, at which point it showed up on /admin/appearance as usual.

If I had been able to use Drush on this server, this all would have been a non-issue. Many thanks to @Clive for his quick response and suggestions.


What's the "Best Practice" approach for disabling secure pages on local Dev? Wondering what the "best practice" approach would be for disabling secure pages on local dev. I'm running a site on Acquia Cloud and have access to the environment variable AH_SITE_ENVIRONMENT and I could easily do something like:

if (isset($_ENV['AH_SITE_ENVIRONMENT'])) {
  switch ($_ENV['AH_SITE_ENVIRONMENT']) {
    // case 'dev':
    //   // do something on dev
    //   break;

    // case 'test':
    //   // do something on staging
    //   break;

    case 'prod':
      // do something on prod
      break;
  }
}
else {
    $conf['securepages_enabled'] = 0;
}

Is that the best approach or is there a better, cleaner way? Also, are there negative implications for filling up settings.php with stuff like this?

It's a best practice to create a settings.local.php file which is included at the end of the default settings.php file. Then within that file you can place whatever logic you want per server as you've done, or make the content of settings.local.php be specific per server host you're deploying too (and keep settings.local.php basically outside of version control).

This is a good practice for Drupal 7 development -- so good in fact Drupal 8 ships with such code in settings.php by default, which you can uncomment to make use of:

/** In settings.php for a drupal 8 site */

/**
 * Load local development override configuration, if available.
 *
 * Use settings.local.php to override variables on secondary (staging,
 * development, etc) installations of this site. Typically used to disable
 * caching, JavaScript/CSS compression, re-routing of outgoing emails, and
 * other things that should not happen on development and testing sites.
 *
 * Keep this code block at the end of this file to take full effect.
 */
# if (file_exists(__DIR__ . '/settings.local.php')) {
#   include __DIR__ . '/settings.local.php';
# }


Contextual filter is not working I have views1 and view2, where in first view linked with view2 so I have given contextual filter in view both for entity reference field of view2.

Now my problem is when I pass nid of view1 at Preview with contextual filters: it not retaining any data the contextual filter is not working.

So you just need to place 1 contextual filter for nid and one relationship with referenced entity, and use that relationship in fields.
See the attached screenshot of a demo view.


switching language requires users to login again I have a multilingual site, that when people switch from one language to another, they are required to log in again.

but if they switch to the language they switched from the user is still logged.

so basically you could log into my site with 2 different accounts.

how is this possible? any ideas whats causing this?

Check out the issue here for i18n.

It seems that the Single Sign-On module should help you out.

  This module enables 'single sign on' between multiple web sites that
  share common user tables (see http://drupal.org/node/2622#advanced).

  Single Sign-On (SSO) means that if you are logged onto the master
  site, you will automatically be logged into any slave site that you
  visit.

  SSO needs at least two Drupal sites running in order to use it (even
  if you are using Domain Access module!). One is called Controller,
  second (third and others) are called Clients. See README for more
  information about setting this up.

I'd think that as the issue in the queue states the cookies are stored per language.  This should be amendable in settings.php.


View listing page/block relationship configuration I have a Part-Time Course content type that holds information about whatever course that needs to be added to the site.

I then have a Part-Time Course Offerings content type that has two fields.
Course Reference, which is an Entity Reference and links it to the Part-Time Course content type mentioned above and Course Offerings, which is an Entity Reference Revisions field type that gets fields from my Part-Time Offering paragraph type. That paragraph type holds various fields including Status and Season.

I have a block view that places the part-time course offerings on each part-time course content type page below the content based on contextual filters of Course Reference based on Content ID from URL.

What I'm now trying to do is create a Course Listing page that lists all the Part-Time Courses that I have but I want to filter it to only show courses that currently have Offerings available. So, if a course doesn't have an Offering available, I don't want it to show up on this listing page. I also want to be able to filter by status and season.

I have a feeling this has to do with Relationships but no matter what combination I've tried, I can't seem to get it to work.

Any suggestions?

The structure is basically like below:

Course - Part-Time (Content-Type)

    --> Course - Part-Time Offering (Content-Type)
        - field_course_reference
        - field_course_offerings

          --> Part-Time Offering (Paragraph)
              - various fields including Status & Season

EDIT: See below answer for an update.

Ok, so Content using field_course_reference (Relate each Content with a field_course_reference set to the content.) was used and required and then Content using field_course_offerings (Relate each Content with a field_course_offerings set to the paragraph.) was used and required using the first relationship.

This ended up allowing me to filter out and only display courses that had an available offering using Content: Course Reference (field_course_reference) with an operator set to Is NOT empty. I was also able to get the other two filters required to work.

However, I still have an issue where instead of just showing the course once, it displays it as many times as course offerings it has. So say that I have 5 different times the course is offered (The Part-Time Offering [Paragraph] allows for unlimited offering choices), it ends up listing the same course 5 times on my page.

Is there any way for the view to only display each course once, disregarding how many offerings are available for each course?

EDIT: Found the answer to the above. Once I turned on aggregation in the advanced settings, it only displayed each Course once.


How to only access a page through drupal_goto() function? I have a form setup so that when the user enters the correct serial #, they are redirected to the download page.

I don't want the person accessing the download page directly or sharing with anyone else through the URL, as this will bypass the serial validation.

How can this be done in Drupal?

Below is a solution that should work for users who are logged in (using Drupal 7, I assume).

Use the Content Access module to limit access to your download page to only those users who have a role like (say) "DownloadAllowed". Since you want to protect that download page, you'll need "some" access module.

And use the Rules module to implement a rule like so:

Step 1: Store your serial number (entered when your form is submitted) in a field which will be used in the next step. Even though you can use any "machine name" for that field, let's assume you call it "field_serialnr"

Step 2: Use a variation of the Rule included in my answer to "How to specify a Rules condition related to select list values?". Here is what you should tune in that rule:

Replace the Rules Event to something like "After saving new content (of some type that matches your form)".
Replace the "Value C" in the Rules Condition to the value of your serial nr.
For debugging reasons, start with a Drupal message to be shown (to ensure your rule works correct if the serial nr is ok, and to also verify it works as you want if the serial nr is wrong or missing). After the message shows up as you want it to show, replace the Rules Action with something like "Assign role to user". The role to assign is ... you probably guessed it ... "DownloadAllowed".

With that, those users who entered your serial nr correctly, will just-in-time get permission to access the download page. Those who didn't will be stopped by the Content Access module ... Which is exactly what you want.

PS: for anonymous users trying to access your download page, you could create another Rule to set a Drupal message indicating that they must be logged in before they can access that download page. For that, just use Rules Event "Drupal is initializing" and a Rules Condition to check if the URL they entered matches the one from your download page.


Get unsaved node from route parameter What I want: In hook_media_presave I want to set a field value according to the same field on the referring node.

By the referring node, I mean the node where the media entity is created through an entity reference field.

I don't know if this is possible at all, but if it is, then how?

My current approach is to get the node from the route like this inside the presave hook:

$node = \Drupal::routeMatch()->getParameter('node');

My problem: The node I get from the routeMatch doesn't contain the new changes. Is there a way to somehow get them using the routeMatch, or is there another way to get the node.

I thought maybe the media entity had some kind of getReferringEntity() method, but no.

Is this the correct approach, or am I wrong?

With the help from @Clive I found a solution:

/**
 * Implements hook_node_update().
 */
function MY_MODULE_node_update(\Drupal\node\NodeInterface $node) {
  foreach ($node->getFieldDefinitions() as $definition) {
    if (!in_array($definition->getType(), ['entity_reference', 'entity_reference_revisions'])) {
      continue;
    }
    if (!$definition->getSetting('target_type')) {
      continue;
    }
    if ($definition->getSetting('target_type') == 'media') {
      $media = $node->{$definition->getName()}->entity;
      if ($media) {
        $media->groups->target_id = $node->groups->target_id;
        $media->save();
      }
    }
    if ($definition->getSetting('target_type') == 'paragraph') {
      $paragraph = $node->{$definition->getName()}->entity;
      if ($paragraph) {
        MY_MODULE_update_media_items($paragraph, $node->groups);
      }
    }
  }
}

/**
 * Set groups on all media items referenced in a paragraph.
 *
 * @param $paragraph
 *   The paragraph.
 * @param $groups
 *   The groups to set.
 */
function MY_MODULE_update_media_items($paragraph, $groups) {
  foreach ($paragraph->getFieldDefinitions() as $definition) {
    if (!in_array($definition->getType(), ['entity_reference', 'entity_reference_revisions'])) {
      continue;
    }
    if (!$definition->getSetting('target_type')) {
      continue;
    }
    if ($definition->getSetting('target_type') == 'media') {
      $media = $paragraph->{$definition->getName()}->entity;
      if ($media) {
        $media->groups->target_id = $groups->target_id;
        $media->save();
      }
    }
    if ($definition->getSetting('target_type') == 'paragraph') {
      $paragraph = $paragraph->{$definition->getName()}->entity;
      if ($paragraph) {
        MY_MODULE_update_media_items($paragraph, $groups);
      }
    }
  }
}


EntityQuery group by clause Using the EntityQuery API I am trying to add a group by clause to the query, however, it doesn't seem that one exists.  The EntityQuery API does not have a groupBy() method.

Current Code:

$nodes = Drupal::entityQuery('node')
    ->condition('type', 'thing')
    ->condition('field_num_1', 'value', '=')
    ->condition('field_num_2', 'value', '=')
    ->range(0, 10)
    ->sort('title', 'ASC')
    ->execute();

Ideal Code:

$nodes = Drupal::entityQuery('node')
    ->condition('type', 'thing')
    ->condition('field_num_1', 'value', '=')
    ->condition('field_num_2', 'value', '=')
    ->groupBy('field_num_3')
    ->range(0, 10)
    ->sort('title', 'ASC')
    ->execute();

For aggregate queries, you need to use the separate method, from https://www.drupal.org/node/1918702:

$query = Drupal::entityQueryAggregate('node');

$result = $query
  ->groupBy('type')
  ->aggregate('nid', 'COUNT')
  ->execute();

groupBY() alone doesn't do anything. The normal entity query returns entity ID's. Always. It makes no sense to group by a field or anything else. Only in combination with aggregate.


Execute some steps before REST POST request I have created a custom content type and configured it to be created via REST POST method using REST client like POSTMAN or any frontend(like angularJS or react).

I want to execute few steps before creation of content type when a POST request is made. For example, make a SOAP call to SAP or make a query to external DB, and based on some condition like if data is received from SAP or external DB, then only content type should be created else it should throw some custom error.

I am new to Drupal and any guidance is welcome.

There is a hook called entity_presave.

This is always called when you persist a new or updated entity through Drupal API.
You can always check for the current request's method to see if it was a POST method (you can also check for the route itself).
So these presave changes (or can be save or post save) will be only taken place if that criteria is met.


How can I programmatically set the default export path? In Drupal 7, you can set the default export path for the features module by setting the variable 'features_default_export_path':

variable_set('features_default_export_path', 'sites/all/modules/custom/features');

What is the equivalent in Drupal 8? Can the export path be set in the features.settings configuration object?

It looks like configuration for the features module is managed in the features.settings configuration object. This settings can be viewed and change via drush.

Viewing the features configuration directory:

drush cget features.settings

Setting the features configuration directory:

drush cset features.settings export.folder "custom/features"


Node creation fields in blocks I am using Display Suite for node creation, but would like to extend this by also using blocks provided by theme to put several fields inside them too (sidebar left and right).

How to accomplish this ?

You may need to enable the Display Suite Extras module. (comes with display suite)

Go to manage display, scroll all the way down. Click on custom fields, add a block field.


Wave tool used to evaluate web content for accessibility issues giving Broken ARIA reference errors I am trying to fix Broken ARIA reference errors notified by Wave tool in chrome for my custom module web pages and Drupal 8 core login form. Sample error in login form is mentioned below for username field. How to fix these issues. For every user control I have this site wide.

Error at username text box:

*aria-describedby="edit-name--description", aria-required="true"

(An aria-labelledby or aria-describedby reference exists, but the target for the reference does not exist.)

I am not able to find aria-describedby attribute itself in the code for the controls. So, I am not sure how to fix them.

The attribute is only added if the element has a description. This is the code from the FormBuilder that does it:

// Add the aria-describedby attribute to associate the form control with its
// description.
if (!empty($element['#description'])) {
  $element['#attributes']['aria-describedby'] = $element['#id'] . '--description';
}

The idea being that when the input is rendered in form-element.html.twig, the description is rendered alongside it with a matching ID. For example this is how the core stable theme handles it:

{% if description_display in ['after', 'invisible'] and description.content %}
  <div{{ description.attributes.addClass(description_classes) }}>
    {{ description.content }}
  </div>
{% endif %}

So it seems likely there aren't that many possible sources for the problem. These are the only ones I could come up with:

You're using a core theme, or a derivative of one which still renders the description in form-element.html.twig, and something in the system is setting the description display to a value other than 'after' and 'invisible', causing it not to be rendered.
You're using a non-core theme, which overrides form-element.html.twig, and doesn't render the description.
Something in the system is changing either the value in the input's aria-describedby attribute, or the ID of the description element in the element template, causing them not to match.
Some combination of the above.

Hopefully that's enough to go on.


Create a view to display all nodes referencing this content I have 2 content types: Recipe and Product. In Recipe, I have an entity refence field to select a Product node used from the Recipe node.

In the Product node, I want to create a view to list all the recipes using that product. This means a block which lists all the recipes that reference this product.

How can I achieve this in Drupal 8?

I've found my mistake :

In Relationship, I have to select the entity reference field used in Recipe.
In contextual, I select NID as usual but I have to use the Relationship I've just created. Then I select Provide default value (ID from url).

I don't need to use this relationship in the Fields I add.


Using Drupal's database for Apache authentication I have static content outside of Drupal that I need to password protect using the users's existing credentials in Drupal. I found an apache module that lets you use MySQL for Apache authentication:

http://sourceforge.net/projects/modauthmysql/

Unfortunately, this doesn't support sha-2 (sha512) that Drupal 7 uses.

Does anyone know of any alternative ways to do this? I'd like to avoid wrapping all this content in PHP because it's generated (and regularly updated) by a tool, has any number of relative links and folders and such, and the only way I can think of handling that with PHP outside of modifying the files is to use mod_rewrite to route all the requests for html files through some sort of front controller that is a Drupal module (or a bootstrapped Drupal).

I did in the past use the export_user_db module, but it is similarly lacking in D7 support.

I am now using modauthmysql quite successfully with D6; I also have an auxiliary module that I can publish to do single-sign-on between Drupal and Apache-authenticated sections of the website.

You are correct that the lack of a Drupal-7-compatible password hash is a limitation, but I don't think this would be too hard to add. Contact me on d.o if you would like to collaborate.

http://drupal.org/user/438598

If you really only need to serve static content, serving it from Drupal per the other answer is easier and better.


How do I limit a particular search result from being indexed I have a content type called "product".  This "product" has an on/off checkbox to flag whether or not the product in question is able to be viewed on the web.  I would like to index only the products that have this "web_catalog" field turned on.  I have tried using preprocess_search_result to limit the returned result to no avail.  Any ideas or suggestions would be greatly appreciated, thank you.

I wanted to thank everyone for their input. In the end we created a small module that will alter the query instead of trying to alter the index of the site. To do this we utilized hook_query_alter() to add a subquery to the search. Below is the final version of our hook for reference should someone else have a similar issue.

function product_view_display_query_alter(QueryAlterableInterface &$query) {
  $is_search = FALSE;
  $tables =& $query->getTables();
  foreach($tables as $table) {
    if ($table['table'] == 'search_index') {
      $is_search = TRUE;
    }
  }
  if ($is_search) {
    $subquery = db_select('field_data_product_web_catalog','pwc')->fields('pwc',array('entity_id'))->condition('product_web_catalog_value',1);
    $query->condition('n.nid',$subquery,'IN');
  }
}


Try to theme a specific page using template.php and a sub theme I have a theme called 'progressive'. It has a sub theme called 'progressive_sub'.

I'm trying to exclude items from being displayed from a particular page in D7 (latest as of 12.2.15).

I have the following useful files:

/sites/all/themes/progressive/progressive_sub/template.php

This contains:

<?php

/**
 * Implements hook_preprocess_page().
 */
function progressive_sub_preprocess_page(&$variables) {
  $path = request_path();

  if ($path = 'node/131') {
    unset($variables['page']['header']);
    unset($variables['page']['sidebar']);
    unset($variables['page']['footer']);
    unset($variables['page']['bottom']);
    unset($variables['page']['top']);
    unset($variables['page']['content_top']);
    unset($variables['page']['sidebar']);
    unset($variables['page']['bottom']);
    unset($variables['page']['footer']);
    $variables['theme_hook_suggestions'][] = 'page';
  }
}

You can see that I'm trying to remove a heap of regions from this page (page.tpl.php) template, in this case when /node/131 is called.

I also have:

/sites/all/themes/progressive/progressive_sub/templates/page.tpl.php

which has all the usual including:

<?php print render($page['content']); ?>

My problem is that I cannot get this page.tpl.php to load when I'm viewing /node/131

Is there something that I'm doing wrong?

This

if ($path = 'node/131')

should surely be

if ($path == 'node/131')

Nevertheless this should not affect use of page.tpl.php.

Is your subtheme working at all, do templates get loaded from subtheme at all?

Your path is /sites/all/themes/progressive/progressive_sub. Does that mean the parent theme is at /sites/all/themes/progressive? If so, maybe try to give the subtheme a separate folder.


How to wrap module output with common html? I am using Drupal 7.14. I have a custom module with a number of different output pages. I define the paths in hook_menu and then in the callback functions I do some work and call echo theme('mytemplate', array(..args...)) at the end to output my content.

I also have a second custom module that does different work but outputs its content in a similar way.

I want to output some wrapping html that is common to the two module page outputs. At the moment the way I do this is to require a head and foot html file in each of the module template files.

This doesn't feel like a very Drupal approach so I'd appreciate some guidance.

Note: the wrapping html is specific to these two modules so I'd prefer not to pollute my main page.tpl.php file with it.

The only thing I see you could do is to have one commeon theme function and let one module depend on the other (you should specify this in the .info file). If you are going to have more modules with them same requirement you could have a central output module doing the theming.


Form Builder module not working in Drupal 7 Can someone confirm if Form Builder module is working on your end. I review the .module and seems like the paths are still using Drupal 6 format.

I was finally able to activate it. If you read well the requirements to install formbuilder you will find one of the options is to install Options Element. Please refer to this link http://drupal.org/project/form_builder and see the requirements.


Backtracing an SQL error shown in drupal set message with no specifying information I am using a feeds hook to email some information to workbench section users. I've been changing some of my code and suddently I'm getting a database error:

SQLSTATE[42000]: Syntax error or access violation:
1064 You have an error in your SQL syntax;
check the manual that corresponds to your MySQL
server version for the right syntax to use near '))' at line 2

This error doesn't show enough of the query to let me know which one it is, what line number or function it originates in, etc. I've tried putting a debug_backtrace() in the core definition of the drupal_set_message() function but I did not find my functions in it, just batch functions. I also tried putting backtraces in the DatabaseStatementBase classes' execute() method, but that caused the site to output a bunch of junk information on the screen.

How can I backtrace this error or otherwise track it down? The only thing that occurs to me put error messages around each query I'm running to see where the actual error falls. Is this the best way?

turn on error reporting for php. turn on mysql query log and inspect new queries -- add a simple parameter you can lookup like SELECT ..., 'IS-THIS-BROKEN-1' as debug_key to easily find your quer(ies) in the mysql log file. ... Views offer such a debug parameter for views sql queries too ... my point is there are better ways to tackle this that strictly form your PHP code and drupal_set_message.


How to change line-wrap length on Drupal 6 Blog? I'm currently managing a Drupal 6 website which has a blog displaying about 155 characters per line. I'd like to set that to under 85 if possible. Is this buried somewhere in the menus or it is something I'm going to have to find in some php file?

hi you can use the module maxlength to achieve it, it can be used to set the charecter limit to any of the cck field like body, summary, title etc.


Managed file input is removing input values of appended input fields by ajax I have a form with checkboxes that are calling ajax callback on checked. This ajax callback is appending another inputs:

$form['expertise']['op-cat-'.$op_cat['id']]['op-'.$op['id']]['checked'] = array(
    '#type' => 'checkbox',
    '#title' => $op['name'],
    '#default_value' => isset($usr['user_scope']['tid'][$op['id']]) ? 1 : 0,
    '#ajax' => array(
        'callback' => 'activit_full_profile_expertise_ajax',
        'wrapper' => 'expertise-div',
    )
);

Ajax callback:

function activit_full_profile_expertise_ajax($form, &$state) {

    $commands = array();
    $commands[] = ajax_command_html('#expertise-div', render($form['expertise']));
    $commands[] = array('command' => 'reinitializeTooltipster');
    return array('#type' => 'ajax', '#commands' => $commands);

}

In form is also an another managed file input:

$form['image'] = array(
    '#type' => 'managed_file',
    '#title' => t('Profilová fotografia <span>(nepovinné)</span>'),
    '#default_value' => isset($usr['picture']->fid) ? $usr['picture']->fid : 0,
    '#upload_validators' => array('file_validate_extensions' => array('gif png jpg jpeg')),
    '#upload_location' => 'public://user_images/'
);

Everything works fine if image field is not used after checkbox. If checkbox is used before image upload, it brings another input fields, but they are not present in $state['values'] in form validate & submit function (only original checkbox is present). They are not present in validate & submit function called by ajax of this image upload input, therefore they are not present in final validate & submit functions on form submit.

I have another custom ajax callbacks in form, but the appended input values are allways present. Is this a Drupal bug or am I missing something?

I'm not sure if this is a good solution, but now I'm taking values from $state['input'] instead of $state['values'].


Cannot change logo or colors of a scheme Hello I use Open Atrium based on Drupal. I can use the standard Radix 7.x theme, but even with that I cannot change the color scheme by saving it via Colorize. If I then use another theme I cannot even get the logo to display or any submenu to appear. I am not sure if it is a question of permissions. The site is installed on a VM as part of a webmin set up. I have seem very nice sites in both Drupal and OA so I am sure I should be able to customize my site, but it just does not work. The colorize shows the result on Radix, but as soon as I save it it forgets it. In my experience this might either mean that the path to the new colors (CSS?) is not valid, reachable or has the wrong permissions. DO you have any idea of what I can try? I need nothing fancy, but I'd like to customize the logo and colours and have all the Radix menus in another there, e.g. Bartik....Thanks in advance for any help you can give me. Please note I am not a programmer...if you advise me to change something in the code I can do it but you have to give me the full instructions. Thank you so much. regards
Enea

I'd check the folder/file permissions set on the "public files" folder for Drupal, especially the sub-folders (css, js, color) because if those aren't set right then the Color module can't write changes for custom CSS and logo uploads.


How to render alt and title texts of image file entities using a theme function Out of the box, image file entities have alt and title text fields attached, field_file_image_alt_text and field_file_image_title_text respectively, that provide the rendered image with an HTML alt and title text.

Today I feel like Mysite.com would be a great title for the images on my website, and I could easily programatically populate both text fields with Mysite.com upon upload of the image file. However, what if tommorrow I change my mind and instead of Mysite.com I want the alt and title text to be Welcome to Mysite.com? I would have to edit all file entities and modify both text fields for each.

Is there a way to render the alt and title text through a theming function so that I do not have to actually store the alt and title text within each file entity? I want to be able to modify the alt and title texts of all images by just modifying a single line of code.

The logic is pretty easy, you can just preprocess theme_image():

function MYTHEME_preprocess_image(&$vars) {
  $vars['attributes']['alt'] = 'alt';
  $vars['attributes']['title'] = 'title';
}

If you're using any of the standard image display formatters they'll eventually be passed through theme_image() so that should work for all fields.

I'd strongly advise you consider not doing this though. The point of an alt tag is to describe the image to parties who can't interpret it in its original form (visually impaired people, robots, text only browsers, search engines, etc)

By setting the alt for every image to the same string, you're making your site quite inaccessible to those groups of visitors. And since Google and others assign a reasonable weight to alt text, you won't be doing your SEO any favours either.