Modules can live in many places. If you use Apple's OSX it's alot like where Applications and Fonts can live in OSX ...

Modules can live at:

/profiles/PROFILENAME/modules/
/sites/default/modules/
/sites/all/modules/
/sites/SITENAME/modules/

core drupal modules are found in DRUPAL_INSTALL_DIRECTORY/modules.

Where a module lives deems how drupal sees it.

Modules in a profile directory can be seen by sites installed by that installation profile.
modules in /sites/default can only be seen by the default drupal site.
modules in /sites/all path can be seen by all drupal powered websites regardless how they were installed, or what subsite they are.
modules in /sites/SUBSITE/modules can only be seen by that subsite.

In general it is best practice to place the module folder where it is needed for its scope of use in your Drupal installation.

Additionally, it is a best-practice to place subfolders such as:

/sites/SUBSITE/modules/contrib
/sites/SUBSITE/modules/custom

to distinguish within a modules directory what is standard 3rd party contributed modules used for a site, and what is custom built drupal modules by your company in /custom.

Yes, there is documentation on this in your drupal installation folder at /sites/all/README.txt

Note: alot of this changes slightly with drupal 8

EDIT - references on /contrib and /custom directories.

Basically at some point in drupal development you want to organize your modules more and more, per site, per drupal installation. Many developers use these types of conventions. Drush Make (bundled into core Drush as of 5.x) allows specification of a subdirectory within /modules to place a module.

Organizing Drupal Modules
Drupal best practices
Drush Make subdir option


How to configure the CORS module for multiple domains?

Upon further investigation, this seems to be an issue with the CORS module, and has been patched, so hopefully fixed in future versions.

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


How to create custom page with user images in grid and with pagination, not using views

use hook_menu() to create a path to your page. Then use db_select() with the tableSort extender to supply pagination in the hook_menu page callback. Select the uid, username, user image(s) ? in your database query.

Then just loop over your resultset and output a div with your user images per cell. Simply float all the divs to the left so your output appears as a grid instead of a single long column of rows.


use \Drupal\Core\Url;
use Symfony\Component\HttpFoundation\RedirectResponse;

function MYMODULE_node_update(Drupal\node\NodeInterface $node) {
  $path = Url::fromUserInput('/node/'.$node->id())->toString();
  $response = new RedirectResponse($path);
  $response->send();
}

You have to use like above. You are just returning the redirect response. You need to send redirectresponse to given path.


You can use Visitors module.
It will give you the following reports:

View pages that have recently been visited.
View pages that have been hit frequently.
View pages count per month.
View pages count per day of month.
View pages count per day of week.
View pages count per hour.
View pages count per host.
View access log.
View user activity report (hits, nodes, comments).
View referer list.

and many more things.
Maybe for your requirement you need some customization.


You'll need to implement hook_permissions(). And you probably also need to read up on user_access(). The strategy is to create a permission set, grant it for the admin role, and then check for user_access before you render the buttons. This way the buttons will only show for users who have been granted the permissions.


How to do menu rebuild when having PHP Fatal error?

Make sure you're running drush in your web root and drush status is showing Drupal bootstrap: Successful.

Then try the following steps:

drush cc all to clear the caches or clear cache tables manually, e.g.:

echo "SHOW TABLES LIKE 'cache%'" | $(drush sql-connect) | tail -n +2 | xargs -L1 -I% echo "DELETE FROM %;" | $(drush sql-connect) -v

try rebuild menu again: drush eval 'menu_rebuild();'
try rebuild your Drupal registry via:

drush -y dl registry_rebuild
drush rr

consider disabling caches

In case your drush status doesn't show Drupal bootstrap as Successful, you either running it outside of your Drupal webroot or your db credentials are not configured properly in settings.php, or you've some missing/corrupted files which prevents from bootstrapping your Drupal core.

If you're using multisite, then don't forget to specify your profile by either running inside sites/X dir or make sure you're specifying the right --uri parameter, e.g.: drush -l http://myprofile status (see: drush topic core-global-options for proper syntax).

If you still having the issue, try: drush -vd status to troubleshoot the source of your problem.


CSS changes not taking effect in customized styles folder

Make the changes to the style.css file which is in Jackson theme folder. Not under mytheme

Use

#banner-wrap {
background: transparent url(../images/main-sprite.png) repeat-x scroll center -90px !important;
height: 133px !important;
overflow: hidden !important;
width: 100% !important;
}

Add this in to style.css file
Flush the cache once.


How to fill checkout form fields with values from a previous custom form?

I think you could get away with this by using hook_form_alter (checkout is still a form) and just setting #default_value on the required field. The previous form could save it in $_SESSION somewhere.


How to get number of results from MySQL query without getting all result data?

MySQL has no mechanism like that; you'll need to run two queries, the first a count query, and the second for the data if your condition on the first query result passes.

The PDO rowCount() method isn't used for SELECT queries, just DELETE, INSERT and UPDATE queries.

You'll need the countQuery() method to determine the count with a separate query, then simply run the original query  if the count query gives the right result


You need to select Method of handling multiple date fields in the same query as AND in the view exposed field setting.

Click on the * icon next to field in exposed filters section as shown below to complete above setting.


How to hide/show view based on field's value?

Okay, I think I got it now. Already tested.

Override the view's template (Tutorial)
Include global $user; somewhere in the first php tag.
Use an if statement: <?php if (strip_tags($view->render_field("YOUR_FIELD", $id)) == $user->name): ?> with YOUR_FIELD as the field's replacement pattern without brackets. (remember the <?php endif; ?>)

Sample view template (for unformated view display):

<?php

/**
 * @file
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
 */
global $user;
?>
<?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <?php if (strip_tags($view->render_field("title", $id)) == $user->name): ?>
    <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
       <?php print $row; ?>

  <?php endif; ?>
<?php endforeach; ?>


Option 1:

Inventory your 3rd party modules as well as your custom modules. Identify those modules that has a Drupal 7 version or if it's included in Drupal 7 core.
Update the Drupal 6 core.
Update the contrib modules and themes.
Disable contrib modules.
When everything is up-to-date and contrib modules are disabled, run update.php. This process will take time depending on how big is your database.
Enable your modules and start fixing some API that is not supported by Drupal 7. Use coder module to assist you.
Check, check, check.

Option 2:

Build from scratch.
Use migrate module to migrate you Drupal 6 db to Drupal 7.


How do I troubleshoot unit tests using xdebug?

I was unable to figure out why the debugger would not initially trigger for tests while it's triggered for other normal requests. Then I changed the xdebug.remote_autostart = 0 to xdebug.remote_autostart = 1 and it started working. I even changed it back to xdebug.remote_autostart = 0 and it kept working.

I also found out that one can also temporarily enable the phpstorm break at first line by xdebug settings:

I presume there is not one answer fit all but hope this helps others.


You can do this by Views:

Create view of block type (admin/structure/views)
Add fields want to display on term page.
Go to "Contextual filters" settings under "Advanced" tab.
Add the filters: "Content: Has taxonomy term ID (with depth)" and "Content: Has taxonomy term ID depth modifier". You can configure this on this filter: → When the filter value is NOT in the URL: → Provide default value → Type: Taxonomy Term ID from URL → under that, check the box "Load default filter from node page, that's good for related taxonomy blocks." → now check the boxes of the taxonomies you want involved here.
Now you need to add the second filter in order to exclude the current node from the list. Click [+] button of the contextual filters section.
Select Content: Nid.
Chosse the option "when argument is not present" to "Provide default argument".
Choose the "Default argument type" to "Content ID from URL".
Go to "MORE" , and check the "Exclude" box.
Move the filter "Content: Nid" to the top position.
Add a block to your view and embed the block on your node pages.
Save your view


How can I print the file size and other file info in a Views field template?

Well with some pointers from colleagues I have found out what I was doing wrong!

In the node you have all that info already there but views and their displays are more stripped back to keep them 'lean' so you have to be explicit that you need that info...

Step 1 - add a 'relationship' to the field

In the settings for the display of the view, I added a relationship to the file from the field under the 'advanced' settings using the 'add' button and it shows like this:

Step 2 - add fields for the stuff from the relationship

Under the fields for the view display I can now add fields for the relationship I just created. I added one for the URI and one for the filesize using the 'add' button and they show like this:

Step 3 - build the template

Now you can use those just like any regular field in the template. Here is the code I'm using to build a link with the file extension, filesize and a link to download the file:

<a href="{{ file_url(fields.uri.content|striptags|trim|convert_encoding('UTF-8', 'HTML-ENTITIES')) }}" target="_blank">Download
  (.{{ fields.field_e_resources.content|striptags|split('.')[1] }})({{ fields.filesize.content }})
</a>

Conclusion

I couldn't access the details for the uploaded file because they aren't included by default so by building the relationships as required you can add to the available fields and get the job done!


Validate new user email name matching a pattern on registration

Try something like this, add a validate to user_registration_form and then in validate check email with your pattern and if not match use form_set_error. something like below

function registration_check_form_user_register_alter(&$form, &$form_state)
{
    $form['#validate'][] = 'registration_check_user_register_validate';
}
function registration_check_user_register_validate($form, &$form_state)
{
        $email=$form_state['values']['email']['und'][0];
        if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)\.edu/i",$email))
                {
                form_set_error('mail', t('Email NOT VALID,TRY EMAIL WITH .EDU'));
            }
}


Showing group managers a list of pending users

First, in the View Commons Contributors - Group (User), I cloned the Display group homepage

In this new content pane, I then added a footer with a link below. This will take the user to the Administer Group/People page.

Manage memberships

Caveat: On Panels (via /admin/structure/types/manage/group/panelizer/page_manager/content), I set view permission to: Logged in User has "Approve or Deny permission for this group"


Right way to create Yes/No boolean fields

As follows:

Field type: List (integer) & Widget: Check boxes/radio buttons
Values: 1|Yes
Number of values: unlimited

See drupal.org


I got what I needed after reading a couple of views docs.

 $view = views_get_current_view();
 $view->exposed_input['filter_name']


Create a drupal 6 views slideshow from a single content type that has both, image and video fields

The only way I've been able to somewhat achieve this is by creating individual nodes for the video and image content.  I then use views to filter for both types. Clumsy for the content editor, but I guess it works.


Assigning content from one user to another user automatically after a payment

Use the Node access user reference module for this purpose. About this module (quote from its project page):

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

And use the Entity reference module to implement your "assignments".
To actually "use" (configure) these settings, refer to the module's README.txt, which includes these instructions:

Create a field to reference users in a content type using the Field UI.  The field's configuration page will contain the settings for Node access user reference. For detailed instructions on using the Field UI see:
https://www.drupal.org/documentation/modules/field-ui

Possibly you also might want to use the Field Permissions module.


How do I implement a block suggesting other relevant content?

Try to use Similar Entries module for this.

  Similar Entries provides lists of links to site content related to the current node being viewed. Links can be displayed in standard blocks or as part of custom views.


sort comments descending programmatically

<?php
$query = db_select('comment') ->fields('comment', array('cid')) ->condition('nid', arg(1), '=');
$query->orderBy('created', 'DESC');
$result = $query->execute();
$cids = $result->fetchCol();
$comments=comment_load_multiple($cids);
foreach($comments as $comment)  {
  //do some stuff with the comment
}
?>


How to change the word "blog" for "journal"

There is String Overrides module.

Provides a quick and easy way to replace any text on the site.

Features
Easily replace anything that's passed through t()
Locale support, allowing you to override strings in any language
Ability to import/export *.po files, for easy migration from the Locale module
Note that this is not a replacement to Locale as having thousands of overrides can cause more pain then benefit. Use this only if you need a few easy text changes.


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.


Is there a Drupal.org issue queues module? Which module does Drupal.org use?

The Project project, and Project issue tracker project, together make up most of the functionality that you are looking for. Since you ask about D7, it's worth noting that the modules are currently under upgrade to D7.

Project:

  Projects are generally assumed to represent software that has source code, releases, and so on.

Project issue tracker:

  It allows users to submit issues (bug reports, feature requests, tasks, etc) and enables teams to track their progress.


The problem was that by default the Bulk Operations actions are set to enqueue rather than be fired directly.


I solved the problem with the module Forum Access.

  This module changes your forum administration page to allow you to set
  forums private. You can control what user roles can view, edit,
  delete, and post to each forum. You can also give each forum a list of
  users who have administrative access on that forum (AKA moderators).


Moving Host - concern about PHP memory limit

A 128M memory limit is often not "more than average" for a Drupal project.
Also, just because you've specified 128M as the memory limit, that doesn't mean your webhost is giving you that much (or even half as much).

Let me explain.
I'll use Commerce Kickstart v2 with the demo store installed as an example (matching a medium-sized Commerce store).
It has 10 content types, 6 product types.
146 modules installed, out of that 23 provided by Drupal core, and 123 contrib.

Installing Commerce Kickstart requires 77M of RAM (xhprof peak memory usage).
A Kickstart page (frontpage, the view that lists products in a category, faceted search page) takes about 17M (as reported by devel).
This number can spike easily on admin pages that show many items, or thanks to a misbehaving module.

Our minimum memory limit requirement for Kickstart is 128M, based on our personal experience developing Drupal sites (it's easy to get "memory limit exceeded" with less than that).
Also, if the server doesn't have enough memory when generating the request, it won't give you how much you asked for. I saw it with my own eyes (MacBook Pro, Chrome with a million tabs, only a bit of RAM left. PHP fails to allocate 77M of ram despite the memory limit being 128M).
I also saw this complaint from people with shared hosting (I strongly believe that running anything more than a blog on shared hosting is pure masochism without excuse in the age of cheap VPS).

Why does Drupal need so much memory? Among other things, because it has a cache problem (which of course saves your database)
Drupal currently likes to cache ALL views in one place, ALL fields in one place, etc. So once you get a site with many content types, fields, views, the caches become huge, and they are all loaded into your memory with each request.
Thankfully, this is being fixed as we speak, thanks to people like catch (See this article for details).

The fix to Views got committed a few days ago and is now available in 7.x-3.x-dev. Quoting #29 from that thread, where the memory usage for Views dropped from 34M to 17M:

  So, for normal use, there's a 15% improvement in execution time, and 49% improvement in memory usage.

There is also a RTBC fix for fields in Drupal core that should make it into the next Drupal 7 release. Benchmarks showed savings between 1M and 50M (depending on your number of fields).

There's an in-progress fix for the system (module & theme) list in Drupal core that should shave a megabyte or two as well.

So, install Devel, go to admin/config/development/devel, enable "Display memory usage", and find out how much your pages need.
Also follow the fixes I mentioned, test them and see how much they help you (they give me a few megabytes of savings on the Kickstart install, which still counts).

And of course, find a decent hosting (I don't know if GreenGeeks is decent, don't have much experience in that field), set a decent memory limit, and don't worry too much :)


How to display all media that references this taxonomy term and its immediate children?

I finally worked this out, using Views (which is a way of querying the database and presenting lists of data). My design places the View as a block on my taxonomy term pages, so I refer to a block display in this method rather than a page display:

BASIC VIEW TO SHOW ALL MEDIA

Structure > Views > Add view

Enter View name and Description
Show Media of type All sorted by Unsorted
Select "Create a block"
Unformatted list of Fields
Adjust "Items per block" as appropriate (e.g. 25)
Save and edit

Scroll down and check all your Media names are listed in the Preview section, to ensure the basic View is working correctly.
FIELDS > Add > Rendered entity (Category: Media).

Here you could alternatively add fields such as Image, Video URL and File rather than the general Rendered entity.
Choose the appropriate View mode > Apply. In my case I had set up a "Preview" display mode in /admin/structure/media/manage/MyMediaType/display, with a thumbnail image format and most fields disabled.

Scroll down to check your media is listed below the names.
Click "Media: Name" > Remove, if you don't want it. It's often unnecessary for media.
Save

CONTEXTUAL FILTER TO SHOW ONLY THIS TERM'S MEDIA

Here we need to make sure that in this block we will only display media that refers to the term whose page the block will be seen on. In this case, that reference is made in a field on my media labelled "Primary Taxon".

ADVANCED > CONTEXTUAL FILTERS > Add
Select "Primary Taxon (field_primary_taxon)" (Category: Media)(or whatever your field is called) > Add and configure contextual filters
WHEN THE FILTER VALUE IS NOT AVAILABLE > Provide default value > Type: Taxonomy term ID from URL > Select (only) "Load default filter from term page" > Apply > Save. We have to supply the value this way because, unlike a page, a block does not have a URL to find the value in.
For testing, find the taxonomy term ID number ("TID") for some of the terms in your vocabulary. You can find these in the URL of the taxonomy term's page. For example my Roses page has URL .../taxonomy/term/86 so the TID is 86. If you have a module such as Pathauto providing URL aliases, then you can find the TIDs by visiting .../admin/structure/taxonomy/manage/MyVocabulary/overview, hovering over "Edit" and looking at the URL at the bottom left of your browser.
In the Preview section, test the View is filtering correctly by entering your different TIDs in the "Preview with contextual filters" box and click "Update preview". For example if I enter 86, I see only media for which I had entered "Roses" in the "Primary Taxon" field.

RELATIONSHIP & CONTEXTUAL FILTER TO SHOW CHILD MEDIA

To list media that refers to children of the term whose page that the block will be seen on, we need to find media whose parent refers to that term. This "reverse thinking" helps with understanding contextual filters; think of the relationship from the thing you're listing, not from the thing you're displaying the list on. My media has no "Parent Taxon" field; that would have been redundant because terms' parents are inherently defined in the hierarchical vocabulary they belong to. This means we can't just add "Parent Taxon" as another simple contextual filter. So we need to extend the range of database tables that Views can query by adding a relationship:

ADVANCED > RELATIONSHIP > Add > Select "Taxonomy term referenced from field_primary_taxon" (Category: Media) > Add and configure relationships > Do not select "Require this relationship" > Apply. This looks at the taxonomy term specified in the media's "Primary Taxon" field and "pulls in" that term's taxonomy information so that Views can query it with our next contextual filter:
ADVANCED > CONTEXTUAL FILTERS > Add. You will see that the list of available filters to choose from is now longer than when we chose the first contextual filter, because of the new relationship.
Select "Parent term" (Category: Taxonomy term) > Add and configure contextual filters
Same as before... WHEN THE FILTER VALUE IS NOT AVAILABLE > Provide default value > Type: Taxonomy term ID from URL > Select (only) "Load default filter from term page" > Apply.
OTHER > Query settings > Select "Contextual filters OR" > Apply > Save. This means results will be listed that pass either the 1st contextual filter OR this 2nd one. Without this, it will filter for media matching both one AND the other, and no results will be displayed.
Note that after this 2nd contextual filter has been added, the view can no longer be previewed below (I don't know why). So we need to place the block on a page...

PLACE THE BLOCK ON THE PAGE

Go to Structure > Block layout > Find appropriate theme(s) (in horizontal sub-menu at the top) and region > Place block > Find your new block > Place block > De-select "Display title" if you want...

We only want our block to show on taxonomy term pages, however in the "Visibility" section there is unfortunately no "Taxonomy term page" listed under "Content type" (I don't know why). So click "Pages" and type /taxonomy/term/* in the box > Save block > Save blocks (at the bottom). This restriction will be applied before URL aliasing, so don't worry if you have a Pathauto alias set for your taxonomy pages.
Visit an appropriate taxonomy term page to check the View works. You may need to refresh the page and/or clear all caches (at .../admin/config/development/performance), especially if you haven't disabled caching.

DISPLAY THIS TERM'S MEDIA BEFORE CHILDREN'S MEDIA

The default order of display of the media is by the "Authored on" time. To display this term's media before child term's media:

Install the Views Argument Order Sort module (there's currently only a development version).
SORT CRITERIA > Add > Select "Multi-item Argument Order" > Add and configure sort criteria > Apply > Save. This put this taxon's media before child taxa's media, whether I selected "Sort ascending" or "Sort descending".
Despite exposing this sort criterion to users to try and allow them to change the sort order, I was unable to get that working. If you know how, please comment.

FURTHER GROUP MEDIA BY TAXON

You can group the media by the term they refer to, with headings:

FIELDS > Add > Primary Taxon > Add and configure fields > Select "Exclude from display" (not necessary but you can still group by this field even if it is hidden like this) > De-select "Link label to the referenced entity" (also not essential) > Apply
FORMAT > Format > Settings > Grouping field Nr.1 > Media: Primary Taxon > Apply > Save > Test the view.

VALIDATION BUG?

In theory, validating the output of the 2 contextual filters as follows is a good idea:

Click the contextual filter > WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED > Select "Specify validation criteria" > Validator: "Media" > Select only the Media types you wish to show (or none for all of them) > Select "Validate user has access to the Media" > Apply > Save.
However, this validation prevents the view from displaying anything. Please comment if you know why, or if you think this is a bug.

IMPROVEMENT SUGGESTIONS

HEADER > Add > Result summary. This will give you a summary of results at the top of the block, as is standard on a page display.
Select ADVANCED > Other > "Use AJAX" to reduce page refreshes.
In some cases a Table view is useful, rather than unformatted list etc., because you can sort the media by field columns if you add extra fields.
You can add a "Media type" regular filter (not contextual) and expose it to visitors to allow them to show only certain type(s) of media (e.g. Images or videos or both). The Better Exposed Filters module allows the choices to be shown as checkboxes rather than as a drop-down menu, although I have a bug with it (link to follow) at the moment (version 8.x-3.0-alpha3 in Views 8.4.4).
The Views Infinite Scroll module can make for a nice improvement over standard paging if you have a lot of media.

Here is what my View looks like (with the optional Infinite Scroll and AJAX selected):

I have little Drupal experience, so feel free to suggest refinements to this method.


To get the bundles for an entity type, use the entity_type.bundle.info service, like this:

\Drupal::service('entity_type.bundle.info')->getBundleInfo('ENTITY_TYPE')

or use dependency injection to inject the service.

See the documentation for getBundleInfo for more information.


What is the difference between Microdata or Schema.org (or can I use both)?

They are different things:

Microdata is a syntax.
Schema.org is a vocabulary.

If you want to use the Schema.org vocabulary, you can use the syntax Microdata, or RDFa (Lite), or JSON-LD (or any other RDF serialization, but the three mentioned syntaxes are supported by the big search engines that sponsor Schema.org).

The schemaorg module integrates the Schema.org vocabulary into Drupal 7 by using RDFa 1.0, which is the syntax used by Drupal 7 for other vocabularies, too.

The microdata integrates the Schema.org vocabulary by using Microdata (without this module, Drupal 7 does not output any Microdata).

If you can’t decide between these two modules: Go with schemaorg, because Drupal 7 already uses RDFa, RDFa is more powerful than Microdata, and parts of this module were ported into the Drupal 8 core.


Media Youtube/Vimeo is being saved (or rendered) incorrectly as application/octet-stream

I was having the same problem. The YouTube video was added correctly using the Media browser, the thumbnail was generated and it was even saved in the database correctly prior to saving the node.

After the node was saved, the entry in the database changed to application/octet-stream with a filename of the description twice, as well as a URI of public://

Something was altering the file details when the node was being saved. There weren't many options I could think of, and a quick review of the field settings revealed filefield_paths was enabled for the field, which was altering the filename.

I disabled fielfield_paths for the field and saved the node again, which resulted in the video displaying properly.

If you have filefield_paths installed, try disabling it for the YouTube field only.

Update: This is resolved in the latest version of filefield_paths. See: https://www.drupal.org/node/2576547


Is there an easy way to serve low quality images for low-bandwidth users?

I don't know that there's a way to determine benchmark throughput performance on the fly without wasting a lot of the users time running a test, on every login. You could do something like:

add a field to the user profile that the user can change which dictates the speed they use
use a custom style or set of styles for all images
create a custom module to override hook_image_styles_alter() to adjust (if necessary, based on the user field value) the style to suit

  This hook allows modules to modify, add, or remove image styles. This
  may be useful to modify default styles provided by other modules or
  enforce that a specific effect is always enabled on a style. Note that
  modifications to these styles may negatively affect the user
  experience, such as if an effect is added to a style through this
  hook, the user may attempt to remove the effect but it will be
  immediately be re-added.

This way the user can determine which speed they are using, and the system should adjust the images on all subsequent logins to fit their choice


Custom action to create a new entity based on a fields of an existing entity

If I have to do that, I would take these steps to achieve what you want here :

Make a custom module for it.
Add a path by help of hook_menu.
Make a custom function for menu callback & mention the same in there.
Inside function, get current node ID (entityform submission, where admin is there) by something like if (arg(0) == 'node' && is_numeric(arg(1))) $nodeid = arg(1);
Then write code to load a entity by ID by help of entity_load & take all the values in custom vars as per requirement for new node(profile).
Save the node of type profile by help of node_save.
Insert a link(CREATE PROFILE) mapped with created path(by above hook_menu) to the node view of entityform submission by help of hook_node_views.

Now when ever your inserted link will be clicked, a profile will be created.

You can restrict the access of created path by implementing hook_permission & give access to admin only.

You are free to do some other stuff as well, like if profile node exist for entityform submission them make link disappear as well. It all depends upon your need & plan :)


How to make metatags output proper images urls

if you get the file name with [node:field-promoted-image:file:url] just put the right path bevore the token. yoursite.de/thepathtoimage[node:field-promoted-image:file:url]or maybe you can put the base path token before it


Why does hook_menu add my menu items multiple times?

This was a problem with link_path as hinted at by @xurshid29 and @ARUN.

link_path "works" in that it inserts a link with the given path into the menu, but it also has the odd side effect of inserting multiple links into the menu - one for each cache clear - despite each link having the same key in $items. It's also undocumented, so I have no idea where I picked it up from.

Removing the link_path argument and replacing it with "page callback" fixes the problem of multiple links being inserted.

"Have a chat" was fixed to explicitly callback the "add discussion form":

$items['have_a_chat'] = array(
    'title' => 'Have a chat',
    'page callback' => 'node_add',
    'page arguments' => array('discussion'),
    'type' => MENU_NORMAL_ITEM,
    'access arguments' => array('create discussion content'),
    'menu_name' => 'user-menu'
);

And "external" was fixed to page callback a function that then calls drupal_goto.


internal server error after deleting thumbnails image-style

After some googling I saw a similar error on Drupal.org

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

Check the last few comments. It might be related to Media Entity


This has been discussed at Use email to validate post, not unlike craigslist.

A module that is still in alpha is also available:

https://drupal.org/project/anonymous_publishing

The module is not widely used, thus not extensively tested. It might be safer to write your own rules as discussed in the first link.


FROM_UNIXTIME(o.created,'%d-%m-%Y') in where clause gives error

You just need to escape the percent sign with another, i.e.,

FROM_UNIXTIME(o.created,'%%d-%%m-%%Y')

Also make sure you use parameter replacement rather than injecting strings directly into the query; you're not protected from SQL injection at the moment.

That would be something like

$sql = "SELECT * FROM {table} WHERE FROM_UNIXTIME(o.created,'%%d-%%m-%%Y') < '%s'";
$result = db_query($sql, arg(3));


Writing unit tests for a method that calls static methods from another class

You can't mock static calls directly.

A relatively easy way to fix this is what core uses in quite some places to mock functions that haven't been converted to objects/services yet. You create a method in your own class that does nothing but call the static method.

Then for your test, you can either mock your own object and only mock that method or create a test subclass that overrides that method and return something else.


How to use $variables from theme setting in main menu

You can't use name suggestions with double underscore in preprocess function names.

You have to replace this with an if statement in code:

function saka_theme_preprocess_menu(&$variables) {
  if ($variables['menu_name'] == 'main') {
    $variables['social_url_fb'] = theme_get_setting('social_url_fb','saka_theme');
  }
}


How to dynamically set the maximum cardinality for a multi value field?

My cardinality was based on the value of another field in a related entity, so I figured out that I could set the number of values to Unlimited in the field settings, then, in hook_form_alter, reattach the field to the form with a new cardinality:

$field = field_info_field('field_my_field');
$field['cardinality'] = $my_new_cardinality;
$instance = field_info_instance('entity_type', 'field_my_field', 'bundle');

// Depending on the form, the entity may be found in $form['#entity'],
// in $form_state, or elsewhere.
// $langcode is usually LANGUAGE_NONE, but may change in multilingual sites.
$items = isset($entity->field_my_field[$langcode]) ? $entity->field_my_field[$langcode] : array();
$new_field = field_multiple_value_form($field, $instance, $langcode, $items, $form, $form_state);

// This is not needed. It tricks theme_field_multiple_value_form into
// not adding the value reordering widget.
$new_field['#cardinality'] = 0;
foreach (element_children($new_field) as $delta) {
  $new_field[$delta]['_weight']['#access'] = FALSE;
}

$form['field_my_field'][$langcode] = $new_field;


Is it possible to automatically create a .install file for a module?

If it's just the field and field instances that you want converted ready for an install file (i.e. if Features is too overkill for you or you don't want the extra dependency), then Field Inspector will give you all the code you need for creating your fields in code.

  Field inspector provides an administrative user interface for the
  Field Info API. This allows users to select what information,
  formatting, and fields they would like to see, and provides output in
  a manner that can be copied into a module, or install profile into a
  hook_install, or hook_update_N function.


Form API-built form only emails Array, not the form results

This line is probably the problem:

$params['message'][] .= ...

If $params['message'] is a string then you want to be concatenating directly to that string like this:

$params['message'] .= ...

When you put empty square brackets [] on the end of a variable PHP treats that variable as an array and essentially pushes whatever's after the = sign on to the array.

The way you're doing it (with a string concatenation of .=) I'm not actually sure what the logic flow would be but it wouldn't be pretty...I'm surprised you don't get a fatal error for this :)


Here is the way to render multiple views on a single template file.

you need to make use of views_embed_view
Using this function, you can embed Views and even dynamically pass them filter arguments. - See more at: http://www.webomelette.com/drupal-embed-view-template-tpl

you can use this function multiple time to get your both views rendered and then do your operations on variables available from them [you need to figure out this at-least], here is the help


You need to return a Response object or a render array from a controller.


How do you display fields created via the File Entity settings configuration?

I was also looking for that functionality, and found this module does exactly that: File Entity Inline

  This module aims to provide the ability to edit File entities inline,
  as part of another form (such as nodes). This should enable the
  ability for reusable and site-wide editing of file properties, such as
  description, alt text, captions, bylines, etc.


You can add an integer field to your node, and set the default value to 0.

Then in a small module, use hook_node_presave to increment its value every time the node is saved (or if you detect a field change). Quick, easy and efficient way.

You can do the same with a computed field, by incremeting the value of the field by 1 when you submit the form,  but storing code in the database isn't advised.


Accessing html.tpl.php variables from outside

Direct answer to your question - you can populate the variables you need by emulating the same functions that the processing function for html.tpl.php uses to render the page:

http://api.drupal.org/api/drupal/includes%21theme.inc/function/template_process_html/7

function template_process_html(&$variables) {
  // Render page_top and page_bottom into top level variables.
  $variables['page_top'] = drupal_render($variables['page']['page_top']);
  $variables['page_bottom'] = drupal_render($variables['page']['page_bottom']);
  // Place the rendered HTML for the page body into a top level variable.
  $variables['page']              = $variables['page']['#children'];
  $variables['page_bottom'] .= drupal_get_js('footer');

  $variables['head']    = drupal_get_html_head();
  $variables['css']     = drupal_add_css();
  $variables['styles']  = drupal_get_css();
  $variables['scripts'] = drupal_get_js();
}

So to access the styles variable, you would just need to call the same function the template engine is using:

$mystyles = drupal_get_css();

However - just to check, these values are already on your page because the html.tpl file is a wrapper for page.tpl.php. Sure you want to print it twice?


Maintenance page being rendered as an entire page load after the main page load

I'm still waiting to see an answer to the question of what causes maintenance mode to be displaying messages. So I don't know specifically whether the recoverable fatal error (this issue) being thrown by the buggy 7.x-2.4 version of XML Sitemap module was what caused the avoidance of a general WSOD/ crash and yet a display of an odd maintenance mode message.

I had not noticed they'd released 7.x-2.5 and so I've updated that which has stopped the behaviour altogether. Happy days :)


Url Path Alias is not working with the "raw value from URL contextual filter"

How have your configured your contextual filter? I have the following configuration and it's working fine for me:

Contextual filters: Has taxonomy term ID
You also need to specify validation criteria for this filter, my setting is:

a) Specify validation criteria = Taxonomy Term
b) Select the correct vocabulary.
c) Set Filter value type to Term name converted to term ID
Create a relationshiop of Content: Taxonomy terms on node

a) Select the correct vocabulary.
b) Set Require this relationship to true

You may also wan't to use Has taxonomy term ID width depth if you have nested terms in your vocabulary.


When you create a view for users or the profile nodes, you should be able to add a relation to the other one. Not shure thou whether this works in both directions.


How can I exclude certain routes from maintenance mode?

You need to override the service directly.
mymodule.services.yml
services:
  maintenance_mode: # same ID as declared in core.services.yml
    class: Drupal\mymodule\Services\CustomMaintenanceMode # point to your class
    arguments: ['@state']

mymodule/src/Services/CustomMaintenaceMode.php
<?php

namespace Drupal\mymodule\Services;

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Site\MaintenanceMode;

class CustomMaintenanceMode extends MaintenanceMode {

  /**
   * {@inheritdoc}
   */
  public function exempt(AccountInterface $account) {
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node instanceof \Drupal\node\NodeInterface && $node->getType() == 'article') {
      return TRUE;
    }
    else {
      return $account->hasPermission('access site in maintenance mode');
    }
  }

}


Your theme is probably not presenting the new action links in D7. In a default install of D7 and forum (using Bartik theme) I can see them. See http://definitivedrupal.org/suggestions/action-links for an explanation.


db_select condition with subquery causes PDOexception

Thanks to @Clive's comment, I checked the documentation about the subqueries on https://drupal.org/node/310086 and I noticed the note about:

  Note: Currently it is only possible to use subselect conditions with the IN operator because with the other operators the sub-query is not wrapped in parentheses and so results in a syntax error. See #1267508: Subselects don't work in DBTNG conditions, except when used as value for IN.

I've changed my code to use IN instead of > and it worked like a charm. Here's the working code for future reference if someone falls into the same situation:

$subquery = db_select('user_revision', 'ur')
  ->fields('ur', array('vid'))
  ->where('ur.timestamp > 1379494886')
  ->orderBy('ur.timestamp', 'ASC');

$query = db_select('users', 'u')
  ->fields('u', array('uid', 'vid'))
  ->condition('u.vid', $subquery, 'IN');

$result = $query->execute()->fetchAll();


Zen subtheme region templates not being used?

A few things to check on that might be causing your error:

Is the footer region populated with a box or content? If no, the region won't show.
Have you edited the region--footer.tpl.php of the main Zen theme or your subtheme? Editing the wrong one won't show the result.
Is the footer properly actived (not commented) in your subthemes's .info file? (regions[footer] = Footer)


Filter under condition based on value checkbox of current user profile

As you can already display the taxonomy terms from the ELSE part of your logic diagram in a View, it is quite easy to achieve what you want with a template file for your View. Find the suitable template here and adapt the code underneath, where I assume that you use views-view-field--YOUR_VIEW-YOUR_BOULEAN_FIELD.tpl.php:

global $user;
if ($user->field_YOUR_BOULEAN_FIELD['und'][0]['value'] == 1) {
  $output = taxonomy_term_load($tid)->name;
}

The variable $tid for taxonomy_term_load() should be the tid of your taxonomy term New.


Two different sites, two installations, no database or core sharing

put your drupal sites in separate subdirectories of htdocs, e.g .../htdocs/site1, ...htdocs/site2
access your sites using the mamp localhost url, e.g. http://localhost/site1

If you know how, you can also create virtualhosts in /Applications/MAMP/conf/apache/httpd.conf and edit /etc/hosts on your mac, so that you can access the sites with whichever url you choose, such as:

http://site1.local

Databases: just upload your databases using MAMP's phpmyadmin, and edit your sites' settings.php to use the respective databases.


Can entity references have "types" like links in Jira?

In Drupal 7, this is possible with the Relation module.
Relations are entities.
So instead of creating entity references to link nodes, when using the Relation module, you create Relation entities, and these Relation entities can contain entity references to two or more entity references to connect them via a "type".  In the case of the Relation module, this is an entity type.
Also, because relations are entities, you can add fields to them.  And the module provides Views integration and other useful features.
Unfortunately, the port of Relation to Drupal 8 has been abandoned and the maintainers now recommend using the features of core itself-- this is possible, but it's a lot more work than what Relation provided out of the box.
Creating a similar config to Relation module in D8

Make each "type" its own entity type.
Add entity reference fields to each type and set them appropriately.
Customize your Views accordingly.


A comment from the Flag Add Checkboxes ad Display Type feature request offered a good foundation for using JavaScript. I read up on JQuery and changed the code slightly to work with D6. All credit goes to ngmaloney.

Drupal.behaviors.alter_flag_links = function (context){
    //Returns a checkbox dom object
    var cb_factory = function(class_attr, checked) {
      var checkbox = document.createElement("input");
      checkbox.type = "checkbox";
      checkbox.checked = checked;
      jQuery(checkbox).attr('class', class_attr);
      return checkbox;
    }
    //Convert each link to a form checkbox.
    jQuery('span.your-flag-value').each(function() {
      var flag_link = jQuery(this).children('a');
      if(flag_link.length == 0) {
        return;
      }
      flag_link.html(''); //Hide text
      var flag_classes = flag_link.attr('class');
      var checked = false;
      var class_attr = 'compare-cb';
      if(flag_classes.match(/unflag-action/)) {
        checked = true;
      }
      //Only Add form element if it doesn't exist
      if(jQuery(this).children('input').length == 0) {
        var elem = cb_factory(class_attr, checked);
        jQuery(this).prepend(elem);
      }
    });
    //Attach an event listener to each of the new checkboxes
    jQuery('input.compare-cb').each(function() {
      jQuery(this).click(function() {
        jQuery(this).parent().children('a').click();
      });
    });
};


Product Bundles & referenced products in Drupal Commerce

In case anyone stumbles across this, you can use the following function:

function commerce_product_bundle_get_sub_line_items(&$parent_line_item, $reset = FALSE){
    //...
}


Javascript "once is not a function" errors after library include

I had this happen in my custom module as well. I then noticed it worked when logged in but once I was unauthenticated my code would throw this JS error. In the end it was simply an issue where I needed the dependency you listed already in my custom module library file dependencies:

dependencies:
- core/drupalSettings
- core/jquery
- core/jquery.once

Once I added this the required JS file was included when unauthenticated as well.

For a little extra information that forced the following JS file to be included as well:

It looks like you solved your specific instance which ended up being multiple versions of jQuery being installed. I would avoid that if possible as it complicates things a bit.


How can add a textfield to user/register page form in drupal 7?

Drupal 7 provides the ability to add custom fields to the User through admin/config/people/accounts/fields.  This functionality should already be in core.


How to store second dropdown value in database

Your error:

  Notice: Undefined index: city_element_wrapper in
  form_test_custom_form_submit()

means that index city_element_wrapper is missing in $form_state variable. Do this:

function form_test_custom_form_submit($form, &$form_state) {
  $prog_id =1;

  db_insert('tot_prog')
    ->fields(array(
              'state1' => $form_state['values']['state1'],
              'city_element_wrapper' => $form_state['values']['city_element_wrapper']['city'],
            ) )
    ->execute();

  drupal_set_message("successfully saved Settings");
}

Always take the reference of $form variables if you want to fetch values from the variables or update the values of the variable. For more details about PHP reference read this.


How predefine templates for webform email templates?

Ok, I got this sorted out, I used hook_form_alter to get the stuff into the select field, and did an override on the javascript-file from the webform module. I will try to answer it more complety in the next days if I have the time to do so.


How do I access paragraphs with the JSON API?

2 steps required :)

create the paragraph(s) by doing a POST request, and receiving the revision ID of the created paragraph,
update the parent entity by assigning the paragraphs' revision ids to the paragraph field (entity revision reference field).

Step 1.

jsonbody = {
    'data': {
        'type': 'paragraph--study_history',
        'attributes': {
            'parent_id': localStorage.getItem('uid'),
            'parent_type': 'user',
            'parent_field_name': 'field_study_history'
        },
        'relationships': {
            'field_school_ref': {
                'data': {
                    'type': 'node--school',
                    'id': this.reg_selectedUni['id']
                }
            }
        }
    }
};

return this.api.apiPost('/jsonapi/paragraph/study_history', {}, jsonbody)

We are using our custom service api (ApiService.ts) which has the apiPost function that does exactly what you'd imagine :)
So the logic above should be easy to adapt to your own code.

Note that if you want to add more fields (text fields for example, you add them to the attributes section).

Step 2.
Here’s how we update the user, PATCH it to have the created “study history” paragraphs.

const jsonbody = {
    'data': {
        'type': 'user--user',
        'id': uuid,
        'relationships': {
            'field_study_history': {
                'data': [
                    {
                        'type': 'paragraph--study_history',
                        'id': schoolhist_info['data']['id'],
                        'meta': {
                            'target_revision_id': schoolhist_info['data']['attributes']['revision_id'],
                        }
                    },
                    {
                        'type': 'paragraph--study_history',
                        'id': unihist_info['data']['id'],
                        'meta': {
                            'target_revision_id': unihist_info['data']['attributes']['revision_id'],
                        }
                    }
                ]
            }
        }
    }
};
return this.api.apiPatch(this.endpoint.getUsers + '/' + uuid, {}, jsonbody);

Where this.endpoint.getUsers is /jsonapi/user/user.
This should be enough to get it to work, else comment and I can update.


I think it's better idea to use token instead of php code for this simple replacement.

When you have the token module installed you'll have a list with available tokens under the Pattern for the title: input box. And if your field is named *field_my_field* then you'll have the tokens

[field_my_field-formatted]
[field_my_field-raw]

or something like that to choose from.


Ok. I got my problem. I was using checkbox cck field. So the Rules were checking all values to be matched. To overcome this issue, I used Rules Bonus Pack module and in that used "Field value is one of several" condition.

Finally got it working as desired!


This could be default browser styles. It does't matter if they are added by the browser by default or by CSS, the solution is to remove them with CSS.

li {
  list-style: none;
}

You should create a sub_theme where you create and add your custom styles.


Using pre-process to wrap multiple regions in html

How can I wrap those 4 regions inside a div so I can set the
  background color?

You can use .tpl files for that.

<?php if ($region_first || $region_second): ?>

        <?php if ($region_first): ?>

                <?php print $region_first; ?>

        <?php endif; ?>

        <?php if ($region_second): ?>

                <?php print $region_second; ?>

        <?php endif; ?>

<?php endif; ?>


How to output data from module to a page. What are my options?

If you already use Panels, and/or if you have an argument to send to your code, i'd advise Panels, definitively...

Great caching powers, multi-instances and rules of access.

But if you don't use it, don't make your site heavier with it and keep it with Blocks.

What about tpl.php ?


How to create a module Dependency Graph?

There is the sandbox drush module dependency_analysis

It provides a drush command that produces a dependency graph using graphviz.  For me, I found that it was a simple matter of installing graphviz using homebrew:

$ brew install graphviz

And then follow the project page description.


How to escape markup with check_markup in a twig template?

This seems like something you could do in a preprocess function and create that variable. At that level, you can use check_markup to check it.

Be sure to see the two notes on the docs page:

  Note: Because filters can inject JavaScript or execute PHP code,
  security is vital here. When a user supplies a text format, you should
  validate it using $format->access() before accepting/using it. This is
  normally done in the validation stage of the Form API. You should for
  example never make a preview of content in a disallowed format.

  Note: this function should only be used when filtering text for use
  elsewhere than on a rendered HTML page. If this is part of a HTML
  page, then a renderable array with a #type 'processed_text' element
  should be used instead of this, because that will allow cacheability
  metadata to be set and bubbled up and attachments to be associated
  (assets, placeholders, etc.). In other words: if you are presenting
  the filtered text in a HTML page, the only way this will be presented
  correctly, is by using the 'processed_text' element.

Here is a similar question/answer (albeit from 2014) that may still apply.


Enabling a new content type in the add new content

Go to structure >> Menus >> Navigation (admin/structure/menu/manage/navigation) and make sure to enable the content type link in that list.

Here I'm showing example for Article Content type.


Trimmed body field only show first paragraph

Your best bet is a custom formatter. Create a custom formatter with the custom formatters module:

  The Custom Formatters module allows users to easily create custom
  CCK/Field Formatters without the need to write a custom module. Custom
  Formatters can then be exported as CTools Exportables/Features or
  Drupal API Formatters.

Once installed just write some php code and format and insert the particular text that you're looking for.


How to hide "Include file in display" in File Field?

You need to set that in the field's settings page.

Structure > Content Types > [your content type] > Manage Fields > Edit [your file field]

You will see settings for the Enable Display Field Option. The caveat is that if you already have data in this file field, unchecking this may not have an effect.

(See my screen capture)


You can theme a individual webform using webform-form-nid.tpl.php.

For example if our webform node id is 7 , create a template file namely webform-form-7.tpl.php and place it in your theme folder. Clear site cache.

Do a print_r($form); to see all the elements. Then render each elements in file within your html elements.

<li>
    <?php print drupal_render($form['submitted']['name']); ?>
</li>

As  @Patrick Kenny said read the theming.txt, it explain all aspects of theming a webform


How do I organize content based on date field in a Y > m > d hierarchy?

So for Drupal 7: Take look at this description:
http://chrisshattuck.com/blog/how-create-monthly-archive-block-drupal-blog-views

This is basically an explanation of the "Archive" view (disabled by default) shipped with views. Take a closer look at it and copy it to apply a few minor changes.

It gives you a monthly grouping of your content if there is no argument passed. That is actually the trick. Instead of the "created" date of your content just use the date field you have as argument.


I had to insert it with a T in between the date and time as follows:

$currentDateString=date("Y-m-d", strtotime($current_date))."T".date("H:i:s", strtotime($current_date));


Parent-child node relationship without using taxonomy?

You can use Entity Reference module.

You create two content types: Parent and Child.

in Child content type, add an mandatory "Entity Reference" field that reference to a Parent node.


How do I reference (what is the syntax I have to use) to get the data of my Profile2 custom fields?

You should use the field_view_field() function. Have a look at the follwing page for more information:
http://coder1.com/articles/printing-or-rendering-node-field-or-profile2-field-drupal-7


Is there a Node Reference URL Widget module for entity references?

OK.  I see there is Entityreference prepopulate.

  Allow prepopulating any Entity reference field via URL

Going to try it now.


Remove  tag after form tag in user register form Drupal 7

That <div> is actually there to ensure XHTML compliance so it shouldn't really be removed.

If that's not an issue for whatever reason, you need to override theme_form(), which is responsible for adding that <div>, and just remove it from the returned markup. The full code is quite short so I'll include it:

function MYTHEME_form($variables) {
  $element = $variables['element'];
  if (isset($element['#action'])) {
    $element['#attributes']['action'] = drupal_strip_dangerous_protocols($element['#action']);
  }
  element_set_attributes($element, array('method', 'id'));
  if (empty($element['#attributes']['accept-charset'])) {
    $element['#attributes']['accept-charset'] = "UTF-8";
  }
  return '<form' . drupal_attributes($element['#attributes']) . '>' . $element['#children'] . '</form>';
}


Can I work with hook_user_login() directly within user.api.php?

The .api.php files are documentation only, they're never included in a request.

hook_user_login() can only be implemented in a module, so you'll need to write one for this.

It's pretty straightforward, the Module developer's guide will get you started quickly.


How can I show parents after child term inside a Views exposed filter?

The exposed taxonomy filter select box form doesn't have any hierarchy built into the select form array (e.g. using subarray to present optgroup elements). Rather, its labels are indented to present the hierarchy on each select option.

To alter the labels, you can utilize hook_form_views_exposed_form_alter() to alter the selectbox array structure with some string manipulate logic. For example:

function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  $parent = '';
  $options = $form['tid']['#options'];
  foreach ($options as $index => $option) {
    if (is_object($option)) {
      $label = reset($option->option);
      $key = key($option->option);
      if (substr($label, 0, 1) != '-') {
        $parent = $label;
      }
      else {
        $options[$index]->option[$key] = $options[$index]->option[$key] . " ($parent)";
      }
    }
  }
}


How to attache multiple nodes of a node type to another node of another node type?

Install the references module, once you done that, you can enable the node_reference submodule and attach a "Node Reference" field to your "restaurant" content type.

Next, set the "item" content-type as reference for the field and the "Number of values" setting as "Unlimited".

When creating or editing a restaurant, you should now be able to link multiple menus to the node.


What version of Drupal are you using? If you are using 6x you will have to create a "blog" content type and fields using the CCK module. In D7 Content types and custom fields are built into core. Make sure you uncheck the "promoted to front page" option in the content type settings so that your posts won't default to the front page. If you want your blog to go to a link other then the homepage (blog for example). You will need to install the views module, and create a "blog" view page, and configure that view to display your "blog" content types as either teasers (that will further link to the full node) or to full nodes themselves if you don't prefer teasers. Then go over to menus and create a "blog" menu link that leads to the new blog view that you created. Now every blog post will post to the blog view.


How can I secure a custom module that contains sensitive data?

As long nobody is able to read this php files, there's no problem. If your host is set-up correctly and you are using the standard .htaccess file which comes with core, you should be fine.

An other question is who has access to your host and your source code. A good practice is to avoid any sensitive data inside git or any other source control system. A way to do this is to have a local.settings.php file a longside your settings.php. You can include it in your settings.php by ading this code at the end of the file:

if (file_exists(dirname(__FILE__) . '/local.settings.php')) {
  include(dirname(__FILE__) . '/local.settings.php');
}

Make sure this local.setings.php file is never visible to unauthorized people.

You can set any system variable in local.settings.php to your needs.


Why does my node-type-specific hook not work

Be sure to return $node at the end of your mynode1_view function. (This is different from most hooks, which generally modify the variable by reference).  You may have missed this. See this comment.


Referencing CSS file from theme library inside Embedded Widget Paragraph type

Your thought process is correct. To implement below script tag is to be referenced inside the embedded widget
Like: Js
<script type="text/javascript" src="/custom.js"></script>

Like : Css
<link href="/custom.css" rel="stylesheet" />

Thanks


There is an open core issue to add validation to content entities: https://www.drupal.org/node/2745797

With that patch, you can enable validation thusly:

destination:
  plugin: entity:node
  validate: true


Migrating to the webserver - what do I have to take care for?

I strongly recommend you look into using drush to synchronise sites.  Although it admittedly will not solve your permission woes, it will greatly ease the pain of doing this for every update you need to push.

As for permissions, there are many ways of configuring depending on your set-up and how safe you want to be. I usually just have all files belong to webserver and add my user to webservers group, but like I said many things can go wrong with permissions.

Coming back to drush rsync, I would most probably attack this by setting up 2 aliases, one for @dev and the other one for @live (or @stage). So, with those aliases you can rsync  via the simple command  drush rsync @dev @live your whole site will be transferred. Just set proper permissions the first time you do this on /files and other folders needing write access, and you should be set to go.

PS: Do look into drush sql-copy and other goodies hidden in drush.  I cannot imagine doing this manually anymore, I have used aliases for a few years now and would NOT go back the old way!

Hope that helps, good-luck!


Juste return "TRUE", not "$image", It is works for me.

 $image->ops[] = "-resize 1600x1600";
 return TRUE;


Drupal 8 Ajax Form Submit works only once?

Your problem is probably here:

$form['submit']['#value'] = time();

You are changing the value of the submit button in the ajax callback. However, Drupal has already cached the form before the Ajax callback is hit. Why that matters is that Drupal uses the value of the submit button to determine which button was clicked, comparing it to the values in the cache. Since your cached value will be different than the submitted value, it cannot properly determine what it needs to do.

You need to change the value of the submit button either in the form definition, or in a form_alter hook.


Sub-themes .tpl file is not overwriting parents

Please try to see to follow same folder structure in base theme which parent theme have for .tpl files. Also check if you added base template file e.g. node.tpl.php for node--type.tpl.php link and also implement THEME_preprocess_page.

function THEME_preprocess_page(&$variables){
  if (isset($variables['node']->type)) {
   // If the content type's machine name is "my_machine_name" the file
   // name will be "page--my-machine-name.tpl.php".
   $variables['theme_hook_suggestions'][] = 'page__' . $variables['node']->type;
   }
}


It is not clear what you want to achieve here but I'm making a guess that you want to display the full content. You can either change the "Teaser" display mode for the content type "article" or you can create a template file "taxonomy-term--tags.tpl.php" and customize it.


You're using the 3.x-dev version of Corolla, which is not quite ready for release.  You should consider using the stable 2.x release instead.

To fix the error, you will need to go the Corolla theme administration page (/admin/appearance/settings/corolla) and choose either "mobile first" or "desktop first" under "CSS Global Settings."

P.S.  In the future, this type of theme-specific question should be filed as a "Support request" in the Corolla issue queue.


Setting the default front page setting to be translatable

I created a proof of concept Drupal (latest - 8.3.5) instance on simplytest.me earlier today to check if this is actually something you cannot override in language//system.site.yml. I had no problem to differentiate frontpage for default (english) language and additional language.

Just remember that front property is nested under page key.


Best location to keep the javascript files in drupal 7

If it's a theme, and if you are defining scripts in .info file, keep the .js files in scripts folder of your theme folder (e.g sites/all/themes/mytheme/scripts). You don not have to define the whole path. Just enter the relative path to the .info file (scripts/myscript.js) and it will get included in the entire site.

if you are using drupal_add_js, in a custom module, the common practice is to keep the file in module's folder. Set it as drupal_get_path.

Although it's not recommended, if you are hardcoding the script in html.tpl.php or page.tpl.php folder, I'd place the js file in theme folder and use a drupal_get_path to get the actual path.


migrate import image (image_import plugin doesn't existe)

Solved by installing and enabling the contrib module migrate_file


Efficient and easy Drupal 7 Development to Production workflow

In short, I would:

Use features to get my configuration in code.
Use git to manage my code.
Use drush to manage my databases.

Why to use git to manage code:

Drupal.org uses git to manage the Drupal project and all the modules.
Version control of code allows you to easily see what changes have been made to your code over time.  Without this, debugging/rolling back to a known good state is much harder.

When using git, I personally avoid complicated features (like submodules for Drupal modules) and simply commit all my code (Drupal core, contrib modules, patches, and my features) to a single repository.

If you already have dev and staging servers set up, getting git to push code to all three machines shouldn't be too hard to set up.

Why to use features to get configuration into code:

If you do dev/staging/live, you are going to have three sites now, not just one.  Keeping track of configuration changes among three sites is a mess.

You basically have two options:

Write down all your changes in a text file and apply them site-by-site manually.
Use features.

Although #2 is harder to set up, it's much easier to deal with in the long run.  A command like drush @mylivesite fd will quickly reveal how the configuration on your live site differs from the code in the features (managed by git).

In addition, as an added benefit of getting everything in features, you can edit the features code directly with a text editor; sometimes this is faster than using the Drupal admin UI.

Why to use Drush to manage databases:

Drush has a number of commands for syncing databases.  It can be a bit of pain to get your servers set up to do this, but once you do, the time savings are tremendous.  Google for tutorials for details.

In conclusion:

With this setup, most of your configuration will be in code (thanks to features).  Your code will be version-controlled and easily pushed between servers (via git).  What git can't handle, the database, will be taken care of with drush.


Generate Install Scripts from current Nodes, Views, Fields in Drupal

Looks like Features module is what you really want:

The features module enables the capture and management of features in Drupal. A feature is a collection of Drupal entities which taken together satisfy a certain use-case.
Features provides a UI and API for taking different site building components from modules with exportables and bundling them together in a single feature module. A feature module is like any other Drupal module except that it declares its components (e.g. views, contexts, CCK fields, etc.) in its .info file so that it can be checked, updated, or reverted programmatically.

With addition of UUID Features Integration:

The UUID Features Integration module provides a mechanism for exporting content (nodes, taxonomy, fields) into a features module. What's that you say? You thought features was only for configuration? This module is meant to be used in the cases where certain pieces of content straddle the line between pure content and configuration.

Of course you will probably only use a subset of it's capabilities, but it should cover all your needs with content types, nodes, and views definitions.


You can simply use Views Selective Filters Module for that.
Here is an introduction about this module :

This module allows to have an exposed filter only show options that belong to result set.
The options are calculated real-time with the current View's configuration, including the filters selected by the user so you get dynamic dependent filters, that is, when the value of one filter is changed, the list of options of the selective filters are updated accordingly to the trimmed down result set.


How to get the url from uri, uri given as string

Based on that string alone you'll never get a url. Do you mean how do you get the url of the current site?

In Drupal you don't need to. As Ivan recommended in his comment, you just need

This is the way to do it if the file was uploaded in Drupal and you have the uri.

file_create_url($path)
https://api.drupal.org/api/drupal/core!includes!file.inc/function/file_create_url/8

If you don't have the URI (for example you need to link to a file in your theme, then use:

drupal_get_path('theme', 'your_theme');

https://api.drupal.org/api/drupal/core%21includes%21bootstrap.inc/function/drupal_get_path/8

Then combine that with a link relative to the theme instead of relative to the server root like your current $directory is:

$directory = "files/myfile.png";

Then jam them together:

$my_url = drupal_get_path('theme', 'your_theme')."/".$directory;

If you do need the full site URL for some reason, you should be able to use global $base_url;
(a global variable in Drupal) or check out https://stackoverflow.com/a/14500505/430191


How to delete/remove Views display programmatically?

Here is an example you would put in mymodule.install

/**
* Disable workbench views
*/
function mymodule_update_7001() {
    // an array of views (their view name) I want to disable
    $viewnames = array(
      'workbench_current_user',
      'workbench_edited',
      'workbench_moderation',
      'workbench_recent_content',
    );

    // grab the array of views that are already disabled
    $views_status = variable_get('views_defaults', array());

    // add our views to be disabled to the list
    foreach ($viewnames as $key => $viewname) {
      $views_status[$viewname] = TRUE;
    }

    // reset the variable with the new list
    variable_set('views_defaults', $views_status);

    // empty cache now
    if (function_exists('views_invalidate_cache')) {
      views_invalidate_cache();
    }
}


Access description field for file in a view

You can get the file description to display by adding your file field (just as Content: fieldname), then choosing to 'Rewrite Results'. For the Replacement Text, there is an option to use [field_fieldname-description].

Reference: http://drupal.org/node/1128270#comment-5253600


Stylesheet for specific page overwritten by standard css

Add weight to the CSS:

drupal_add_css(drupal_get_path('theme', 'subtheme') . "/css/login.css", array('weight' => 100));

See the drupal_add_css() API page for more info. The group option may also be relevant as this also affects the weight.

Also if the specificity of a rule in style.css overrules a rule in login.css it won't matter what order the CSS files are included.


Yeah, i know according to strict forum rules it's not fine to answer your own question :-)
But anyway ...

I not realized, that the default fields are stored in table field_config and just a instance for a node in table field_config_instance.

I added the following lines to mymodule_install() of my module:

$instance = array(
  'field_name' => 'field_tags',
  'entity_type' => 'node',
  'label' => 'Tags',
  'bundle' => 'mynode',
  'widget' => array(
    'type' => 'textfield',
  ),
);

I don't need field_create_field() because the field_tags already exists.

And i added a field to the custom node form:

function mymodule_node_form($form, &$form_state, $node) {
...
   $form['field_tags'][LANGUAGE_NONE] = array(
       // '#entity_type' => 'node',
      '#type' => 'textfield',
      '#title' => t('Tags'),
       // '#autocomplete_path' => 'taxonomy/autocomplete/field_tags',
      '#field_name' => 'field_tags',
       // '#bundle' => 'mymodule',
      '#element_validate' => array(
                                 0 => 'taxonomy_autocomplete_validate',
                             ),
       //    '#after_build' => array(
       //                        0 => 'field_form_element_after_build',
       //                      ),
      '#field_parents' => array(),
      '#language' => LANGUAGE_NONE,
      '#columns' => array(
                        0 => 'tid',
                    ),
      '#parents' => array(
                       0 => 'field_tags',
                       1 => LANGUAGE_NONE,
                    ),
   );
...
}

I tried to find out the obligate values. I'm not sure if it's wise to add more values?! I just realized that some values are not nescessary (the commented ones).


Exclude a free product from total calculation

Create a rule with the event Calculating the sell price of a product.

There, you can check for the SKU of the product and set its price to zero (using the Set data value action).

You can also use the Subtract an amount from the unit price action to assign the value to a price component so that it appears in the totals (this will require extra configuration)


How to add and render a region in omega 3.x subtheme?

Clear the cache first.

Go to the subtheme appearance settings, click the "Zone and region configuration" tab, and scroll down to the bottom to find your "unassigned regions". Simply assign it to a zone, configure the options above, and save.

Go to Structure and check "Demonstrate block regions".


How to set a multi-value image field's default value from author's profile field on a node create form?

You can prepopulate from other content through Tokens and Entityreference field. Here's a tutorial: Automatically Populate Drupal Fields From Other Content.

I don't know if it works with images but I don't see why it wouldn't. Not sure about the multi-value fields, you can try and see.

For a custom module solution you can lean on Prepopulate.

In Drupal 8 you can create a custom Media Entity browser that would show only the current user images from that field, then you might be able to choose them, or maybe even set as default.

Saving the images into the Content types ensures that if the user changes their user images it won't affect the Proof content. But if you want to always have them the same then you shouldn't add that to the Proof content at all. Simply create a contextual Views Block that would always display the content author's proof images and display it on the Proof nodes.


You could use the Password Policy module to manage your password policies.


How do I use '#attached' to attach a style sheet?

You cannot use #attached inside your hook_theme implementation. Instead, you should add it when you're building a render array:

$blocks['content'] = $render;
$blocks['content']['#attached'] = array (
  'css' => array(
    drupal_get_path('module', 'mymodule') . '/mymodule.css',
  ),
);

As kiamlaluno already pointed out in the comments, in your code example $blocks['content'] is the render array, so the #attached element must be part of that array.


Where to place the admin screens for a module

There is a handbook page that covers where you should place these menu items.

See Information architecture

I won't copy and paste the info here as it is too long. You also don't provide any info on what your module is about, so I can't even paste a excerpt that pertains directly to your issue.

The handbook page should be considered the canonical source for this info.

EDIT:

While these are guidelines, I don't think that they are very cut and dry. I would personally place the menu where the other two major tag cloud modules (Cumulus and TagCloud) place theirs: admin/config/content and keep them both in the same spot (one as a child item of the other)


How do I create content programatically?

you can create a custom function to create a node.

function create_my_node() {
  $node = new stdClass();
  $node->type = 'your content type';
  node_object_prepare($node);

  $node->title = "your title";
  $node->language = LANGUAGE_NONE;
  global $user;

  $newnode->uid = $user->uid;
  $newnode->name = $user->name;
  $newnode->status = 1;     // 1 means published
  $newnode->promote = 0;
  node_save($node);
}


Should a form only be users to collect input and not display it?

I think its totally fine to do what you want with Form API. I once did something similar for a personality test module. On the final submit the node gets reloaded but this time in a different view mode to provide the results. If I remember it right I got inspired by Drupal's poll module which uses/used this view mode approach. By that you have both parts divided a little bit better - logically and performance related. Could that work for you?


the two issues causing this were both in the .htaccess:

this line was commented out:

RewriteBase /

and then we had to add this per subsite:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteCond %{REQUEST_URI} ^/wikifix
RewriteRule ^ wikifix/index.php [L]

including the first 3 rules:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteCond %{REQUEST_URI} ^/wiki
RewriteRule ^ wiki/index.php [L]

since both subsites start with /wiki, it was also important to have the RewriteCond for wikifix BEFORE the RewriteCond for wiki


How to override base url when creating links to public files?

You are basically describing the use case of a CDN (Content Delivery Network).
Check CDN module:

This module provides easy Content Delivery Network integration for Drupal sites. It alters file URLs, so that files are downloaded from a CDN instead of your web server.
It provides two modes: "Origin Pull" and "File Conveyor".

In Origin Pull mode, only "Origin Pull" CDNs are supported. (These are CDNs that only require you to replace the domain name with another domain name.)
In File Conveyor mode, this module integrates with File Conveyor, which allows for much more advanced setups (e.g. optimize images, transcode videos, and so on, before syncing to the CDN).


Is it possible to define hook functions in template.php instead of the module?

Yes, you can implement any alter hook in a theme, as well as  hook_theme() and preprocess hooks.

Adding $form_state['redirect'] won't do anything there, though. You need to do that in a submit handler:

function MYTHEME_form_phone_book_node_form_alter(&$form, &$form_state, $form_id) {
  $form['#submit'][] = 'MYTHEME_phone_book_node_form_submit';
}

function MYTHEME_phone_book_node_form_submit($form, &$form_state) {
  $form_state['redirect'] = 'go/some/where';
}

To ensure that your hook is running, get the Devel module installed and add dpm('alive'); in there. Then clear the caches (to be sure) and refresh the page a couple of times. If you don't see the debug message, the hook isn't being called, and it might be named incorrectly.


Views uses a different mechanism to provide variations of twig templates that doesn't work yet with the debug feature from twig.

The logic that builds those suggestions is in \Drupal\views\ViewExecutable::buildThemeFunctions(), you can debug that or ad some php statements to dump the $themes variable for a certain hook to get what you need.


Alter core "Configure Block" contextual link path or text?

I was able to accomplish this for Panels by using the following:

/**
 * Implements preprocess_panels_pane().
 */
function hook_preprocess_panels_pane(&$vars) {
  if ($vars['pane']->type == 'panels_mini') {
    unset($vars['admin_links']);
    $vars['admin_links'] = '';
  }

  // Load the currently logged in user.
  global $user;

  if ($vars['pane']->type == 'block') {

    // Check if content array is set
    $type = isset(array_keys($vars['content'])[0]) ? array_keys($vars['content'])[0] : '';

    // Check if the pane subtype is a bean
    if (strpos($vars['pane']->subtype, 'bean-') !== false) {

      // Get path of bean edit link
      $path = isset(array_keys($vars['content']['bean'])[0]) ? array_keys($vars['content']['bean'])[0] : '';
      unset($vars['admin_links']);

      // Check if the user has the 'administrator' or 'content editor' role.
      if (in_array('administrator', $user->roles)) {
        $vars['admin_links'] = '

Edit Block

';
      } else {
        $vars['admin_links'] = '';
      }
    }
  }
}


Does Drupal's theme('table') works in email body?

You can read drupal_mail() in HTML for how to output HTML in an email sent with drupal_mail().

As you are outputting links, I will add a note about that. By default l() outputs relative links that outside the website are not much useful. You need to force Drupal to output absolute links, for example using the following code.

if ($row->subject) {
  $titlerow = l($row->subject, "node/{$row->nid}", array('absolute' => TRUE)) . '
' // Your code here is not complete.
}
$rows[] = array(
  $titlerow,
  t('Reply posted by !user-link', array('!user-link' => l($row->name, "user/{$row->uid}", array('absolute' => TRUE))))
);

If you have the Devel module installed, you can see (using the following code) the difference between the output of your code, and mine.

print l('Test page', 'node/1') . "\n";
print l('Test page', 'node/1', array('absolute' => TRUE));

In my test site, what I get is the following.

Test page
Test page

As side note, remember that the $options parameter for l() can receive the same values the $options parameter for url() accepts.


I was missing the implementation of hook_theme. In order to use the template you need to declare it there.
FX

/**
 * Implements hook_theme().
*/
function mymodule_theme() {
  return array(
    'block__newsletter' => array(
      'render element' => 'elements',
    ),
  );
}

You should then have a templates/block--newsletter.html.twig.


redirect multiple nodes on same page in core search results

Finally got solution, but still I think this is not right way to achieve this. First enable the Pathauto module and make some pattern for particular content type. Then install the Redirect module. You can find URL Redirects under URL alias option in edit mode of content type.

click on Add URL redirect and add your desire path (in my case path to page /tesimonials). Thats it. It will redirect particular node to your given redirect path.

Hope this will help you...


I waited some more, cleared cache and ran cron again and it worked.


how to request multiple public image sizes from a field's filename?

But avoid … Asking for clarification,

Really? What a joke! I hate this forum so much

There are a few things happening here. When you make a change to the field in the content type UI the imagecache is being manipulated/cleared. Changing the javascript manually does not do this so the path is not pushed through the system.

The easiest way to do this is to have separate fields for each size in the content type to make them available to your js. Hide the display of the fields not needed on the page (use  hook_alter or the admin UI).

Then in your js call them programmatically. To ease the JS call I would name the fields so they can be iterated, ie. field_photo_1(lrg),field_photo_2(med),field_photo_3(sml)


How to know a user can access node/{nid} and node/{nid}/latest in fastest way

If you know the route name you can check access in PHP. For the second link you can use this route:

\Drupal::service('access_manager')->checkNamedRoute('entity.node.canonical', ['node' => '1'])).

You can find the first one with the help of the Devel module when you click on Current Route Info while displaying the content and look for [_route].

I would put the nid into the title field and override the field content in a preprocess hook. Display the link for each route if the access check returns true. Caching is no problem because caching is by default permission based.


What's a good way to prepopulate web form fields with data from an external database?

You would need to expose an API from your external database. If the external database is also a Drupal 7 site, you could use the RestWS module to do this (https://www.drupal.org/project/restws).

Once you have your data exposed via api, you would then have to connect to the api on the client's site, and you could auto populate some hidden fields via an ajax call when they select the ID. You would want to do this in a custom module.


How to display only one block in custom page using tpl?

You can use Context module for this purpose. It provides the same functionality as you require.

Note:  If you don't want to use any extra module, then it can also be done simply through block configuration setting. There are three options to control the block visibility.


can I use db_update to update a field ( appending a string to the current string in the database )

You can still use db_update() just with an expression() instead of fields(), e.g.

db_update('my_module_table')
  ->expression('myfield', 'myfield + :newstring', array(':newstring' => 'Some string'))
  ->execute();

Although it strikes me that still wouldn't work as you're trying to concatenate strings (the + operator doesn't perform string concatenation as far as I know). This should do it:

db_update('my_module_table')
  ->expression('myfield', 'CONCAT(myfield, :newstring)', array(':newstring' => 'Some string'))
  ->execute();


How to create custom template suggestion, when there is no hook suggestion?

You can do it this way

implement hook_theme_registry_alter like the following:

    /**
     * Implements hook_theme_registry_alter().
     */
    function YourCostumModuleName_theme_registry_alter(&$theme_registry) {
      // Defined path to the current module.
      $module_path = drupal_get_path('module', 'YourCostumModuleName') . "/templates";
      // Find all .tpl.php files in this module's folder recursively.
      $template_file_objects = drupal_find_theme_templates($theme_registry, '.tpl.php', $module_path);
      // Iterate through all found template file objects.
      foreach ($template_file_objects as $key => $template_file_object) {
        // If the template has not already been overridden by a theme.
        if (!isset($theme_registry[$key]['theme path']) || !preg_match('#/themes/#', $theme_registry[$key]['theme path'])) {
          // Alter the theme path and template elements.
          $theme_registry[$key]['theme path'] = $module_path;
          $theme_registry[$key] = array_merge($theme_registry[$key], $template_file_object);
          $theme_registry[$key]['type'] = 'module';
        }
      }
    }

Create Folder called templates inside your custom module folder.
Copy contrib/quiz/question_types/multichoice/theme/multichoice-alternative.tpl.php file into templates folder with the same name multichoice-alternative.tpl.php.
Clear Cache.
Now you have $form and $fullOptions variables.


Trying to convert db_fetch_object for Drupal 7

the syntax is incorrect, and the error is correct. If you need to track $i, you could do something like:

$i = 0;
foreach($result as $order){
  ...
  $i++;
}


Is there a list of file/image field subtokens?

For file https://www.drupal.org/node/390482#token-file
https://www.drupal.org/project/imagefield_tokens
and
add https://www.drupal.org/project/filefield_paths   add this module
for {The File (Field) Paths module extends the default functionality of Drupal's core File module, Image module and many other File upload modules, by adding the ability to use entity based tokens in destination paths and file names.}

Check this screenshot:


Creating a tag list in a view of multlingual nodes

You should use " Translate. Different terms will be allowed for each language and they can be translated." in the vocabulary's settings.

In the view's settings, make sure that "news category" content field's "formatter" option is selected as "Link (localized)" or "plaintext (localized)".


update only a part of url path in database

Try the scanner module instead:

http://drupal.org/project/scanner

  Search and Replace Scanner can do plain text search-and-replace, or regular expression search-and-replace, against the title, body and text content fields on all nodes in your system. This is useful for finding html strings that Drupal's normal search will ignore. The module is very handy if you are fixing typos in a lot of content, changing the name of your company, or are changing the URL of a link included multiple times in multiple nodes, among other things.

Your sql query might work but this is a little more robust and has a rollback option.


How to apply function to a chosen region only?

You can use theme_menu_tree__MENU_NAME() to target a specific menu.


is there a safe way to convert a pressflow website to drupal 6?

Pressflow and Drupal are API compatible, so you can simply replace Pressflow with the equivalent version of Drupal core. The only snag may come if someone has used private Pressflow functions in their module code on the site - but this is highly unlikely.

To upgrade, you can follow the normal upgrade path, which is to go to the highest version of Pressflow first, then upgrade to Drupal 7 or Pressflow 7.


Everything in Drupal is UTF-8 encoded, yes.

Be aware that various tools still don't properly support such characters in URLs and might display it encoded.


How do I print the name of the field for a submission a value?

The Webform submission object's data parameter is a keyed array of component ID's/component submission data. The object doesn't contain the component field name so you'll need to reference its value through data attached on the node.

For example:

$webform_node = node_load($submission->nid);
foreach ($submission->data as $cid => $data) {
  print $webform_node->webform['components'][$cid]['name'] . ':' . $submission->data[$cid][0];
}


Alter menu title or add menu item programmatically?

For example, if I take the User-Menu in bartik theme, and I want to change the My Account menu-title with Username, So whenever, the user logged in, instead of My Account that menu-item shown the Username.

Image-1: Default menu-item

Image-2: After the code

function YOURTHEMENAME_translated_menu_link_alter(&$item, $map) {
    global $user;
    if ($item['href'] == 'user') {
      $item['title'] = t($user->name);
    }
}

Now, same way as shown in the above code, you can change the apply the href of any particular menu-item and there it will show the user-name instead of the menu-title.

I am not sure are you looking for this or other, but this is the straight code to change the men-item with username.


How to know add/edit page in hook_form_alter?

In D8 you can get the operation of an entity form with the form object:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_state->getFormObject()->getOperation() == 'edit') {
    $page = 'edit';
  }
}


Installed Wysiwyg profile module (if is not exists)
If installed configuration->content authoring -> wysiwyg profiles

select editor  drop down list

Full HTML -> ckeditor

click "Install Instruction Tab"

check ckeditor


In Drupal 7 to avoid conflicts with another library you should wrap your code in:

(function ($) {
  // Original JavaScript code.
})(jQuery);

To learn more visit: http://drupal.org/update/modules/6/7#javascript_compatibility


It is a bug. However, there is a workaround for it.

In admin/config/content/panelizer make sure to mark "Panelize", "Allow Panel Choice", and "Provide Default Panel".

Here is a link to where i found the solution


Writing to a drupal table form javascript as fast as possible

If you have zero concerns about user verification and data validation (seems to be the case given the example code) then I would post to a custom script that just boots up the database and does the write. Note that drupal_write_record is only available at the full bootstrap level.

Example code below:

/**
* Root directory of Drupal installation.
*/
define('DRUPAL_ROOT', getcwd());

// Boot up Drupal.
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);

$name = $_POST['propertyName'];
$value = $_POST['propertyValue'];
$result = db_query('SELECT * FROM {global_properties} WHERE property=:property', array(':property' => $name))->fetchAll();
$record = array(
  "property" => $name,
  "value" => $value
  );
$primary_key = !empty($result) ? array('property') : NULL;

// Load up code for drupal_write_record().
// Untested and might break stuff as we are not at a full bootstrap.
require_once DRUPAL_ROOT . '/includes/common.inc';
drupal_write_record('global_properties', $record, $primary_key);

If you do care about user verification and server side data validation and thus need a full drupal bootstrap but the client does not care about what is returned then httprl's httprl_background_processing() function might do what you need. Example of this workflow below.

/**
* Root directory of Drupal installation.
*/
define('DRUPAL_ROOT', getcwd());

// Cut The Connection.
require_once DRUPAL_ROOT . '/sites/all/modules/httprl/httprl.module';
httprl_background_processing();

// Fully Boot Up Drupal.
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

// Do various user checks here.

// Run Example code.
$name = $_POST['propertyName'];
$value = $_POST['propertyValue'];
$result = db_query('SELECT * FROM {global_properties} WHERE property=:property', array(':property' => $name))->fetchAll();
$record = array(
  "property" => $name,
  "value" => $value
  );
$primary_key = !empty($result) ? array('property') : NULL;

drupal_write_record('global_properties', $record, $primary_key);

What the above example will do is return ASAP to Apache but drupal/php will run in the background. If the above example doesn't work there is one other option using HTTPRL in order to get a background worker running.


How do I programmatically create a view in a custom module?

Place the YAML file in config/optional as you would normally do to create the view on install optionally when Views is enabled.

Then use an update hook to check whether the view exists when updating the module and create it in PHP by reading the YAML file:

function dblog_post_update_convert_recent_messages_to_view() {

  // Only create if the views module is enabled and the watchdog view doesn't
  // exist.
  if (\Drupal::moduleHandler()
    ->moduleExists('views')) {
    if (!View::load('watchdog')) {

      // Save the watchdog view to config.
      $module_handler = \Drupal::moduleHandler();
      $optional_install_path = $module_handler
        ->getModule('dblog')
        ->getPath() . '/' . InstallStorage::CONFIG_OPTIONAL_DIRECTORY;
      $storage = new FileStorage($optional_install_path);
      \Drupal::entityTypeManager()
        ->getStorage('view')
        ->create($storage
        ->read('views.view.watchdog'))
        ->save();
      return t('The watchdog view has been created.');
    }
    return t("The watchdog view already exists and was not replaced. To replace the 'Recent log messages' with a view, rename the watchdog view and uninstall and install the 'Database Log' module");
  }
}

Source: dblog_post_update_convert_recent_messages_to_view


You can add the path to your homepage from admin/config/system/site-information
And replace /node/1 to /home.
You don't need an even subscriber to do that.