Is it possible to remove classes from a field that uses the Rendered entity format? I have an entity reference field that is being handled by Display Suite. Even when setting the field template to expert, I can't completely strip away the default classes. The markup still has a div wrapper like so:

      Configure

Edit

Delete

Manage display

    Chicken Breast Tenderloins

Is there any way to remove those classes? Like maybe using a preprocess function or something?

Generally:
You could modify the display of the content type referenced by the Entity reference field. There you can use Display suite again for formatting the fields of the referenced content type and have it styled your way.

Especially, regarding this:

  Configure

Edit

Delete

Manage display

There is an option "Display Links" on the Rendered Entity. If you uncheck this, you can get rid of this code. This is done in the content type where  the Entity Reference field is included, not in the referenced conten type.

If you want to change this:

Go to the content type you are referencing and check the display. It seems you are using the 1 Col Display, so you can use ds-1col.tpl.php template. There you can change the classes.


Remove order from Field Collection set in form I am using the Field Collection and Field Collection Fieldset modules to group a set of elements in my form. But what i see in the form is an Order column for the fieldset items, which i would like to hide, as shown in the below screenshot.

I have tried a lot to figure out if i can hide the Order from the backend, but i could not find a setting for it anywhere. So i am now looking forward to use a hook, to hide it. I also checked the field level structure using Devel module and dpm($form); but i have no idea on how to accomplish this. Can anyone help me?

Well, as Rupesh suggested in his comment, i was able to use CSS for hiding the Order column in my form:

First, i specified an ID for the fieldset field in my module's node_form_alter() function:

$form['field_user_details']['#attributes'] = array('id' => 'user_details');

Then in my CSS, i used these lines to hide the Order column:

#user_details table th:nth-child(2) { display: none; } /* Hide the Order column Label */
#user_details table td.delta-order { display: none; } /* Hide the Order column */


How to get a same result of Views with Random Sort Criteria There is a View which it's Sort Criteria is Random.I have to use the following code to implement two different displays of one view.

print views_embed_view("library","block_0",$term->tid);
$views = views_get_view_result("library","block_0",$term->tid);
//some other codes that retrieve data from $views

The problem is, because the View is Random the above two lines return different results while I need to have one. How do I can solve this problem?

if its in the same context, you can assign a variable and print it twice

$output = views_embed_view("library","block_0",$term->tid);

print $output;
print $output;

if that is not the idea, you could simply do what views_embed_view() does manually by loading the view first which gives you access to the content, and then calling the preview - here's the code from the function:

function views_embed_view($name, $display_id = 'default') {
  $args = func_get_args();
  array_shift($args); // remove $name
  if (count($args)) {
    array_shift($args); // remove $display_id
  }

  $view = views_get_view($name);
  if (!$view || !$view->access($display_id)) {
    return;
  }

  return $view->preview($display_id, $args);
}


Tools to create registration site with calendar and jQuery/ajax I belong to a volunteer organization that uses a painful .NET site for signing up for shifts (for example, you can change registrations for anyone, not just yourself), so I'm looking to create a Drupal site that can handle this process much easier and also allow admins to make changes without having to pay someone to make changes when needed.

You can see the current site below.  Each column is a day, the numbers (140, 148, etc.) are the stations, and the second column is the position. At one glance, you can see who is signed up on a given day and at which station. This is just one small part of the entire page, which is a calendar view of a whole month.

What I would like to do is create a "Register" button for each slot that uses ajax when clicked that would register the user for the shift and replace the button with the user's name (after doing some validation, such as making sure the user isn't signed up for another slot at the same time, they have permission for that slot, etc.).

The trickiest part is creating the custom form and then displaying it in the calendar.  As with any Drupal site that needs a calendar, I'm looking at the Calendar and Full Calendar modules.  Both seem to require nodes with date fields and Views displays to show a calendar, so I'm guessing I would need to create something like a Shift entity with a date field and then create the node via the ajax code.  The bigger question is how to create the custom form and display it in the appropriate date in the calendar.  Is it a matter of creating a custom Views display handler for the form, or is there a simpler way? Once I figure that part out, the rest will be pretty easy.

Thanks.

Creating the form should be as easy as simply  as creating a content type and populate it with your needed fields. This content type will have the date,  the stations, etc etc.

Then, using views will be as easy as list your nodes. If you need to display them in a calendar you can customize your view using third modules, calendars or customizing your own view.

Good luck :-)


How to display the comment form of a node in a popup? How can I display the comment form in a popup. I want the functionality when I click on the link "add new comment" on a node, the comment form should appear in a popup window.

Any one who have some idea?

There is Dialog API for Drupal 6, and Drupal 7 (although only the development snapshot for Drupal 7 is visible in the project page). This module contains sub-module Dialog Comment.

For Drupal 7, as I can see, there are some problems with modules for popup dialogues.


User Content with image gallery and text i am building a little "show and tell" page, for showing pictures of a room, basically as practice to get into Drupal but the page will be used later.

What i have managed (as it was pretty easy):
1) Generate an custom content type for the room
2) Add fields for the room for the information

But now i got stuck: The users should have the ability to upload multiple pictures within the form (i think pluploads will handle this). The room should then have a gallery for the pictures. How do i add the upload form to the content type and how do i manage to get a gallery in the content type, that shows only the pictures a user added to this post

I tried the media gallery module, but it seems to only have static album pages and can not be embedded in a content type.

You can configure the number of images the user can upload while creating a node in the field settings (manage fields page of your content type)

Once the images are uploaded you can display them in a slider/carrousel style using modules such as :

Galleria
Gallery formatter

Or you can just display clickable thumbnails (and a bigger version in a lightbox.)

You can set the image dimensions in : /admin/config/media/image-styles

You need to tell me more about the way you want your images to be displayed.
What version of drupal are you using ?


Webform token formatting I'm trying to get the answers from one form, pre-filled in another form by adding tokens in the confirmation URL. This works for most answers while using the token: [webform_submission:values:?]
However one of the answers I need to pre-fill is based on a content type (Entity select question), instead of sending just the node number of the content type, it sends 'node 101' (node%3A101) in the URL. I need the 'node%3A' part to disappear in order for the pre-fill to work.
This is how my confirmation URL looks like: /thank-you/?destination=[webform_submission:values:destination:raw]&e_mail=[webform_submission:values:e_mail]
The e-mail token works, the destination token not. If I leave the raw part out it will send both the destination name and the node in the URL, you will then get something like this: Sri%20Lanka%20%28101%29. The node of this content type (Sri Lanka) is 101.

You need to add the :urlencode suffix and change [webform_submission:values:e_mail] to [webform_submission:values:e_mail:urlencode]


Multiple sites, each is either one page (with multiple editable content) or has multiple pages I tried researching into this on google for a while, but I'm stuck.

Basically what I'm trying to do is this: I have a "big" main website.  Then, on the same drupal installation I want to have a "mini" site that will have a completely different theme, and only one page (but the page will have multiple editable content).  I also will have another site that will have a completely different theme, completely different navigation, and multiple pages.  Final piece that has me puzzled is that this will be on a subfolder basis.  By that I mean / will have the main site, /sitea will have the single page site, and /siteb will have the multipage site.

Any suggestions on how to handle this?

If you don't need multiple domains (or sub-domains for that matter) you could probably get away with using a custom module to simply switch themes under a given criteria (URI path, user role, etc).

How do I change a theme based on the URL?


Searchable civiEvents in drupal7 I have a site that is running on drupal 7 and uses civicrm 4.4.1. I need the events to be included in the search results.

So far all I have found was dated documentation on civicrm that required modules that are not available for Drupal 7.

I also tried the search page module and it is not grabbing the events.

I would use the CiviCRM views integration to create views of the events, and ensure that these are searchable by using the Search by Page module which according to the project page "allows you to index non-Node pages, including user profiles, file attachments, and Views".


How to create a protected RSS feed We are planning to provide an RSS feed (from a Drupal site) to someone who is going to display it on their site. Is there a way to limit access to only this specific site or maybe provide an embed code they can use to display the feed on their site?

If you use Views to provide it then you can limit it by role/ permission (which will tie your user to a REST login process), else the Views RSS Feed Authentication module allows you to utilise basic auth or oauth.
There are plenty of options, but what you do will depend on how you intend to implement the feed.


How to change the 'Quantity' label in commerce-order-item-add-to-cart-form I'm trying to modify my 'Add to cart' form, changing the 'Add to cart' button text and the 'Quantity' label:

if(strpos($form_id, 'commerce_order_item_add_to_cart_form_commerce') !== false) {
    $form['actions']['submit']['#value'] = t('Book Now');
    $form['edit-quantity']['und'][0]['value']['#title'] = t('Number of days');
  }
}

The first part is working, changing the 'Add to cart' button text, but the second part is failing changing the 'Quantity' label.

Any idea how to fix it?

To change label try with:

$form['edit-quantity']['widget']['value']['#title']  = t('Number of days');

Or:

$form['edit-quantity']['widget'][0]['value']['#title']  = t('Number of days');

Use Devel to check $form['edit-quantity']['widget'] with dsm($form['edit-quantity']['widget']) or dpm($form['edit-quantity']['widget']).


Hierarchical menu of all Terms of a Vocabulary & Contents of the Terms I have Category vocabulary under which there are several terms, i.e Tabs, Smartphones, Cellphones, Umbrellas. There may me one or more contents of custom type under each of these terms (A content could be linked with one term only). I want to generate a menu (automatically, if possible) like this:

Now I've installed Taxonomy Menu module which allows to generate menu with one level hierarchy only (with only terms of a vocabulary, but no contents of the terms).

Is there a pretty solution of my problem? Thanks for caring :)

I think this is just a straightforward menu - nothing automatic needed. When you add a new node, just choose it's parent menu item.


How to format database fields in a report created with Forena? How can I choose how to display the fields from the database returned by the data block (using the Forena module)? Such as a field just returns a number, but each number of that field represents something else that I'd like to display. For example:

 if (id=5) { $text = "see website"; } else { $text = "free"; }

If this is not possible, how in general can I change how the fields are displayed?

When you're "developing" a report (= Specifying the various report options), you have a choice to do so using either of the following features:

Use the WYSIWYG Report Writer, something novice Forena users typically do, or end users that are granted permissions to "develop" their own reports (and which get saved in Forena's typical '.frx' files).
In this case, you should look at Fields (within the WYSIWYG tutorial), located also at /reports/help.reportingwysiwyg#fields in your own site.

"Code" your own reports in the XHTML language used in Forena (saved in '.frx' files), which is called "FRX Report Writing". This is what the real power users will want to do, since it gives them the full XHTML power to build any report.
In this case, you should look at Fields (within the FRX tutorial), located at /reports/help.reportingwysiwyg#fields in your own site.

Be prepared: there are quite some options to pick from ...


How do I remove the header background image in Pixture Reloaded theme? I'm not sure why this is difficult, but how do I remove the default background image in the Pixture Reloaded theme?

For Pixture Reloaded 3.x, I made a subtheme and I added this CSS:

#header, #header .header-inner {
    background: mycolor;
    background-color: mycolor; }


Upgrading Drupal 8 to a newer version from the command line using Drush? Currently I have stable Drupal 8.1 release and I would like to uprgrade my site to 8.2 dev. How can I do this via the command line with Drush if that is even possible?

If not using drush, can I just download 8.2 and extract it into 8.1 directory?

To do it via the command line you can simply run the command drush up drupal

To do it manually, it's a bit more tedious as you need to be really careful about what you want to keep, templates.. modules... themes. Basically you need to replace all core files at the root level and note that the files that reside at the root level e.g. .htaccess.. robots.txt need to be compared and merged with the latest.

I hope this helps.


page not found after migrating drupal 7 to dev version same server using drush archive-restore I have tried twice over to migrate a production site to a development version using a different database and although the files are all there and the database is also there I just keep getting a 'Page not found' when browsing to the dev version. I have checked my settings.php file which is pointing to the correct database too.

Here is a list of the process I used:

drush archive-restore /home/username/drush-backups/archive-dump/20120821113939/hampstea_db.20120821_113946.tar.gz default --destination=./hamp-dev --db-url=mysql://username:password@localhost/db_name

Any suggestions? Thanks in advance

A couple of questions:

Are you creating that dev site as a root subfolder of the production site?
If yes, do you get a page not found on the production site OR on the server?

This might be an issue with .htaccess; if you just added dev site to the root of your production website, you might need to add a rule to exclude "/dev".

I think adding this before rewrite conditions for the production site would work:

RewriteRule ^(dev).* - [NC,L]


Mixed content issue while running updates.php in Drupal 6.37 We are facing this issue again for Drupal version 6.37.
We do not have jquery update module installed.

In our case the progress bar just hangs but the functionality is accomplished.The Drupal core and modules do get updated.
When we run the update.php since ours is a https site, we get the Mixed content error

Mixed Content: The page at 'https://example.com/update.php?op=start&id=14' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://example.com/update.php?id=14&op=do'. This request has been blocked; the content must be served over HTTPS.

Any help will be appreciated.

Sorry, but I doubt this can be debugged from here. You need to:

inspect which elements, exactly, was served over HTTP instead of https.
Then, identify what created them (we may or may not be able to help)
Fix the reason - most common I know is hardcoding URLs in templates, but it might not be the case for you.

Last but not least, I find it to be much stable to use drush for updates.


How to remove Site Name from page title I'm using Omega 7.3x to theme my site, and at current, all the page headers are

[Page Title] | [Site Name]

but I'm trying to bring back google analytics reports into the site so the admin can see a list of the most active pages etc, except all the reports have the same pattern, it makes reading the report more difficult

eg, the report looks like

My Account | My Website
Fixtures | My Website
Events | My Website
Contact | My Website

I want to either remove the Site name from the page title, or just so that Google Analytics doesn't pick it up, I assume the latter is better to do in terms of SEO etc, how do I do that?

Use https://www.drupal.org/project/metatag module to modify page titles (among other things) per content or content type.

To modify what google analytics displays as title is beyond the scope of this forums


How to install Drupal 7 on Ubuntu? I'm in the process to move the development on Ubuntu 14.04.

At the beginning everything seemed to work fine but quickly I discovered it was not.

Installing new modules, by UI, Drupal stops without (displaying) any error and shows a blank page. After that, the site works undisturbed. You can go back and continue on other tasks.

After many attempts to log the error without success, I run few test with NetBeans discovering that the code stops, with no reason, in system.tar.inc, when preparing to untar the package. Really weird.

Tried with fresh install of Drupal 7.28: the same.

Now I don't know how to go on. Main suspect is PHP 5.5.9, but before starting a new adventure with PHP versions, I'd like to hear you. What should I try first?

No way.
Reinstalled starting from a new VirtualBox, Ubuntu 14.04 and Ubuntu 7.28.
Same story, all is working but stops when I try to install a new module (without errors).

I took note of every piece i installed and can't find a reason why.

apache

    apt-get install apache2

in global section of /etc/apache2/apache2.confd:

ServerName localhost

replace run user in /etc/apache2/envvars

export APACHE_RUN_USER=joe
export APACHE_RUN_GROUP=joe

rewrite mode

sudo a2enmod rewrite

MYSQL

    apt-get install mysql-server
    apt-get install mysql-client
    apt-get install mysql-workbench
    mysql_secure_installation

PHP5

    apt-get install php5
    apt-cache search php
    apt-get install php5-curl php-pear php5-imagick php5-imap
    apt-get install php5-mcrypt libssh2-php php5-dev php5-gd php5-mcrypt

changed values in php.ini

realpath_cache_ttl = 36000
max_execution_time = 300
max_input_time = 60
memory_limit = 256M
post_max_size = 128M
upload_max_filesize = 256M
default_socket_timeout = 60

apt-get install phpmyadmin

complete manually some missing conf in: /etc/apache2/apache2.conf

include /etc/phpmyadmin/apache.conf

virtual host test-me

<VirtualHost *:80>
ServerAdmin webmaster@localhost
ServerName test.me
ServerAlias *.test.me
DocumentRoot /home/joe/Workarea/test-me
<Directory "/home/joe/Workarea/test-me">
Options All
AllowOverride All
Require all granted
 </Directory>
</VirtualHost>

in /etc/hosts

127.0.0.1   test.me

DRUPAL

created a db test-me with collation utf8_unicode_ci
in: /home/joe/Workarea

wget http://ftp.drupal.org/files/projects/drupal-7.28.tar.gz
tar xzvf drupal-7.28
mv drupal-7.28 test-me

in settings.php file:

$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'test-me',
  'username' => 'root',
  'password' => '',
  'host' => 'localhost',
  'prefix' => 'main_',
  'collation' => 'utf8_unicode_ci',
);

Permissions:

chmod 644 settings.php
chmod  a+w sites/default

This could be a bug, see:

https://bugs.launchpad.net/ubuntu/+source/php5/+bug/1315888
https://bugs.php.net/bug.php?id=53829

As I had the same error and after deep diving I reached to modules/system/system.tar.inc at line 716 which calls gzopen(). Here the errors are suppressed using @.

Actually its giving following error on ubuntu 14.04:

Fatal error: Call to undefined function gzopen() in /var/www/html/drupcom/modules/system/system.tar.inc on line 718

So this is issue with Zlib.
I've tried to solve it using
these instructions, but no luck. Then I found that it is known bug.


Add textfield as option for checkbox 'other' entry I am creating a form using the Drupal 6 Form API and I have a set of checkboxes. One of the options is "Other."

Is there a way to have one of these options be a fillable field? How would I define that in the options array.

Thinking something like:

[] Option A
[] Option B
[] Other ___________

Any ideas?

The easiest way is to add the Select or Other module.

It lets you define these using the Form API, CCK, Webform and some others.


Drupal node title as URL permalinks How can I use Drupal node title as URL Permalink just like wordpress %postname% ?

or even change the "node" from example.com/node/id ? (Drupal 6)

Enable module Path. it is provided in Drupal core.
If you want automatically generate url aliases for new nodes - install Pathauto

  The Pathauto module automatically generates URL/path aliases for various kinds of content (nodes, taxonomy terms, users) without requiring the user to manually specify the path alias. This allows you to have URL aliases like /category/my-node-title instead of /node/123. The aliases are based upon a "pattern" system that uses tokens which the administrator can change.


Is there a way to trigger an image crop dynamically? I have a Flag setup for an image content type which allows users to Flag an image that they want to be their avatar/user picture. I also have a View which displays this flagged image.

When a user clicks this Flag I would like to be able to trigger a crop (where the user is able to select the cropping area manually) so that a copy of the image can be made and referenced in a separate avatar gallery, without effecting the original image which will stay in it's gallery uncropped. There are several cropping solutions for Drupal 7 however is there a way that cropping can be triggered dynamically as in my example, perhaps via Rules or another way?

A module that you want to start looking at is Imagefield Crop. Details from project page:

  When the user uploads an image it is presented inside a cropping area. A cropping box is shown inside, and the user can resize and move it. Upon clicking "preview" or "submit", the image is cropped and the result is saved instead of the original image.

  Features
  - Seamless, intuitive cropping, almost like using a desktop photo editing app
  - All major browsers supported
  - Dynamic preview - you see how your crop will look like, in real time!
  - Original image is saved for recropping.
  - No matter what resolution the cropping area is, the original image is used for cropping (for highest quality)
  - The sizes of the cropping area, cropping box and resulting image can be controlled by the administrator

The problem with using this module however is that it only works with the imagefield module and the user picture.

If you already have a bunch of users that uploaded avatars using Drupal's core functionality then it would be best to rip the ImageField Crop module apart and see how it can be integrated into Drupal's user avatars.

If you have yet to have any users upload avatars then you can follow these steps....

Create a user field called "Pic" and use the "Image with cropping" widget on it.
When the user flags the image, you can redirect to the user edit page while passing the fid of the flagged image.
After that you can use hook_form_alter to chuck in the fid, uri and fileurl from the passed fid as the '#default_value' of the newly created "Pic" field from step 1.

The annoying thing about this solution is that you will have to modify user-picture.tpl.php to use your custom created field over the default avatar picture.


Translation of months and days in Calendar Views Module The Views Calendar template displays months and days, i.e. June, July, Monday, Tuesday,  etc.

When someone changes from english to french, how can I tell it to display the months in a different language?

You need to translate the strings. Go to Administration » Configuration » Regional and language » Translate interface, in the menu.

Then search for !month-name and !day-abbreviation and translate the strings to your language.

You can also download translations for the whole module on https://localize.drupal.org/translate/languages/fr

You can also use the Localization update module. From the UI of the module you can download and keep track of new translations for your downloaded modules.


What is the database relationship between node_type and taxonomy_vocabulary tables? I have 3 content types. I have 3 vocabularies - one for each content type.

Recently I have created a script to save nodes programatically based on batch files clients send me. I am very happy with it, and it works fine.

However, I currently have to manually manage a separate file for a huge multidimensional array. Here is an excerpt from the file.

$query['baby_clothes']['category']['id'][] = 1;
$query['baby_clothes']['category']['id'][] = 2;
$query['baby_clothes']['category']['id'][] = 3;
$query['baby_clothes']['category']['id'][] = 4;
$query['feeding']['category']['id'][] = 26;
$query['feeding']['category']['id'][] = 28;

The first dimension represents the content type and the others the id. There is one entry per unique taxonomy term id in the array. Basically I loop through the IDs; extract the content type from key [0]; save accordingly.

As the taxonomy grows and changes this becomes very inefficient to manage, and i would like to create these arrays dynamically, but I am having trouble understanding the database relationships to create this part of the code.

Basically it would work like this:
"Get an array of content types. For each content type get the taxonomy IDs for the one vocabulary that is associated with the content type. Dynamically create the array."

Or, how about this? Would this be easier?
"Get a list of taxonomy IDs. Get the content type with which this term is accociated. Now I have my content type and my id - save node accordingly."

I can see the node_type and taxonomy_vocabulary in the mysql database, but I am not sure how they relate to each other, or how to relate them so I get the desired result.  I would prefer option two, but any direction is appreciated as well as are alternate suggestions. Pseudocode is fine. Thanks!

Not to discourage database deep-diving, but if you're bootstrapped into the Drupal system with your system (i.e. programmatically creating nodes), then you don't have to necessarily understand how the DB works to get this working. Just use the functions in the node and taxonomy API to generate your array.

Specifically, lets say you wanted to try for option #1. You could use

node_type_get_types()

to pull a list of all of your content types, and then iterate through that to generate a list of taxonomy terms for each vocabulary. Here is a function I've used before to that effect, from VicTheme.com

/**
 * Helper function return all the taxonomy terms of a given node type
 * @param $type
 * The array of machine name of the content type that the function should look for taxonomy terms
 * the array format should be : array('machine_name');
 * @return
 *   An array of taxonomy terms containing tid => human name.
 */
function vt_commerce_api_get_vocabulary($type = array()) {
  // break if there are no types specified
  if (empty($type) || !is_array($type)) {
    return FALSE;
  }

  $output = array();
  foreach (field_info_fields() as $field) {
    if ($field['type'] == 'taxonomy_term_reference' && is_array($field['bundles']['node'])) {
      foreach ($field['bundles']['node'] as $content_type) {
        if (in_array($content_type, $type)) {
          foreach ($field['settings']['allowed_values'] as $value) {
             $output[$value['vocabulary']] = $value['vocabulary'];
          }
        }
      }
    }
  }

  return $output;
}


Showing content on pages without taxonomy I have setup a drupal site so that a block is showing specific content on pages with the same taxonomy term as the block.

Now I am trying to get some sort of default content for pages without taxonomy terms.
I want the block to show all the content without taxonomy terms attached on pages without any terms attached (such as the front page and some sub pages the client makes himself).

The block in question is a slider and it would be silly if the client would see the slider disappear on pages he creates due to taxonomy.

How can I achieve this?

This should be fairly straight forward

Create a new view that displays all the content without a taxonomy term,
In the existing block view look under the advanced settings for no results behaviour and click add. In here you can add a view to display if there are no results so simple select your view that you created in step 1.


How to get html source code from body field in node type edit form? In node type = "article", I have field of type body.

In my .module file, I want to get its raw source code with actual html classes too. But all I get is:

$body = $node->get('field_all_body')->value;
print_r($body);die;

I want the value should contain div class too. How it can be achieved?
My actual requirement is:
I want to populate one field value on behalf of the class exists in 'field_all_body' field.
Foe example, I select some text in text-editor, and mark it bold, then that particular text should get cloned in another field too.

The basic text format filters out all but a few HTML tags.  You want to select the Full HTML text format to keep your divs and classes.


Block wrapping DIV disable with theme hook? I've managed to suppress the wrapping markup for a few blocks using

block--block--1.tpl.php
region--banner.tpl.php

but now it's getting messy as I have several blocks which require no additional wrpaping markup so I would ideally like to do this in a theme function with a switch case...but can't find any example that works...

function front_preprocess_block(&$vars, $hook) {

$to_delete = array('block-block-4');

//if(in_array($vars['block']->delta , $to_delete)) {
//  $vars['template_files'][0] = 'block-empty';
//}

print_r($vars);

}

I need to remove wrppaing DIV's for about 4 blocks onlys...ideas???

You can specify an additional variable in hook_preprocess_block() and check for that variable in block.tpl.php file, example:

function front_preprocess_block(&$vars, $hook) {
  //dpm($vars);
  $vars['must_be_removed'] = FALSE;
  if(/* CONDITION e.g. $vars['elements']['#block']->delta == 'MY_BLOCK_DELTA' */) {
    $vars['must_be_removed'] = TRUE;
  }
}

and block.tpl.php file;

<?php if($must_be_removed): ?>
  <?php print $content ?>
<?php else: ?>
<div id="<?php print $block_html_id; ?>" class="<?php print $classes; ?>"<?php print $attributes; ?>>

  <?php print render($title_prefix); ?>
<?php if ($block->subject): ?>
  <h2<?php print $title_attributes; ?>><?php print $block->subject ?>

<?php endif;?>
  <?php print render($title_suffix); ?>

  <div class="content"<?php print $content_attributes; ?>>
    <?php print $content ?>

<?php endif; ?>


Selecting an SVG as an Image Field value I have a Content Type, News, with an Image Field, News Icon.

When the field settings are viewed at /admin/structure/types/manage/news/fields/node.news.field_news_icon

I have supplied SVG as one of the allowed types.  I have also tried allowing only SVG.

We also have IMCE in use so I have SVG set up in the IMCE config like so at /admin/config/media/imce  I have also tried using a list separated by spaces including SVG.

The Widget settings for the field at /admin/structure/types/manage/news/form-display allow for the IMCE manager to be enabled.  I have tried disabling but it did not resolve the issue.

The widget displays and lists allowed types but no SVG.

IMCE allows upload of SVGs but when selecting one as the news_icon I get

The normal (non-IMCE) file browser gives the following when an SVG is selected for upload:

Is there a deeper setting I am missing to get SVG included in the list of allowed extensions for use as an Image Field value?

AFAIK the jpg/png/gif limitation is hardcoded in the image field, you can't solve this (only) with configuration.

SVG Image allows .svg files in core's image field. You can use the standard image formatter with it (or better: you must use the standard image formatter, it will not work with Focal Point or similar)

SVG formatter uses the file field and provides an SVG formatter for the file field.

Both also work with media entities, but I've not tested them with IMCE yet.


Can a Webform display the last submitted version of instead of creating a new submission I have a web form that is embedded into a field on a content type and wondering if the form has been already submitted can you display the webform/manage/webform_name/submission/webforn_numer/edit form instead?

Yes!!! Just go to Webform: Submissions: Settings and check off 'Limit total to one submission' per user or per submission.


Drush site install without dropping/recreating database I am from Ukraine, so sorry for my bad English...
Please help me to fix a problem. I'm trying to install Drupal with Drush on shared hosting.

I use the command drush site-install. On localhost everything worked correctly, but on the  hosting I get an error: Access denied for user 'bigferwn_t'@'localhost' to database 'bigferwn_t'.

Command string is 100% correct. The problem lies with permissions. When Drush runs the site-install command it DROPs the RECREATEs the db. So if the db user does not have that permission (like in many hosting provider) we get the error access denied.

So I created a db in hosting account manually and want to install drupal using the database that I just created. I don't want to drop and recreate this db. I simply want use the existing database.

There are issues discussing the same problem https://www.drupal.org/node/1105514.

In the site-install command there is no option to "NOT CREATE OR DROP DB" or if there is I can't find it.

I tried to use the patch from https://www.drupal.org/files/issues/drush-script-options.patch which was proposed in the issue above, but it is old and for a different version of drush.

Drush doesn't and likely isn't going to support this workflow based on developer comments in these pull requests:

https://github.com/drush-ops/drush/issues/134

https://github.com/drush-ops/drush/pull/353

Your remaining option is to install using the Drupal installer script.


Information added by Drupal.org on Distribution Hi am trying to make a Drupal 8 Distribution, all is well, but when I download it from drupal.org I get on all modules this information.

I would like that all contrib modules to have their default information. What do I need to setup in order to remove the profile package from contrib modules?

In the image below Drupal.org comment out the module information and added profile information. I do not want to add the profile information on to the contrib modules.

# core: '8.x'
# Information added by Drupal.org packaging script on 2017-08-15
# version: '8.x-1.0'
# core: '8.x'
# project: 'ace_editor'
# datestamp: 1502816349

# Information added by Drupal.org packaging script on 2018-01-18
version: '8.x-1.x-dev'
core: '8.x'
project: 'myprofile'
datestamp: 1516303995

So it's not confusing I don't want to remove the information from Drupal.org. Somehow Drupal.org is packaging the modules as part of the profile, and the result is the image below

I want to be able to see it normally like the image below

Whoever is getting the same error it is probably you got some patches and themes that are not from Drupal.org

The 2 links below helped me see what my problem was:

https://www.drupal.org/docs/develop/packaging-a-distribution/how-to-package-a-distribution-on-drupalorg

https://www.drupal.org/docs/develop/packaging-a-distribution/drupalorg-distribution-packaging-requirements


How do I render a form? What is the alternative to drupal_get_form('user_login'). in Drupal 8?

I am using the following code in theme_name.theme, but it doesn't work.

// Include namespace for userLoginForm.
use \Drupal\Core\core\modules\user\src\Form;

function MYTHEMENAME_preprocess_page(&$variables) {
  $form = UserLoginForm::create();
}

drupal_get_form() has been replaced by the form builder service, e.g.:

$form = \Drupal::formBuilder()->getForm(\Drupal\user\Form\UserLoginForm::class);

See the Change Record for more details.

Actually, don't - that change record is incorrect. It'll tell you to pass the form ID, when in fact you need to pass the class string.


Global view footer not replacing tokens I am having a problem with token replacement in a views footer. I added a "Global: Unfiltered text" footer, and checked "Use replacement patterns", and added [title]. However, it shows up as the literal string [title] on the view, not the title from the first row.

Here's the footer I've created:

And here's the view preview:

And here's the actual view, where we should see "Sample Article" instead of "[title]". Note that "Sample Article" is the title of an article node, so there is one record showing in this view:

I can't tell what I've done wrong. FWIW, I put an export of the view here.

How can I get the tokens to render properly in my view footer?

I can't tell from the examples provided ... but if a View has no results from the database, then tokens are not replaced.


How do I block access to forum landing page, forum containers and forum posts? I need only members to be able to access the forums. I have researched this to death and from what I can tell, I need to have at least three modules to achieve this.

Path access to block access to the core forum landing page at /forum (as it is not a node, entity nor view)
Forum Access module to block the top level forum containers
And Taxonomy Access or something like Node View Permissions to block access to the forum topics posts themselves.

Are you kidding me??? I need three permission modules just to stop anonymous users from looking and using the forums. Am I missing something here?

To control access top level forum containers, forum topics and forum content, you should use the forum_access module (you mention it for blocking containers, but it can also be used to block access to forum topics and content).

However, after installing this and denying the anonymous user role access to forums, this user still has access to the forum landing page (he or she will see a message that it is necessary to log in to access forums).

If you also need to block access to the core forum landing page, you need to add a small custom module that uses hook_menu_alter to set up a custom callback function to check the user id.  Since the anonymous user is assigned uid 0, you can use this to only grant users with a uid that is not 0 access to this menu item.

Here is all that is needed, stick this in noforumforanon.module:

/**
 * Implements hook_menu_alter.
 * Check access for forum menu item.
 */
function noforumforanon_menu_alter(&$items) {
  $items['forum']['access callback'] = '_accesscheck';
}

/**
 * Callback to disallow access for anonymous users.
 */
function _accesscheck(){
  global $user;
  return $user->uid;
}

And this in  noforumforanon.info:

name = No Forum for Anonymous
description = Blocks anonymous from accessing the forum landing page.
package = Access control
core = 7.x

Put both files in a directory named noforumforanon below site/all/modules, enable and refresh cache, and the landing page shall be gone for anonymous.


Can't access my website I can't access my website. I guess it has been hacked. Some drupaldev user is already been created and is in admin list. I have blocked that user multiple times, but it reappears again and again in my admin panel list.
My site has also faced spamming, which i stopped by disabling registration module. But i believe its too late now.

How can i prevent letting this user access my website? What have i missed in my security constraints? Please help.

Drupal Version : 7.17

What have i missed in my security constraints?

I looks like you're running an outdated version of Drupal (ver. 7.17) with many severe security issues including the one known as "Drupageddon" (fixed in ver. 7.32).

First, you must start reading up on the Drupal Security advisories, in particular SA-CORE-2014-005 - Drupal core - SQL injection, PSA-2014-003 and FAQ on SA-CORE-2014-005 - they will tell you what you've missed regarding Drupageddon. This flowchart is a great resource.

To get back the control over your site, you should simply delete it, and start recreating it from scratch on a different server, since the attacker may have a root kit on your present server.  Change the password of the db-user that Drupal uses, and the passwords of all privileged accounts. If you want to keep your content, roll it back from a backup created before Oct. 15 (you have backups, don't you?).

If you don't have backups, there are some tools (including a Drush command named Drupalgeddon) that may be use for forensics and part clean-up of an compromised site.  I do not recommend that you use these tools, as there is no guarantee that they'll able to find all infected areas on your site and web server. But they're the last resort, if scrapping the site and starting over is not an option.

You should also start reading up an all Drupal SAs.  Or even better, subscribe to them: Log in on Drupal.org, go to your user profile page and subscribe to the Drupal security newsletter on the Edit » My newsletters tab.

Contributed modules frequently have security flaws.  These are eventually fixed, but the fix also tells all the bad guys how to exploit unfixed sites.  That means that to keep your site secure, you must make sure you install security updates in a timely manner.  That's why subscribing to the security newsletter is so important.

Custom modules made by inexperienced programmers is a huge risk.  If you use custom modules, make sure you have their code reviewed by someone experienced in security.


Saving a data to two different nodes with same node id? I am having this problem , i want to save the same data into two tables with the same node id. I want to use both the tables on two different places because data is changing in the first table and i want to keep a track to the older data in my second table.

$node->field_call_response['und'][0]['tid'] = $call_response;
$node_new->field_log_response['und'][0]['tid'] = $call_response;

As Paul commented, there is already a system to keep track of changes. You can enable node revisioning through the UI by going to Config > Structure > Content types > [Content Type] > Edit and select the Create new revision option under Publishing options. Now every on-site node edit will be registered as a revision and the previous values are logged in the Revisions tab (next to edit).

If you need to programmatically create a new revision, you can do it as follows:

$node = node_load($nid);

$node->field_call_response['und'][0]['tid'] = $call_response;

$node->revision = 1; // Save new revision
$node->log = "Explain what you changed";
node_save($node);


ImageFlow module doesn't find its library in Drupal 7 I have downloaded and installed ImageFlow module and also the library library from here and placed its content in \sites\all\libraries . this is screenshot:

but when I'm trying to enable ImageFlow it reports this error:

You need to install the Imageflow library. The js file should be readable at sites/*/libraries/imageflow/imageflow.js. You can find the library at http://finnrudolph.de/ImageFlow/Download. (Currently using Imageflow library Library required for Imageflow)

imageflow.js is in the directory. I have tested both uppercase and and lowercase for ImageFlow directory but it doesn't work. why it doesn't find the ImageFlow directiry in /libraries?

Try using the dev version of the module. I was having the same problem, found this issue: https://drupal.org/node/2042787
Seems the maintainer fixed it in dev but did not in the point release.

If you find documentation on getting this to work after installation, please link!


Keeping old site live while testing new site? I'm helping my university department upgrade their Drupal website from 6 to 7 (university doesn't support 8 yet).  So far, I've been able to install and test the new site on my local machine, but now it's time to move it to the actual host so that users (mainly the department secretary) can start to populate pages with content.  Can I have a Drupal 7 site live on a subdomain like test.dept.university.edu while keeping the Drupal 6 version live on dept.university.edu?

Apologies if this is a naive question - I've read a lot about creating clones of existing sites for testing, but this assumes that one is upgrading within the same Drupal version.

In short, yes you can, but this has a little to do with drupal.
To clone a Drupal site is nothing more than copying the drupal root directory (codebase) and taking a database dump. It's quite easy then to transfer all these on any other environment and with some settings.php tweaking you will have an up and running clone of your site. The hard part is to migrate from D6 to D7, but you have already done this as far as I understand.

I would propose you to setup a staging environment by using a clone created from your local environment and start adding/editing content there. It dosen't really matter under which hostname that (staging) will be, it may well be the test.dept.university.edu  because you can make the production's url (dept.university.edu) to point back (redirect) to the staging machine when all things are in place and the time to go live has come.

This is a rough idea but I guess that the meaning is quite clear.

Let the mods to decide if this question should be close or not.


How to force a selection in one field if another webform field is a certain value I know it is quite simple with Conditionals to show and hide fields based on another fields value in a Webform -- is it possible to change values of fields based on another field's value?

For example, if someone selected a certain membership type in a field at the top, could a field lower down automatically have certain selections disabled automatically (or a single selection selected, and the entire second field disabled)?

This is a bit of an oversimplified example, but:

  Membership type (select) > Single person

  How many t-shirts would you like (select)? [Preselect "One" and disable the field from edits]

and

  Membership type (select) > Two people

  How many t-shirts would you like (select)? [Option to select "One" or "Two"]

You could use normal conditional fields for that. Simply create two "How many t-shirts" fields, one with only one enabled option, second with both available. Then, make them visible depending on value in "Membership type". It is possible since Webform version 7.x-4.0-alpha2, and earlier using this module.

Sure, this will create two separate entries in results, and only one filled, but if your traffic is low, it will be easy to read. And if it's high, you can aggregate easily in your warehouse handling software. Or in spreadsheet of your choice, after export.


How to add markup inside a form radio button div Currently I have a form displaying radio buttons and I added some markup to it by attaching #suffix to the form element. However, I found that this didn't do exactly what I needed. This created the following code structure:

     ...

            <input type='radio'></input>

            <input type='radio'></input>

Markup goes here

I'm trying to figure out how to add markup inside the 'radio-button' div, right after the label tag. How can I do this? If there is no Drupal way of doing it, I can add it with javascript, but that's not ideal.

EDIT:
I have chosen to try using a custom template for this form element, but its not working. Here is my code:

'my_module_is_member_radios' => array(
  'variables' => array(
    'description' => array(),
  ),
   'template' => 'templates/my_module_is_member_radios',
),

I was able to follow @Alfred's advice above and used the #theme element to make this work.
I added this to my module theme hook:

'my_module_is_member_radios' => array(
  'render element' => 'form',
  'template' => 'templates/my_module_is_member_radios',
),

and in the template used this:

$armedForcedInfo = "some markup";
$civilianInfo = "some more markup"

$variables['form'][0]['#suffix'] = $armedForcedInfo;
$variables['form'][1]['#suffix'] = $civilianInfo;
print drupal_render($variables['form'][0]);
print drupal_render($variables['form'][1]);


How can i make a Slide Show for my Home Page with the following requirements How can I make a Slide Show for my Home Page with the following requirements:

The image would link to any content
The caption would be different for all images of the slide show
The slide show would be responsive
The images can be added, deleted from the CMS itself by the client/admin
Navigation controllers
Place a link "Sign Up" on top of the slide show which takes the user to the  sign up page

I tried with Views Nivo slider but it has open issues regarding rewrite results. Are there any other modules? Views slideshow is one but I am not able to configure it as per my exact requirement.

Views slideshow has solutions to be responsive, see:
http://drupal.org/node/1510526

You can also embed a custom slideshow navigation using views and a global counter in the view, using Tokens you can replace the counter text with whatever you want. An example of this can be found here:
http://blog.urbaninsight.com/2012/01/03/building-slideshows-with-navigation-based-views

All of your criteria are met by Views Slideshow I believe, you just have to get crazy with CSS. I have made the following slideshow with Views Slideshow using the navigation tutorial above, Views, Views Slideshow and Nodequeue.

example view slideshow config

default rendering of ViewsSlideshow in Admin area, an un-themed slideshow

Final themed slideshow with custom navigation

In my case I overlay the navigation into the view, I had to use jQuery to achieve some of the dimensions at runtime and CSS3 stuff for opacity of my overlay div.


How can I filter for the UID of the node on a view? I want to have a relationship between the the author of the node ($uid) and the view results, seems straightforward but I'm not getting it. On the view, I've added the relationship to content:author and then used a contextual filter for the nid. Since this is a block view, I've provided the default argument from the url. It seems like I've done the very same thing before, but I'm going crazy with this case. I have noticed this time that the contextual filter doesn't ask whether to use a relationship, which seems odd.

Hope this will help you, To display all content created by author who created the current node loaded, No need to make any relationship, Just add a Configure contextual filter: Content: Author uid check the bellow options,


How do I include a PHP library? In Drupal 7, there are hook_library() and drupal_add_library() that can be used to manage JS and CSS libraries. I am looking for how to include the PHPExel library in my distribution.

How can I do it?

hook_library() is thought only for Javascript and CSS files; for PHP libraries, you should consider the Library API module.

  This module introduces a common repository for libraries in sites/all/libraries resp. sites//libraries for contributed modules.

  External libraries

  Denotes libraries ("plugins") that are neither shipped nor packaged with a project on drupal.org. We do not want to host third-party libraries on drupal.org for a multitude of reasons, starting with licensing, proceeding to different release cycles, and not necessarily ending with fatal errors due to conflicts of having the same library installed in multiple versions.
  Drupal 7 only has built-in support for non-external libraries via hook_library(). But it is only suitable for drupal.org projects that bundle their own library; i.e., the module author is the creator and vendor of the library. Libraries API should be used for externally developed and distributed libraries. A simple example would be a third-party jQuery plugin.

The Library API module implements an API that can be used from third-party modules to load libraries installed on a Drupal site; the pro of using Library API is that it handles dependencies between libraries, and versioning.


How do I return a number in render arrays? I am building a module in Drupal 8. I am doing a query in database and I return the number of users and the number of nodes. I write of screen this numbers without errors, but I cannot write them in a block.

This is the code I am using.

Module file

/**
 * Implementa hook_theme ()
*/
function my_module_theme() {
  return array(
    'my_module_test' => array(
      'template' => 'test',
      'users' => NULL,
      'questions' => NULL,
    ),
  );
}

The class implementing the block

  namespace Drupal\my_module\Plugin\Block;
  use Drupal\minka_qa_core\FormatUtils;

  use Drupal\Core\Block\BlockBase;

  /**
   * Provides a 'Bloco' block.
   *
   * @Block(
   *  id = "bloco",
   *  admin_label = @Translation("Bloco"),
   * )
   */
   class Bloco extends BlockBase {

     /**
      * {@inheritdoc}
      */
     public function build() {
       //$count = $this->countTest();
       $example = $this->test();
       $example2 = $this->test2();

       print_r($example);
       printf('\n');
       print_r($example2);
       //$questions = $this->countTest2();
       /*$build = [];
       $build['bloco']['#theme'] = 'my_module_test';
       $build['bloco']['#plaint_text'] = 'Questões';
       $build['bloco']['#users'] = $count;*/
       return [
         '#theme' => 'my_module_test',
         '#plain_text' => 'Questões',
         '#users' => $example,
         '#questions' => $example2,
       ];
   }

   public function test() {
     $query = \Drupal::entityQuery('node')
      ->condition('status', 1)
      ->condition('type', 'questoes');
     $nids = $query->count()->execute();

     return FormatUtils::formatNumber($nids);
   }

   public function test2(){
     $query = \Drupal::entityQuery('user')
      ->condition('status', 1);
     $nids = $query->count()->execute();

     return FormatUtils::formatNumber($nids);
   }

}

The template file

Test twig template!

user: {{ users }}

Why isn't my code working?

There is a mismatch in hook_theme(), template is "test", elsewhere "my_module_test". And the return array has three levels, with the keys variables and template in the second level and the twig parameters in the third:

  return [
    'loremipsum' => [
      'variables' => [
        'source_text' => NULL,
      ],
      'template' => 'loremipsum',
    ],
  ];


Add items to router but not links According to the last paragraph:

https://api.drupal.org/api/drupal/includes%21menu.inc/group/menu/7

  Everything described so far is stored in the menu_router table. The
  menu_links table holds the visible menu links. By default these are
  derived from the same hook_menu definitions, however you are free to
  add more with menu_link_save()

I need to do the reverse of that, which API do I use? I need to add a record to the routing table but not couple that to an visible menu link...

The only way I can think (short of manually INSERT'ing) is to initialize a hook_menu call somehow with the various paths I want and call menu_rebuild()??? This appears to be how Panels does it...

Suggestions, opinions, etc???

EDIT | Why isn't this code working...resulting in "The requested page "/test" could not be found."

function test() {
  return 'Do something';
}

function pagegrid_menu_hook() {
  $items = array();

  $items['test'] = array(
    'type' => MENU_CALLBACK,

    'title' => 'TEST',

    'page callback' => 'test',
    'access arguments' => array('access content')
  );

  return $items;
}

Menu links are only created by default because the default type for a router item is MENU_NORMAL_ITEM:

  Menu type -- A "normal" menu item that's shown in menu and breadcrumbs.

What you need is a MENU_CALLBACK:

  Menu type -- A hidden, internal callback, typically used for API calls.

e.g.

$items['example/feed'] = array(
  'title' => 'Example RSS feed',
  'page callback' => 'example_feed',
  'access arguments' => array('access content'),
  'type' => MENU_CALLBACK,
);

That will create you an accessible path with no menu links, unless of course you add them manually through code or the UI.


How to implement search on multiple fields limited to one content type in drupal 7 I've created a new content type which has several fields (some of them are custom fields I created myself). Now I need to implement a search function on each of those fields.

This means that if I have these fields:

VideoCV (video field)
Occupation (text field)
Driving licence (select lists)
Region of birth (taxonomy term)

I need a search module with those four fields, so that if you search for occupation "engineer" it searches only data inserted in that specific field.

What do I need to do? What additional modules should I install? What should i do with my custom fields?

I'm not a D7 expert but I you can try with an EntityFieldQuery like this:

$query = new EntityFieldQuery();
$entities = $query->entityCondition('entity_type', 'node')
                ->entityCondition('bundle', 'YOUR_CONTENT_TYPE_NAME')
                ->propertyCondition('status', 1)
                ->fieldCondition('YOUR_FIELD_NAME', 'value', $searchterm)
                // other conditions...
                ->propertyOrderBy('title')
                ->execute();
$nodes = entity_load('node', array_keys($entities['node']));


How do I get a list of nodes that have a reference to a given user? I can get a node's referenced users like so:

$users = $node->get('field_allowed_editors')->getValue();

But how can I get a reverse list? Getting all the nodes that have a certain user referenced?

You can use an entity query:

$nids = \Drupal::entityQuery('node')
  ->condition('type', 'article')
  ->condition('field_allowed_editors', $userid)
  ->execute();

This will result in an array with all node id's that match the conditions.


Lost Social Connection Icons after uploading custom images I created a subtheme for Commerce Kickstart / Omega. As part of the refresh, I want to use the existing "Connect with Us" block, but replace the existing icons with customized images (theme consistent colors).

I uploaded replacement files to sites/all/SUBTHEME/images, using the same file name and type as in the original theme:

icon_facebook.png
icon_twitter.png

Saved / refreshed: Icons disappeared from the block. If I was uploading to the wrong directory, I feel like it would continue to show the original yellow icons, but the icons no longer show at all.

Here's the code from the css file:

  #block-menu-menu-social-connection .content ul.menu li span,
  #block-menu-menu-social-connection .content ul.menu li a {
    color: #eeeeee; }
  #block-menu-menu-social-connection .content ul.menu li a.facebook {
    background: url("../images/icon_facebook.png") 2% 50% no-repeat;
    /* LTR */ }
  #block-menu-menu-social-connection .content ul.menu li a.twitter {
    background: url("../images/icon_twitter.png") 2% 50% no-repeat;
    /* LTR */ }
  #block-menu-menu-social-connection .content ul.menu li a.instagram {
    background: url("../images/icon_instagram.png") 2% 50% no-repeat;
    /* LTR */ }

After troubleshooting with @nosssweat, it turns out this is an issue with Adobe PS saving empty PNG files. Surprise!

To fix, I switched to 24-bit PNG and was able to save the web-optimized format correctly. All issues fixed here.


Views 3 and HTML5 - how to override output for markup? I have a view that I've created that selects blog posts based on a specific taxonomy term, creating a sort of "Featured Posts" view that I've embedded on the front page of my site. The issue I keep running into is trying to output the view so that each post is semantically marked up using some of the new HTML. I've tried the built-in "Rewrite this field's output", but it ignores the tags I use (ie, article, header, footer) and wraps everything in divs even when I deselect the placeholder tags.

Should I create a overriding views--view_name.tpl.php to rewrite the output of each post as it appears in the view, or do I need to use preprocess hooks in the template.php to affect the output?

I should state that I have basic experience with writing PHP and preprocess hooks, but I can any resources I need to move me down the linke if I'm pointed in the right direction.

You'll notice that in your view under the "Style Settings" block there is a link for Theme: Information. It will expose all the theme files that are called for your view. You can use generic to very detailed theme files that will only be use for your views display.

The first file name in Display output is views-view.tpl.php. That will apply to all views and displays. The next one in the list is views-view--[view name].tpl.php. It will only apply to your view. It keeps drilling down until it gets as specific as possible. views-view--[view name]--default.tpl.php is the last one in the list and only applies to the default display of the view. Clicking the Display output: link will expose the template code that views uses. Simply copy and create a new template file with one of the suggested in the list. It's usually best to be as specific as possible. The template file can go anywhere in your theme and views will pick it up as long as you rescan template files in the theming information and save the view. There are view templates, row templates, field templates and field specific templates.

Once you learn how to manipulate view template files it will really open up your design possibilities.


What is required to get a custom module to appear in uninstall list? Solution: Ayesh K provides the correct answer below.

What is required to get a custom module to appear in uninstall list?  I thought all you had to do was specify a database schema in hook_schema(), but I've done so and my module does not appear in the uninstall list.  Currently my module consists of the following code in the .install file:

<?php

/**
 * Table schema definition for the Events Sponsors module.
 */
function event_sponsors_schema() {
    $schema['event_sponsors_sponsors'] = array(
        'description' => 'A collection of event sponsors.',
        'fields' => array(
            'id' => array(
                'type' => 'serial',
                'not null' => TRUE,
                'unsigned' => TRUE,
                'description' => "Unique ID for the sponsor.",
            ),
            'name' => array(
                'type' => 'varchar',
                'length' => '255',
                'not null' => TRUE,
                'description' => 'The name of the sponsor.',
            ),
        ),
        'primary key' => array('id'),
        'unique keys' => array(
            'id' => array('id'),
        ),
    );

    $schema['event_sponsors_sponsor_relations'] = array(
        'description' => 'Maintains sponsor and node relations.',
        'fields' => array(
            'sid' => array(
                'type' => 'int',
                'not null' => TRUE,
                'unsigned' => TRUE,
                'description' => 'The sponsor ID, as can be found in the sponsors table.',
            ),
            'nid' => array(
                'type' => 'int',
                'not null' => TRUE,
                'unsigned' => TRUE,
                'description' => 'The node ID as can be found in the node table.',
            ),
            'ordinal' => array(
                'type' => 'int',
                'not null' => TRUE,
                'unsigned' => TRUE,
                'description' => 'The order this sponsor appears alongside the node.',
            ),
        ),
        'primary keys' => array('sid','nid'),
        'unique keys' => array(
            'sid' => array('sid'),
            'nid' => array('nid'),
        ),
    );

    return $schema;
}

Any insight is appreciated.

For Drupal 6, you needed to install/uninstall schema using hook_install and hook_uninstall.

This is not necessary for Drupal 7.

Module will appear in uninstall list if both of these conditions are met:

module implements hook_schema OR hook_uninstall in its .install file.
module was enabled once and now is in disabled status.

If the only purpose of hook_uninstall is to uninstall the schema, you do not need a hook_uninstall function. For variable_del(), etc: you need.
If you have any of these and module has data in the site already, you will see the uninstall check box.


what is the use of Backup Folder? I'm going to migrate my site to another server. so, i need to backup my database if i dump my database using mysqldump command into backup folder. does database manage it by updating the changes done into database to the sql file.

No, the database does not update your dump-file afterwards. You should prepare your new site with a database dump.

Then when you are ready to move the site finally you should put your original site in maintenance mode, and dump and import your database with the latest content. In this way you ensure that you will get the most recent content from your old live site.


Why aren't the titles of my items in a new product type not displaying at check out? - Commerce I am building a store based on Commerce Kickstart.  I am using one of the original product types and two new product types that I created by essentially copying the field and display settings in the content type and product variations settings.  After a lot of fiddling around I have everything displaying properly, except in a couple of places in the check out process.

1) In the cart ( mysite.com/cart# ) the line items that I created display the sku of the item but not a "view product" link.  Where can I change this?

2) In the review order page ( mysite.com/checkout/ordernumber/review ) the line items of the product type that I created don't display the item title, while the item type that was there originally does.  Where can I change this?

It's a bit of a gotcha, but I suspect under user permissions, you may need to check the "View products of [type] type" permission for anonymous / authenticated users.


Expose (other) user's role to anonymous using views Setup

On my site I have created two new, different roles (say role A and B). New users get assigned one of these roles.

Using Views I have generated a user listing, i.e. a view showing all users having either of role A or B. This overview listing shows some user information, including the role that the respective user in the listing has. The role is pulled in using a field making use of user relationship: (Owner: User) User relationship: Roles

The anonymous user also has View user information permission.

Issue

The user listing view works fine, if the user viewing it is authenticated (i.e. logged in).

However, if the user is anonymous (i.e. not logged in), the role does not get displayed in the user listing view.

Desired outcome

I would like all users, including the anonymous user, to be able to view the roles in the user listing.

Question(s)

How can this be achieved using Views?
If this can not be achieved using Views, then how?

Ok, I figured it out with help from @Dropa. What I had to do was to build my view in a different way than I initially had it set up.

Initially I had my view built as showing fields from profile, and then I pulled in the user information through a relationship.

What I had to do was to switch it around and create the view showing fields from user. This allowed me to display the user information, including the role info that I am after.
All other desired information (e.g. other information from the profile module) is then pulled in through a relationship.


Date display field drupal I have created two content types A and B. I have a Date field in A which is referred in B. But in B I want to display the Date field separately i.e 3 different select list for month, year and day.

Using the Date API module (part of the Date module), you can do something like this...

<?php
$form['payment_expirationDate'] = array(
    '#type' => 'date_select',
    '#title' => t('Expiration Date:'),
    '#date_format' => 'm', OR  '#date_format' => 'y',
    '#default_value' => $expirationDate,
    '#date_year_range' => '-1:+10',
    '#required' => TRUE,
    '#date_label_position' => 'within'
 );
?>

The date_select type will give you select box form elements for your field. And the #date_format array key allows you to use a PHP date format string to control what select boxes appear and what goes inside them.

Reference


Views: show only one node per select box value I created a Block showing the latest 3 articles ("pets") as teaser (not using fields). The content type has a field type which can be dog, cat or other.

Now i want to show only one of each type: one dog, one cat and one other. I don't have any idea how i can do that... I have some filter criteria (content-type=pet, available=yes, public=yes) and sort criteria (content:date_arrived desc) and limited to 3 items.

Thanks for any help / hint!

I'm using drupal 7 and the newest views-module.

I thing it's difficult to make just with the views UI (the aggregation will not work)
If you don't want the solution of Anil Sagar, i have another solution with some theming.

Go to format => setting : In Grouping field Nr.1 select your field type (left)
Now your result will by group by type (dog, cat and others) You can see an extrat of the output. (right)

Go to Advanced setting => Other => Theme information

Copy / Paste views-view-list.tpl.php in your new template and make some modification

 <?php print $wrapper_prefix; ?>
 <?php if (!empty($title)) : ?>

<?php print $title; ?>

 <?php endif; ?>
 <?php print $list_type_prefix; ?>
 //Add this
 <?php $x = 0; ?>
 <?php foreach ($rows as $id => $row): ?>
    <?php if($x < 1): ?>
    <li class="<?php print $classes_array[$id]; ?>"><?php print $row; ?>

    <?php $x++; ?>
  <?php endif ?>
<?php endforeach; ?>
<?php print $list_type_suffix; ?>
<?php print $wrapper_suffix; ?>

And you'll have what you wanted:


views Filter field equal to the value of another field Is there a way or a module to filter a vie by a field against the value of another field. For example uI'd is equal to the  value of another field that's given.

From what I understand of your request you are adding a view on a node display page and want to use a field on that page as an argument in the view, if this is the case you want to add a contextual filter and under default value select php and then do a node_load or db_select to load the field from the node being viewed.


How to display a link field with its link text in a twig template A content type includes a link field link that accepts Link text.

A user inputs the URL /target with the Link text "Go to target".

How do I get twig to generate

   `<a href="/target">Go to target</a>`

I have tried what I've found by reading, including

{{ node.field_link }} (crashes)
{{ node.field_link|render }} (crashes)
{{ node.field_link.value }} (does nothing)
{{ node.field_link.0.url }} (displays /target but not as a link and ignores the link text)
{{ node.field_link.uri }} (displays internal:/target but not as a link and ignores the link text)

Seems like there must be a one-step way to accomplish this.

{{ node.field_link }} and {{ node.field_link|render } crashes because node.field_link of type FieldItemList not a rendered array.

Instead of using node variable use content variable like {{ content.field_link }} or even {{ content.field_link.0 }} it works.


content relationship in views I have a view and I need to relate contents, the problem is that you do not show me the data.
Two contents: 1. productions, 2. functions (theater).
the functions are related to the productions, but inversely not.

I need to create a cover of productions, which contain the dates of the functions with the link of your purchase.

example:

Manage  Field: functions

products, they have no related field
Thank you very much!

Add a similar problem, on the same types of content.
Is list of productions:

I can not add a list with this design. Add views

thanks

You can introduce functions fields into your productions views by adding a Relationship through the Entity reference field.

Add a new Relationship Content referenced from field_production_content
Add a new Field field_date_functions and set it to use the Relationship field_production_content
Add a new Field field_tiket_link_functions and set it to use the Relationship field_production_content

If I understood your structure correctly you'll see functions fields on their related functions nodes in Views results.


"PHP Fatal error: Call to undefined method Consolidation\AnnotatedCommand\Hooks\HookManager::getHookOptions()" I just installed drush using "composer require drush/drush". It ran correctly and when it completes a navigate to vendor/drush/drush/ directory where the drush.php file is located

Then I run the following command:
php drush.php status and I get the following error:

PHP Fatal error:  Call to undefined method Consolidation\AnnotatedCommand\Hooks\HookManager::getHookOptions() in
[...]/work/www/EnviePractice/vendor/drush/drush/includes/annotationcommand_adapter.inc on line 475
PHP Stack trace:
PHP   1. {main}() [...]/work/www/EnviePractice/vendor/drush/drush/drush.php:0
PHP   2. drush_main() [...]/work/www/EnviePractice/vendor/drush/drush/drush.php:12
PHP   3. Drush\Boot\BaseBoot->bootstrap_and_dispatch() [...]/work/www/EnviePractice/vendor/drush/drush/includes/preflight.inc:66
PHP   4. drush_dispatch() [...]/work/www/EnviePractice/vendor/drush/drush/lib/Drush/Boot/BaseBoot.php:67
PHP   5. annotationcommand_adapter_add_hook_options() [...]/work/www/EnviePractice/vendor/drush/drush/includes/command.inc:170
Drush command terminated abnormally due to an unrecoverable error.                                                                      [error]
Error: Call to undefined method Consolidation\AnnotatedCommand\Hooks\HookManager::getHookOptions() in
[...]/work/www/EnviePractice/vendor/drush/drush/includes/annotationcommand_adapter.inc, line 475

Can anyone please guide me to what might be causing this?

Additional details:

I am on ubuntu 16.04
Drupal 8 installation
version of drush 8.1

I think your installation or class registry might be broken. Try doing the following things:

See if drush rebuild works (if it does not, go to the next point).
Go to your Drupal install directory and try to run composer install.
If drush rebuild didn't work in the first step, try running it again now.


Multi-sites local dev alias question for Drupal 6 / OS X With Drupal 7, it's fairly trivial to set up a local alias for a multi-site using the sites.php file. With Drupal 7, I can have a multi-site folder on my local dev be named:

subsite.com

... located in the /sites/ folder

so that it's: /sites/subsite.com/

Then in my sites.php file, I do something like this:

$sites['subsite.dev'] = 'subsite.com';

... but I can still view this local site in my browser as:

http://subsite.dev

This is good on many levels, it allows me to have a custom subsite (of a multi-site) as the actual name it will be on the remote server. Thus I can have custom modules and themes for the subsite in my Git repo. In addtion, if I clone the remote db back to local at any given point, any given site specific references do not need to be changed in the local DB.

The question then, is there any way to have similar local aliasing with Drupal 6.  I know Drupal 6 does not have the sites.php file so I am not sure how else to do this. Becuase of this, right now I am stuck with rendering my local Drupal 6 multi-site folder as subsite.dev. I know I could chnage my "hosts" file in OS X but then I am stuck having to change it all the time to view the actual ".com" remote domain.

Seems like what you want could be accomplished by creating a symbolic link in the sites directory. Linking to subsite.com by the name subsite.dev would do it:

$ cd [sites-directory]
$ ln -s subsite.com subsite.dev

Mind you, you might need to change the $conf['cookie_domain'] and $conf['base_url'] values in the settings.php file if you want to be able to log in to your local dev site.


how to solve Notice: Undefined offset: 1? I used the following function to alter menu (hook_menu_alter)

function _term_account(){
  global $base_url;
  global $user;
  $account_id = custom_get_user_account_id();
  $tesr = explode('_', arg(3));
  if($tesr[1] == $account_id){
    return true;
 } else {
    return false;
 }
}

function custom_menu_alter(&$items) {
  // Works fine.. So every user has he's own and only vocabulary return true..
  $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/list']['access callback'] = '_term_account';
  }

and it works fine.. but.. when i go to reports/dblog in my site.. i have over than 30 row of same error

  Notice: Undefined offset: 1 in _term_account() (line 277 of
  ../public_html/sites/all/modules/custom/custom.module).

Is there something wrong in the function?

This line of code will split arg(3) into an array of strings using _ as the delimiter.

  $tesr = explode('_', arg(3));

Assuming that in this case arg(3) is never empty, it is still possible that there are no underscores in arg(3), in which case you will have an array of 1 item.

Since arrays are zero based, this will give you something like

Array
(
    [0] => 'somestring'
)

In that case, your next piece of code

  if ($tesr[1] == $account_id) {

will throw the Undefined offset: 1 notice because there is no array element with the key 1.

If you want to safely use $tesr[1] you have to do something like

  if (isset($tesr[1]) && $tesr[1] == $account_id) {

Additional unsolicited feedback:

Don't name your module 'custom'. Name it something more descriptive of its purpose. If it has many distinct purposes split it into multiple modules. It will be easier to maintain in future if you can easily tell what different modules do.
Always prefix your function names with the name of the module. _term_account() might clash with another module's function. Prefixing with your module's name helps avoid that.
You have global $base_url; and global $user; but then you never use them.
Consider using a variable name that is more descriptive than $tesr, so you can easily tell what it means if you come back to the code in future.
Code is easier to work on if it uses consistent formatting standards. Check out Drupal's at https://www.drupal.org/docs/develop/standards


Rules: Data comparison between saved and unchanged node doesn't work with radio buttons I successful used the data comparison on rules condition between saved and unchanged node for a date field.

I tried the same with a radio buttons list with two options, but the rule doesn't trigger if I change the value after saving the node.

What's wrong?

Here the rule: http://kopy.io/6GfFi  and here is an instream copy of it:

{ "rules_last_day_of_work" : {
"LABEL" : "Last Day of Work",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "interval", "rules_conditional" ],
"ON" : { "node_update--job_contract" : { "bundle" : "job_contract" } },
"IF" : [
  { "NOT data_is" : {
      "data" : [ "node-unchanged:field-date-of-last-day-of-work" ],
      "value" : [ "node:field-date-of-last-day-of-work" ]
    }
  },
  { "OR" : [] },
  { "NOT data_is" : {
      "data" : [ "node:field-resignation-layoff" ],
      "value" : [ "node-unchanged:field-resignation-layoff" ]
    }
  }
],
"DO" : [
  { "drupal_message" : { "message" : "test" } },
  { "data_calc" : {
      "USING" : {
        "input_1" : [ "node:field-days-of-notification" ],
        "op" : "*",
        "input_2" : "-1"
      },
      "PROVIDE" : { "result" : { "days_of_notification_negative_sign" : "Days of notification with negative_sign" } }
    }
  },
  { "interval_apply" : {
      "USING" : {
        "interval" : [ "days_of_notification_negative_sign" ],
        "period" : "day",
        "date" : [ "node:field-date-of-last-day-of-work" ]
      },
      "PROVIDE" : { "date" : { "notification_date" : "Notification Date" } }
    }
  },
  { "CONDITIONAL" : [
      {
        "IF" : { "text_matches" : {
            "text" : [ "node:field-resignation-layoff" ],
            "match" : "L",
            "operation" : "starts"
          }
        },
        "DO" : [
          { "data_set" : {
              "data" : [ "node:field-layoff-date" ],
              "value" : [ "notification-date" ]
            }
          },
          { "data_set" : { "data" : [ "node:field-resignation-date" ] } }
        ]
      },
      { "ELSE" : [
          { "data_set" : {
              "data" : [ "node:field-resignation-date" ],
              "value" : [ "notification-date" ]
            }
          },
          { "data_set" : { "data" : [ "node:field-layoff-date" ] } }
        ]
      }
    ]
  },
  { "redirect" : { "url" : "[node:url]" } }
]
}   }

THE ANSWER IS:
this is the way to put two condition in "OR"

and NOT this one:

1st attempt (do some debugging ...)

You clearly have a combination of Rules Conditions and/or Actions which don't seem to react as you expect/want them to do. If I was to get this to work, the first thing I'd do is Rules debugging. Rules is great, but sometimes also tough to debug if things don't work as you'd expect.

There are some typical facilities to do such debugging, but my Keep-It-Super-Simple technique I often use is my BINGO-trick (if you want, you could consider/call it "adding breakpoints to a rule you want to debug"). A sample of such rule can be found in my answer to "Which Rules condition can be used to email a user when an admin updates their profile?". Obviously, if you have more then 1 Rules Action (you seem to have (about) 4, following the "Display message test"), you may want to  make it like Bingo1, Bingo2, Bingo3, etc. Depending on the order they are shown, you also know the order of execution. Stupid, but simple and efficient (I think). Here is an edited version of your rule containing those BingoX-messages (try to import it in your site, note I gave it another machine name):

{ "rules_cessazione_with_breakpoints" : {
    "LABEL" : "Cessazione with breakpoints",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "interval", "rules_conditional" ],
    "ON" : { "node_update--rapporto_di_lavoro" : { "bundle" : "rapporto_di_lavoro" } },
    "IF" : [
      { "NOT data_is" : {
          "data" : [ "node-unchanged:field-data-cessazione" ],
          "value" : [ "node:field-data-cessazione" ]
        }
      },
      { "OR" : [] },
      { "NOT data_is" : {
          "data" : [ "node:field-dimissioni-licenziamento" ],
          "value" : [ "node-unchanged:field-dimissioni-licenziamento" ]
        }
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Bingo1" } },
      { "data_calc" : {
          "USING" : {
            "input_1" : [ "node:field-giorni-di-preavviso" ],
            "op" : "*",
            "input_2" : "-1"
          },
          "PROVIDE" : { "result" : { "giorni_neg" : "Giorni neg" } }
        }
      },
      { "drupal_message" : { "message" : "Bingo2" } },
      { "interval_apply" : {
          "USING" : {
            "interval" : [ "giorni-neg" ],
            "period" : "day",
            "date" : [ "node:field-data-cessazione" ]
          },
          "PROVIDE" : { "date" : { "data_preavviso" : "Data Preavviso" } }
        }
      },
      { "drupal_message" : { "message" : "Bingo2" } },
      { "CONDITIONAL" : [
          {
            "IF" : { "text_matches" : {
                "text" : [ "node:field-dimissioni-licenziamento" ],
                "match" : "L",
                "operation" : "starts"
              }
            },
            "DO" : [
              { "drupal_message" : { "message" : "Bingo3a" } },
              { "data_set" : {
                  "data" : [ "node:field-data-licenziamento" ],
                  "value" : [ "data-preavviso" ]
                }
              },
              { "drupal_message" : { "message" : "Bingo3b" } },
              { "data_set" : { "data" : [ "node:field-data-dimissioni" ] } },
              { "drupal_message" : { "message" : "Bingo3c" } }
            ]
          },
          { "ELSE" : [
              { "drupal_message" : { "message" : "Bingo4a" } },
              { "data_set" : {
                  "data" : [ "node:field-data-dimissioni" ],
                  "value" : [ "data-preavviso" ]
                }
              },
              { "drupal_message" : { "message" : "Bingo4b" } },
              { "data_set" : { "data" : [ "node:field-data-licenziamento" ] } },
              { "drupal_message" : { "message" : "Bingo4c" } }
            ]
          }
        ]
      },
      { "drupal_message" : { "message" : "Bingo5" } },
      { "redirect" : { "url" : "[node:url]" } },
      { "drupal_message" : { "message" : "Bingo6" } }
    ]
  }
}

I'd be interesting to hear which of those "BingoX" messages will get shown while debugging your rule ... Based on that you should come closer to finding the real reason for your rule which doesn't seem to do what you expect/want.

For more suggestions about Rules debugging, and more advanced facilities, refer to "How can I display the value of a variable inside a condition?"

Note: for those who think "this is not an answer", here is my reply to that already: do you know the story about giving somebody a fish, versus giving a fishline (or whatever that is called)?

2nd attempt (why no "entity has field"?)

About your "but the rule doesn't trigger". It may mean that you NOT (repeat: NOT) get that "test" message (as in your very first rules action). If that's the case, I'd wonder (if I was debugging) what results you get if you (temporary) remove the first rules condition? And what if you (temporary) remove the 2nd rules condition?

Hang on: you don't seem to have the typical "entity has field" condition (as your very first Rules Condtion). Imagine Rules thinks all those field values are blank (because of the missing  "entity has field" ...), then neither condition is true (because of the NOT ...), so the rule works as implemented. Therefor, add such "entity has field" Rules Condition, 1 for each of the fields you are already doing those data comparisons. Then let us know the result (the bets are open ...).


How to filter content (admin view) based on taxonomy term I'm looking for a way (I'm happy to write a module if shown the way) to filter content in the admin view based on taxonomy term. I've been using the Administration View modules, but it doesn't provide what I'm looking for. And to be honest, I'd be happy to write a simple module that would do such thing. Can anyone point me in the right direction?

Thanks

Using [Administration Views] https://www.drupal.org/project/admin_views you should be able to enable or extend an existing view.  I have done it for content but have had trouble with that module and had to revert a few times.


Creating a page per bundle I am trying to create multiple bundles for a given entity.

However, when I'm doing this, all of my manage field and manage displays are on the same page, and it doesn't appear like any of the other pages are working.

Here's one of the bundles:

  $info['gov_data'] = array(
    'label' => t('Government Data'),
    'base table' => 'gov_data',
    'entity keys' => array(
      'id' => 'gid',
      'label' => 'type',
    ),
    'module' => 'gov_data_entities',
    'access callback' => 'gov_data_access_callback',
    'fieldable' => TRUE,
    'bundles' => array(
      'bill' => array(
        'label' => t('Bills'),
        'admin' => array(
          'path' => 'admin/structure/gov-data/bill',
          'real path' => 'admin/structure/gov-data/bills',
          'access arguments' => array('administer site configuration'),
        ),
      ),
  'committee' => array(
    'label' => t('Committee'),
    'admin' => array(
      'path' => 'admin/structure/gov-data/committee',
      'real path' => 'admin/structure/gov-data/committee',
      'access arguments' => array('administer site configuration'),
    ),
  ),
),
    'admin ui' => array(
      'path' => 'admin/structure/gov-data',
      'controller class' => 'EntityDefaultUIController',
    )
  );

There are about 6 or 7 more exactly like that.

Why are they all showing up on the main entity page?

How do I organize this so that it looks like content types?

EDIT: Here's my hook_menu() for the person asking:

function gov_data_menu() {
  $items = array();

  $items['admin/config/services/gov-data'] = array(
    'title' => 'Government Data settings',
    'description' => 'Configure settings for Government Data',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('gov_data_admin_settings'),
    'access arguments' => array('administer site configuration'),
  );
  return $items;
}

Why are they all showing up on the main entity page?

This is the easy part. I had the same issue with https://www.drupal.org/node/2299755, but I was dealing with several modules that were each defining a single entity.  Your configuration is a bit more complicated.

You are seeing the UI elements for Manage Display and Manage Field at admin/structure because admin/structure/gov-data doesn't exist. admin/structure is inheriting everything you've defined after admin/structure/gov-data like admin/structure/gov-data/bill/fields and admin/structure/gov-data/bill/display,  First you need to define a menu path for admin/structure/gov-data in your module, but this will only push all of the fields and display tabs up to that level.  You'll also need to either define a redirect for each entity so admin/structure/gov-data/bill goes to admin/structure/gov-data/bill/fields or alter the admin/structure/gov-data/bill/fields and display menus so they aren't tabs.

  How do I organize this so that it looks like content types?

This is a bit more complicated.  The display of node types found at admin/structure/types doesn't just automagically appear.  It is defined in the Node moduels's menu hook http://cgit.drupalcode.org/drupal/tree/modules/node/node.module?h=7.x#n2004.  To get something that looks like the content type list, you'll need to create a customized version of the node_overview_types() function found in http://cgit.drupalcode.org/drupal/tree/modules/node/content_types.inc?h=7.x#n8

So for your configuration, alter your hook_menu to add something like...

function gov_data_menu() {
    $items = array();

    $items['admin/config/services/gov-data'] = array(
        'title' => 'Government Data settings',
        'description' => 'Configure settings for Government Data',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('gov_data_admin_settings'),
        'access arguments' => array('administer site configuration'),
    );

    // returns list of entities with menus "under" gov-data.
    $items['admin/structure/gov-data'] = array(
        'title' => 'Manage Government Data Entities',
        'description' => 'Links to manage field and display of entities',
        'page callback' => 'gov_data_overview_types',
        'access arguments' => array('administer gov data'),
        'weight' => -50,
    );

    return $items;
}
/**
 * Displays an entity type admin overview page.
 * Borrow from node/content_types.inc
 */
function gov_data_overview_types() {
  // This requires a lot more work
}

There is a lot of code you can repurpose from node_overview_types(), but that is something you can figure to meet your specific needs.  You biggest issues here are undefined menu paths being displayed at a level you didn't expect because the deeper, custom menu paths aren't defined anywhere.


How to create a Question/Answer block? I want to create a question/answer block.

I guess I need to create a content type, turn comments on, and in page.tpl.php display nodes with comments. It should appear as in the image below.

What's the easiest way to get that block?

Update:

I decided to use 2 content types, one for question and another for answers, and link each other with node reference.

For example any registered user on the site can write a question, but only moderators can make answers on their questions. When moderator does node/add/answer he/she chooses with a select list to which node the answer would be linked.

Is this a right solution?

If you just want to create a node where a user writes a question to which the other users answer using comments, then you can use a content type that Drupal has by default. For example, with Drupal 7 the "Article" content type has already what you need; an article appears as in the following screenshot:

The only things that would need to be changed are the subject of the comment, that should not be entered, and the string "Add new comment" that should be changed in "Add new answer."
For the first, you need just to change the settings for the content type.

If you deselect the highlighted checkbox, the user will not be able to enter a title for the comment.
The other option to which you could be interested is the following one:

When it is selected, any comment for a comment is shown indented. As the comments for the node are the answers given to the question, any comment for the answer should be indented, or it would not be possible to understand when a comment is an answer, or a comment for an answer (or a comment to a comment given to an answer).

For changing the string from "Add a new comment" to "Add a new answer," you need a custom module that changes that string. For this reason, I would create a content type copying the setting used for the "Article" content type.

You don't need to alter the page.tpl.php file to show the comments together the node: That is what Drupal normally does. There is a module that allows to shows the comments in a different tab, but without that module, Drupal shows the comment in the same page where a node is shown. You will eventually need to change a template file to change the layout of the comments, though.

If you are using the word block to mean Drupal block (e.g. you want to show a block for asking a new question), then that is not possible without using third-party modules. I am not sure there is already a module for that.


How to override field collection field title? I have created field using field collection. I need to override field title and and incremented by 1 every field title. For this I am using this code. But its not working for me.

function previewcustom_form_alter(&$form, &$form_state, $form_id) {
  $x = 1;
  if($form_id =="article_node_form"){

  foreach($form['field_ingredientsf']['und'] as $k => $v) {

    if(is_numeric($k)) {

      $form['field_ingredientsf']['und'][$k]['field_steps']['und'][0]['#title'] = $form['field_ingredientsf']['und'][$k]['field_steps']['und'][0]['value']['#title'].' '.$x;
      $form['field_ingredientsf']['und'][$k]['field_steps']['und']['#title'] = $form['field_ingredientsf']['und'][$k]['field_steps']['und']['#title'].' '.$x;
      $x++;
    }
  }
}

Note I cleared the cache.

Maybe just a typo. It should be ['value']['#title'] = .... Also you'ld rather use LANGUAGE_NONE instead of 'und'.

$form['field_ingredientsf'][LANGUAGE_NONE][$k]['field_steps'][LANGUAGE_NONE][0]['value']['#title'] .= $x;


Complex Content Type, modules? I've been trying to figure out how to create a content type "a course" that has title, description, duration, instrucor details and contains video lessons.
I made three different content types - courses, videos and instructors but couldn't figure it out how to relate it. I've been trying with View but if someone could suggest module/tips how-to would be much appreciated.

BR, Ivan Ivanov

Entity Reference

  Provides a field type that can reference arbitrary entities:

To your course content type add new field of entity ref type and refer videos content type.
Add second field to your course ct and refer instructions content type.

When you create new course you will be able to select instructions and videos

Tutorial (simple)

Youtube tutorial


Content Type "Article" is not showing when trying to add, but it is showing in Structure-> Content Type. Please help me I don't know how i lost Article content type when adding a content. It is not visible for me.

Please find the two screen shots attached.

Try re-enabling the content types in the navigation menu.

Go to administration->structure->menus->navigation and you should see your article content type disabled in the menu. Just re-enable them and it should all work fine