Best practice for writing PDO Query? I have noticed one thing in all core files: all DB related operations are not in try-catch block.

So please suggest me whether it's good practice to put SELECT, UPDATE, INSERT query in try catch block.

It's good practice to put any code that could potentially throw an exception in a try...catch (not just in Drupal-related code, and not just in PHP).

So yes, it's good practice to put your database queries in a try...catch.


Bootstrap external login from subfolder isn't working Consider the following script.

define('DRUPAL_ROOT', getcwd() . "/..");

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$username = "Silox";
$password = "hidden";

global $user;

$account = user_authenticate($username, $password);

// Woah, it seems like we don't know this user, let's create him!
if (!$account) {
    $userinfo = array(
        'name' => $username,
        'pass' => $password,
        'init' => $username,
        'status' => 1,
        'access' => REQUEST_TIME,
    );
    $account = user_save(drupal_anonymous_user(), $userinfo);
    $account = user_authenticate($username, $password);
}

$user = user_load($account, TRUE);
drupal_session_regenerate();
?>

This script logs me in or creates a new account when the username and password combination doesn't exist. When I put this script in the base directory of my Drupal installation, everything works perfectly fine.

However, when I put it in the root directory of the PhpBB subdirectory and change the DRUPAL_ROOT to getcwd() . "/.." to compensate for the extra folder, it doesn't work. If I print out my user array at the end of the function, I get a nice array with corresponding correct info but however, if I return to my Drupal site, I am not logged in.

How can this problem get solved?

I think this is related to how you're defining the DRUPAL_ROOT constant.

Several times I've had to make scripts interact with Drupal from sub folders, and I've found the simplest way to make sure things work correctly is to preface my code with the following:

<?php
chdir('../');
require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
?>

The key thing here is the chdir() call.

Also, when creating a path and you want to go up one folder, its usually ../ not /.., because directory paths should usually end with a /.


Drupal Commerce: Get selected payment method programmatically Is there any way to get programmatically the selected (by customer) payment method from the $order_wrapper variable in Drupal Commerce?

$order_wrapper = entity_metadata_wrapper('commerce_order', $order);

I don't think there's anything built in, but you can use an EntityFieldQuery to grab the transaction(s) related to the order, and from there the payment type(s) used:

$query = new \EntityFieldQuery();
$query->entityCondition('entity_type', 'commerce_payment_transaction')
  ->propertyCondition('order_id', $order->order_id);

$results = $query->execute();
if (!empty($results['commerce_payment_transaction'])) {
  $transactions = entity_load('commerce_payment_transaction', array_keys($results['commerce_payment_transaction']));
  foreach ($transactions as $transaction) {
    $payment_method = $transaction->payment_method;
  }
}


How to get RSS feeds from other sites and display their links in a block? I am using the aggregator core module, I also have feeds module installed but I can't figure how to make it read a remote rss and display the remote links in a block.

Thanks

Drupal 6, Views-6.x-2.12 has built-in Aggregator type you can configure. Make sure you have contents in your aggregator from a valid RSS Feed.


How to delete all nodes of a given content type? I have several thousand nodes of a particular content type. Using the web interface (example.com/admin/content), I can only delete about 50 at a time. How can I quickly delete them?

There is a module for that (TM).

See Bulk Delete.

That will use the Batch API to delete the nodes to avoid timeout or memory issues when deleting thousands of nodes with a single call to node_delete_multiple().

Bulk Delete is an abandoned module.  See for alternatives:

Views Bulk Operations
Delete All


How do I have points and polygons in the same Leaflet map? I have two content types

Location that geocodes an addressfield to place markers on the map
Boundary that uses a geojson field to create complex shapes on the map

I need to use views to show both content types on the same map. It appears that I can only do one or the other.

For an example, think about a map that shows constituency boundaries and voting stations.

Nigel Waters has it correct. Here are the details. I did this for cities and states. I used points for cities and polygons for states. Here are the steps.

Requirements:

Geofield module
Leaflet module
Leaflet Views module (a submodule of Leaflet)

Steps:

Create the two content types: City and State.
Create a field of type Geofield, call it "Location"
Choose GeoJSON as the field widget
Add the Location field to both content types
Create a city. For location enter GeoJSON Point data
Create a state. For location enter a GeoJSON Polygon data
Create a view with a Page display
Add the Location field to the view
Filter the view by State and City content types
Set the Format of the view to Leaflet Map
Your view should now look like pic 1
Click on View Page
You should see a map like pic 2


Loading a form via AJAX with drupal_get_form() I am trying to load a form via ajax, here is the code i use:

JS:

bigPopupBut.click(function () {
        jQuery.ajax({
            url: "http://site/group_create",
            dataType: "html",
            success: function (data) {
                bigPopup.append(data);
            }
        });
})

The group_create is a PHP script that returns me a form, here is the code i used:

$node_type = 'group';
    $form_id = $node_type . '_node_form';
    $node = new stdClass();
    $node->uid = $user->uid;
    $node->name = $user->name ;
    $node->field_city['und']['0']['value'] = $user->field_city['und']['0']['value'];
    $node->field_country['und']['0']['value'] = $user->field_country['und']['0']['value'];
    $node->type = $node_type;
    $node->language = LANGUAGE_NONE;
    $node->path = '';
    node_object_prepare($node);
    $return=drupal_get_form($form_id,$node);
return $return;

The Problem i have is that the PHP callback doesn't just return me the form, but a whole page, with headers, body, so when i append it with JS i get a duplicate of the whole page in my bigPopup DIV.

What am i doing wrong ? how could i just get the form without the surounding page?

Thanks all for the help.

Try just to do echo render($return); exit();.

Otherwise, you should change de delivery callback from the path of your page, and I'm pretty sure that exists one one Drupal for Ajax.


How to offer Views as options in a Content-Type field I would like to add a field to a content type (Events) that gives several views (Certificates of Completion) as options.  Thus, when creating an Event the admin can select which certificate will be associated with this Event.

I'm hoping there is a module for this, but as you might imagine Google can't figure out exactly what I'm asking when my query is predominantly filled with generic drupal terms like "Content Type", "Field", and "Views".

Any recommendations will be greatly appreciated.

You could create a taxonomy for that content type and assign values to it like "Certificates of Completion", etc. Here is the Link for the taxonomy docs.


Drupal 7 - How to get AJAX response displayed in a ctools modal? I want to create a ctools modal popup when a button is pressed.

function custom_form( $form, &form_state ) {
  $form['btn'] = array(
    '#type' => 'button',
    '#value' => t('add'),
    '#executes_submit_callback' => FALSE,
    '#ajax' => array(
      'callback' => 'custom_callback',
    ),
  );
}

function custom_callback() {
  ctools_include('ajax');
  ctools_include('modal');

  ctools_modal_render( 'Error', 'Error Message');
}

I only get the alert message with the un-rendered ajax response. How can get I this response displayed in rendered format in modal?

Checkout Documentation on: http://api.drupal.org/api/drupal/includes!ajax.inc/7
or: http://drupal.org/node/1635198#comment-6120546 on how to render drupal messages.

For more Information about ctools modal you may check: Example to display webforms (webform.module) within CTools modal windows

Or what about a tutorial like: "Ajax modal windows, the easy way"


How do I NOT clear memcache or other cache tables? All of us who love Drupal know the pain of building those cache tables for the first time.

I have a site whose activity is high during a certain part of the day and then non existant at others. I have over 25,000 items of content on the site, and that grows daily.  I  have Memcache, APC (etc) installed for performance. When the site is active, it flies. I am very happy with the speed and performance.

However, if you are part of the lucky few who get to access the site when the cache tables are being rebuilt, you have a good 10 min to sit there and wait.

What can I do to prevent this? Can I have memcache keep all cached files in memory until new versions of pages are requested? I thought about writing a spider to access the site every 15 min to half hour or so (somewhat like boost module does), but wanted to see if any of my caching options could be simply configured before diving into that. If so what configuration options would you recommend?

One setting you can play around with is the minimum cache lifetime setting. It will help, but it won't solve the issue.

The standard Drupal cache doesn't allow for what you are describing. One can do some exotic stuff to update caches in the background but unless you have a large developer budget to make this work I would move on. Note: The 6.x version of boost is the only thing I know of that allows for the cache to be updated in the background.

If you are looking to build a spider, http://drupal.org/project/httprl/ is the way to go. I hope to be developing with this more in the future.


Create  in custom node.tpl I have a node with a lot of images and I want to convert this images in a
-list. So I created a node.tpl-overwrite page and tried to alter my HTML, but with no result.

 <div class="content"<?php print $content_attributes; ?>>
    <?php
      // We hide the comments and links now so that we can render them later.
      hide($content['comments']);
      hide($content['links']);
      print render($content['field_themes_body']);
    ?>

        <?php
          dpm($content['field_themes_images']);
          //print theme_item_list($content['field_themes_images']);
        ?>

It seems like the dpm of the $content['field_themes_image'] contains a whole array with all kinds of properties... Is it possible to filter out the images path only?

I've looked at the theme_item_list-function, but with no luck (or I did it wrong).

The following should work for you.

      hide($content['field_themes_images']);

        <?php
          foreach ($content['field_themes_images']['#items'] as $key => $img)
          {
            print "
";
            print render($content['field_themes_images'][$key]);
            print "
";
          }
        ?>


how to correctly write drush sql-sycn using drush_invoke_process() I need to execute a drush command from a custom module, Im using drush_invoke_process() but I do not know how to write it correctly

How would you write this command for use with drush_invoke_process() ?

drush sql-sync @site1 @site2 --tables-list table1,table2,tableN

How to write the above command in drush_invoke_process() syntax?

Thanks

From your php code:

$values = drush_invoke_process('@none', 'sql-sync', array('@site1', '@site2'), array('tables-list' => 'table1,table2,tableN'));

$values will be an array containing various interesting information about the Drush call.  In particular, check $values['error'] to see if the command succeeded or not.


Create Node and related Node at the same time? I have a content-type (Recipe) that is created by anonymous users and can be rated/reviewed with another content-type (Review).

Users should be able to write a Recipe and a Review related to that Recipe at the same time on the same Page. I think I'm searching for the wrong things but I can't find a solution for this Problem without the need to write a new module.

Thanks in advance.

The Inline Entity Form module will get you that functionality (assuming your reference field is provided by the Entity Reference module).

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


X-Frame-Options and Strict-Transport-Security are prohbiting me from uploading any images via ajax error due to self signed cert (on a dev box) When trying to upload an image in a Node Edit form, I'm getting an Ajax error in the main browser window. The browser console is displaying complaints surrounding Strict Transport and X-Frame options.

  Strict-Transport-Security: The connection to the site is
  untrustworthy, so the specified header was ignored.[Learn More]
  form-VHZcgnXwba2plRQ9nE0JQPqgblsvmrgYHtOtCywfYmo

And

  Load denied by
  X-Frame-Options:
  https://server.ext/file/ajax/field_module_images/und/0/form-VHZcgnXwba2plRQ9nE0JQPqgblsvmrgYHtOtCywfYmo
  does not permit framing

We're I'm at now:
I've followed guildlines in Securing file permissions and ownership. I've not run into this issue with other sites. The only difference in this site and others we run is that this is our first on RHEL 7.  I've read other reports about playing with jQuery Update with little luck.

Potential issue:
Could this be because I'm on a dev server with a self signed certificate?

What I've tried:

I've tried adding the follwing inside /etc/httpd/conf.d/Xframe.conf

<Location /var/www/html>
        Header always append X-Frame-Options SAMEORIGIN
</Location>

This seems to have had to impact after a service restart.

File under just being a bad morning.

It turned out to be the ADMIN THEME was using jQuery 1.4 instead of an updated version. Using jQuery Update, the admin theme now has a 1.8 and content creators are happy.


Migrate fields to another site? I have a Drupal 8 site with a contact form that has a lot of fields. I need to duplicate these fields onto another Drupal 8 site but can't find where they are stored in the DB.

In the config table there is a row per field, but when I try to copy these across, I get this message:

  Drupal\Core\Field\FieldException: Attempt to create a field my_field_name that does not exist on entity type contact_message. in Drupal\field\Entity\FieldConfig->getFieldStorageDefinition() (line 286 of core/modules/field/src/Entity/FieldConfig.php).

Does anyone know if it's possible to copy the contact form fields to another site via the Database?

Yes. One way could be:

You export your configuration. (drush cex -y, or on the interface configuration management)
You filter the configuration you need.
You import those configuration files into the other site (drush cim, or manually).


Give user 1 status to someone else? I'm in the process of leaving my current job, and that requires that all of my accounts be disabled.  Well, some of those accounts are user 1 accounts in a few of our Drupal sites.  Is it possible to just "transfer" user 1 to another account?

As others have said, the user account with ID equal to 1 is a special account: It is one of the default accounts created by Drupal during its installation, and it is the only account to which every permission is assigned. (See @Clive's answer.)

What can be done is changing the password, and the email associated with that account.

Create a file in the same directory containing index.php, and add the following code.

define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$account = user_load(1);
$edit = array(
  'pass' => 'New password';
  'mail' => 'New email';
);

user_save($account, $edit);

With this code, everybody with access to the filesystem of the server can change the password, and the email of the user #1. I am not suggesting to change the password directly in the database because the password in clear; Drupal saves the hash obtained from user_hash_password(), whenever user_hash_password() is the function implemented by Drupal, or from third-party modules.

If Drush is available, changing the password is even easier. Everybody could execute the following command:

drush user-password <username> --password="<password>"


Change error message generated by webform for duplicate email submission I have a webform which takes a name and an email, the email field is set to not accept duplicates.

I have done this by choosing unique in the field settings (which is next to the required checkbox).

The error message it shows when a duplicate email is attempted is

'The value email has already been submitted once for the Email field. You may have already submitted this form, or you need to use a different value.'

How can I change this completely?

There's other way if you don't want to code anything.

You can use String Overrides  Module

  This module allow override any translatable string on the site.


How to translate blocks content (created with views module) in drupal 6? I created blocks with views, my question is this: When you select a language, even the block content ( created with views )applies to me translated ?

You can add a filter to your view, under the Node translation group that will make your view filter out nodes that don't belong in the default or current language.

Edit You may need the i18n views module to see some of the options in the screenshot.


Media with WYSIWYG not converting media tags to markup I just installed the Media module v 7.x-2.0-alpha3 along with WYSIWYG, CKEditor, and Image Resize Filter. (The site has many other modules active.)  The site also uses Display Suite, and its view modes are used for different types of images. My use case is for images embedded in the Filtered HTML text format, not as separate entities in a content type.

When an image is first embedded, its source code is like this:

[[{"fid":"161","view_mode":"default","fields":{"format":"default","field_file_image_alt_text[und][0][value]":"f asdfasdf"},"type":"media","attributes":{"alt":"alt text","class":"media-element file-default"}}]]

From my reading, I found that checking "Convert Media tags to markup" at mysite/admin/config/content/formats/filtered_html is required. I have verified that is active.

Instructions at https://www.drupal.org/node/1599070 include "Image resize filter" is AFTER "Convert Media tags to markup" and my filters are in that order.

If I double-click an embedded image in the CKEditor and make it a captioned image, then the Media tags are converted to markup. If a caption isn't added, the Media tags do not get converted.

Based on my configuration, can anyone suggest why the conversion is not occurring?

I was having this same problem and have solved it. My problem was not rendering the text in the correct format in the template. So if you are using a custom theme, .tpl or whatever you need to make sure you render it correctly. I had it like this:

<?php print $node->field_main_body['und'][0]['value'] ;?>

Changing this to proper rendering using field_view_field fixed it for me:

<?php print render(field_view_field('node', $node, 'field_main_body', array('label'=>'hidden'))) ;?>

Hope that's helpful


Twig template variable not displaying value I have a Twig template for a custom block. My custom module is establishing what template is used like so

function mymodule_theme($existing, $type, $theme, $path){
    return array('mymodule' =>
        array(
            'variables' => array(
                'header-title' => 'Default Title',
                'header-size' => 'h1'
                ),
                'template' => 'block--HeaderText'
            )
        );
}

and my custom block contains.

public function build() {
    return array(
        '#theme' => 'mymodule',
        '#title' => '',
        '#header-title' => $this->configuration['label'],
        '#header-size' => $this->configuration['header-size-submit'],
        );
}

And in my block--HeaderText.html.twig I have

<h2>{{ header-title }}</h2> This is a test {{ header-size }}
{{ dump() }}

However header-title and header-size both output 0. But using the dump() function in the template shows that the actual variables are available some how.

The dump() produces

array(15) { ["header-title"]=> string(19) "Header Textsdfgsdfg" ["header-size"]=> string(2) "h4"...

Yet {{ header-title }} just results in 0.

The issue was that Drupal didn't like that the variable names had hyphens in them.
When switching from header-text to header_text it worked fine.


Given a node object how can I detect if it's first term (or term in a chosen vocabulary) contains a taxonomy image? Using php code and a node object, how can I detect whether or not the node's first term (or term in a chosen vocabulary) has a taxonomy image? Any help appreciated.

taxonomy_image_display returns an empty string iff the term has no image.

Given a node $node, the terms are stored in $node->taxonomy as an array indexed by term ID (see taxonomy_nodeapi($node, $op = 'load')).


How to add a tooltip to a Form API field? I have a field defined like that:

'name' => array(
  '#title' => t('Name'),
  '#type' => 'textfield',
  '#size' => 30,
  '#maxlength' => 45,
  '#default_value' => $item->Name,
  '#description' => t("Item's name, no longer than 45 characters."),
),

How can I turn the description into a tooltip that will appear when user keeps mouse cursor over form element?

Solution is to use #attributes attribute to provide form element with HTML title attribute, like that:

'name' => array(
  '#title' => t('Name'),
  '#type' => 'textfield',
  '#size' => 30,
  '#maxlength' => 45,
  '#default_value' => $item->Name,
  // '#description' => t("Item's name, no longer than 45 characters."),
  '#attributes' => array(
    'title' => t("Item's name, no longer than 45 characters."),
  )
),


drupal commerce calculator I have a webshop made with drupal commerce kickstart and use it as a POS in a bar. The people pay with cash. What i want is a calculator with 2 input fields: field 1: the "Order total" from checkout automatic comes in this field. Field 2 is the amount of cash the customer pays with. So i can see how much i have to return to the customer.
I have webform calculator installed. But the big question is how to automatic place the value from Order total in the calculator.

If you already have a calculator that you like and the commerce portion is working the way you want it, the best thing to do is probably to change as little as possible. My first thought is to use a simple javascript that looks for the field where commerce stores the order total and copy it into your webform field. In my kickstart staging environment, there is a field called "ajax-item-price". So you could do a jquery one-liner like

$('#name-of-your-webform-field').val($('#ajax-item-price').html());


How to move my site files outside the Drupal folder on local computer? I like the Windows file structure that keeps program files separate from my data files. This allows me to organize my stuff logically by content and makes it easy to do regular backups of all of my stuff without needing to back up the program files, which are more easily replaced if necessary.

I have several websites that I've developed in ASP over the years and I keep the HTML, ASP,
and other content files for each site in subfolders of a folder called "Web root". When I want to update a site, I first test the changes locally and then just FTP the modified files from the correct "Web root" subfolder to the online server.

Can this philosophy work for Drupal?

I'm now looking at revamping those sites in Drupal and I'd like to keep this separation of program and data files if I can. I've installed XAMPP and am getting ready to install Drupal. I've figured out how to move the MySQL "data" folder out of the MySQL folder and confirmed that the configuration works, so that's taken care of. Now the question is how to do the same thing with the site content files for Drupal.

What I want to do is keep the Drupal core along with downloaded modules and themes in XAMPP's "htdocs" folder where they're designed to go, but put content that I develop elsewhere outside the XAMPP folder. I think this means basically the contents of subfolders of the "sites" folder.

Can this be accomplished with configuration settings or symlinks or some other method?

I found the following related forum post that recommends symlinks:

Store Drupal files outside of the root

but it only talks about putting the contents of the "files" folder elsewhere. I don't know Drupal enough yet to know if that's enough or if I need to be able to put other contents of "sites" subfolders elsewhere as well.

Can someone point me to information on how to do this?

Thank you.

Yes you can separate files folder out of Drupal core installation.
Follow these steps:

Go to admin/config/media/file-system
See public file system path, this needs to be relative to drupal installation. So if I want to make the files folder in parent folder of Drupal core installation, I need to give path like ../test_files
Go to admin/config/development/performance
Clear cache and if you have aggregated css and Js, disable them, clear cache and again enable them.

This works


Best way to backup and restore the databases of a Drupal 7 multisite using Drush? I'm looking for an easy way to backup (and if needed restore) the databases of a Drupal multisite using Drush.

Drush command I use to backup all the databases:

drush @sites sql-dump --result-file --gzip

The backup of the databases seems to work. After executing the above command, databases are automatically stored in /root/drush-backups/DATABASENAME/TIMESTAMP/DATABASENAME_TIMESTAMP.sql.gz

What command can I use to restore the last backup of the databases automatically?

What is the best way to backup and restore the databases of a Drupal 7 multisite using Drush?

PS: I'm using Git, so I only need to backup databases.

Many thanks for your advice!

This is how I do the restore on a site-by-site basis:

drush @site1 sql-drop -y && gunzip -c /path/to/backup/file1 | drush @site1 sql-cli

You could maintain a list of site aliases to database name and write a shell script to automate the process.

The database name for an individual site could be extracted as follows:

drush status @site1 --fields=db-name --field-labels=0

Unfortunately, there's no all-in-one solution for restore.

An alternate solution would be to use the Backup and Migrate module, which has drush integration. There are bam-backup and bam-restore commands which might be easier to work with.

As @Duncanmoo mentioned, it's also good to run drush rebuild-registry after the restore.


Getting form variables data into twig templates I need to pass an array to twig along with the form.

public function buildForm(array $form, FormStateInterface $form_state) {
   $form['job_locations'] = $job_locations;
   $form['#theme'] = 'search_form';
   $form['#method'] = 'get';
   ......
   return  $form;
 }

where $job_locations is

Array
(
[0] => Array
    (
        [city] => Singapore
        [count] => 5
    )

 [1] => Array
    (
        [city] => Toronto
        [count] => 3
    )
 )

And my twig file looks like

 {% for location in form.job_locations %}
        {% if location.city  %}

              {{ location.city }}

     {% endif %}
    {% endfor %}

Everything is coming correctly but it is throwing an error in the error log like

User error: "count" is an invalid render array key in Drupal\Core\Render\Element::children() (line 97 of C:\xampp\htdocs\aws\dev\careers\core\lib\Drupal\Core\Render\Element.php)

User error: "city" is an invalid render array key in Drupal\Core\Render\Element::children() (line 97 of C:\xampp\htdocs\aws\dev\careers\core\lib\Drupal\Core\Render\Element.php)

Please help me to solve this.

Three possible solutions:

Valid render array

You get a valid render array by putting the content of city and count in #markup elements:

  'city' => [
    '#markup' => 'Singapore',

Form variable with a #

Or start the variable name with a hash, so that it is no longer
considered to be a form element which needs to be rendered:

$form['#job_locations'] = ...

Twig:

{% for location in form['#job_locations'] %}
  ...
{% endfor %}

Separate template

Or create a custom template
with a variable for the locations array to theme the list separately from the
form:

$form['job_locations'] = [
  '#theme' => 'job_location_list',
  '#locations' => $job_locations,
];


Theming views-exposed-form search block same like normal Drupal search block On this page, top-right you see a custom views-exposed-form search block. How do i theme this, so it has the same classes and HTML structure as the one below (default Drupal search block)?

You can try block attributes
You can edit class or ID. More readable and easy to maintain.


In custom install profile How to delete the "Footer" menu that core provides by default? I am writing custom Drupal 8 install profile to be used in our organization.

The core creates the "Footer" menu as default system menu listed in menu admin page.

I want to delete or disable this menu during installation execution.

I already found that I can make it manually delete able if I add system.menu.footer.yml with

locked: false

But how can I eliminate it in the first place, via install profile ?

Solved.

Following https://drupal.stackexchange.com/a/186322/8938  I added the code below to  my_profile_install() function inside my_profile.install file.

  \Drupal::configFactory()->getEditable('system.menu.footer')->delete();

Reinstalled and yes, footer menu is not around anymore :)


Organic groups & views So... I created a few groups and a new content-type. The problem is that I don't know how to display content linked to a certain group using a path like: "/[-content-type]/[group-name] (using views, of course). As far as I know it has something to do with contextual filters, but that's where my knowledge ends.

Thanks for any help.

take some time and watch these very informative new videos: Modules Unraveled Kudos to Brian Lewis aka bjlewis2


Fetching text field from the node I am working on flex slider module and I want to add one button in caption so for that I have added one field in content type with Machine name: field_image_url and Field Type: text.

Now I am changing in core file of the module to fetch that URL into the front end.For that code is below:

    <?php
    /**
     * @file
     * Default output for a Flex Slider node.
    */
    ?>

      <div class="flexslider-content flexslider clearfix" id="flexslider-<?php print $id; ?>">

        <?php foreach($items as $item) : ?>

<?php print render($item); ?>
            <?php if(!empty($item['#item']['title']) || !empty($item['#item']['alt'])) : ?>

<?php print $item['#item']['alt'];?>

<?php print $item['#item']['title']; ?>

             <?php if(isset($node->field_image_url)): ?>
                <a href="<?php print render ($node->$field_image_url); ?>" class="btn btn-theme">Learn More
             <?php endif; ?>

            <?php endif; ?>

        <?php endforeach; ?>

I know I am making some mistake as I am very new to drupal development.

     <?php if(isset($node->field_image_url)): ?>
        <a href="<?php print render ($node->$field_image_url); ?>" class="btn btn-theme">Learn More
     <?php endif; ?>

Above code is for fetching URL.It is not giving me any error, but it is also not showing me the button.I have already entered URL for one slide.

Where am I lacking ?

Edited :

I want to also mention that Slider is on front page and there is an article content just below to the slider.

I have given node path to the front page from the Configuration to show it on front page.

So now, If I do

     <?php
        if (arg(0) == 'node' && is_numeric(arg(1))) {
          // Get the nid
          $nid = arg(1);
          // Load the node if you need to
          $node = node_load($nid); print_r($node);
        }
     ?>

It is giving me the node ID of the article.I want the node ID of the slider Image so that I can pull out the image URL field that I have added to the Slider Image Content type.

EDITED:

    <?php
        //this code will load all nodes from your content type and then print them
        $node_type = "slider_image";
        $result = db_query("SELECT nid FROM node WHERE type = '%s' ", $node_type);
        $nodes = array();
        while ($obj = db_fetch_object ($result)) {
          $node = node_load($obj->nid);
          echo $node->field_image_url['und'][0]['value'];
          echo '
';
          $nodes[] = node_load($obj->nid);
        }
    ?>

I have tried above code but it is giving me an error :
Recoverable fatal error: Argument 2 passed to db_query() must be of the type array, string given, called in path to modules\modules\flexslider\theme\flexslider-container.tpl.php on line 19 and defined in db_query() (line 2345 of path to site\includes\database\database.inc).

So to resolve above error, I tried following code with help of this:

$result = db_query("SELECT nid FROM node WHERE type = ':type' ", array(':type' => $node_type));

But above code also gives me error : Fatal error: Call to undefined function db_fetch_object() in path to module\modules\flexslider\theme\flexslider-container.tpl.php on line 21

In general to get the value of field if the entity type is a node

$node = node_load($nid);
echo $node->field_image_url['und'][0]['value'];

or try to print the $node to figure out how to get it

echo '<pre>'; var_dump($node); var_dump($node->field_image_url); die;

in your situation try the next to figure out what is happen there

<?php
$node_type = "slider_image";
$sql = db_query("SELECT nid FROM node WHERE type = $node_type");
$results = db_query($sql);
foreach($results as $row){
   $node = node_load($row->nid);
   echo $node->field_image_url['und'][0]['value'];
   echo '<br>';
}
?>


How To customize user account creation form I successfully customized the user login and password reset form using this:

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

  $items['user_login'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'responsive_bartik') . '/templates',
    'template' => 'user-login',
    'preprocess functions' => array(
       'responsive_bartik_preprocess_user_login'
    ),
  );
  $items['user_pass'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'responsive_bartik') . '/templates',
    'template' => 'user-pass',
    'preprocess functions' => array(
      'responsive_bartik_preprocess_user_pass'
    ),
  );
    return $items;
}

then I created two files, user-login.tpl.php and user-pass.tpl.php
Which each have code like this:

<?php print render($intro_text); ?>

  <?php print drupal_render_children($form) ?>

Forgot Password

Don't have an account? Sign Up

I tried to the the same thing with the registration form but it still looks the same. It has not overriding it. Here is the code i am used for that:

  $items['user_register'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'responsive_bartik') . '/templates',
    'template' => 'user-register',
    'preprocess functions' => array(
       'responsive_bartik_preprocess_user_register'
    ),
  );

I stuck this right before the
 return $items;
}
section.

Then i created a file: user-register.tpl.php and placed this code into it:

Hello TEST!

<?php print render($intro_text); ?>

  <?php print drupal_render_children($form) ?>

Already have an account?Log in

Don't have an account? Sign Up

Form output didn't change.
I am using Profile2 Module and Logintoboggan Module

You need to use user_register_form instead of user_register.

Try using it like this :

$items['user_register_form'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'responsive_bartik'). '/templates',
    'template' => 'templates/user-register-form',
    'preprocess functions' => array('responsive_bartik_preprocess_user_register'),
);

Now create a user-register-form.tpl.php in your themes template folder.


How To Create 'Node 1 vs Node 2' 'Node 1 vs Node 3' nodes etc as quickly as possible to compare their fields? I want to create a node for each comparison of 2 nodes, so you end up with site.com/node-1-vs-node-2 and then on that page it shows both the node 1 and node 2 fields side by side in a table to compare them.

What am i looking at to get this done as quickly as possible? I have 50 nodes in total and want to do node 1 vs node 2, node 1 vs node 3, node 1 vs node 4, etc all the way through.

Would it be views, or entity reference which shows a table format for each output?

I'm using Drupal 8

You could achieve this quite easily with a custom module. In this example I'll use Drupal console to simplify settings every thing up.

Create a module:

drupal generate:module

Call it whatever you want.

Create a controller:

drupal generate:controller

Sample answers for this may be:

Controller class name: ComparisonController
Method title: CompareNodes
Action method name: compare_nodes
Route path: test/compare_nodes/{id1}/{id2}

Now edit your newly created controller. At the top add a use for the node module:

use Drupal\node\Entity\Node;

Edit the compare_nodes method.

Here is some sample code:

public function compare_nodes($id1, $id2) {

  $node1 = Node::load($id1);
  $node2 = Node::load($id2);

  $fields_to_compare = ['body'];

  $build = [];

  foreach($fields_to_compare as $field) {
    $build['comparisons'][$field] = [
      '#type' => 'container',
    ];
    $build['comparisons'][$field]['value1'] = [
      '#markup' => 'Node 1 value: ' . $node1->get($field)->value,
      '#prefix' => '
',
      '#suffix' => '
',
    ];
    $build['comparisons'][$field]['value2'] = [
      '#markup' => 'Node 2 value: ' . $node2->get($field)->value,
      '#prefix' => '
',
      '#suffix' => '
',
    ];

  }

  return $build;

}

You can edit the list of fields to compare as required and also make any changes to the markup required.

Enable your module and now when you visit: /test/compare_nodes/1/2 you can compare the values of node 1 with node 2.

You can replace 1 and 2 with whatever ids you would like to compare.


User profile view - 2 x variants or view panes with args? I've overridden the User profile template to display custom fields for the user view in Panels, I need to have a View listing with a filter of user comments by 'date' or 'conversation' this I am comfortable with only problem is the filter results list very different info. My approach in resolving this is to have two separate views and create two dynamic links to filter by 'date' or 'conversation'.

I know I can create two variants within the one panel or alternatively two separate panel panes which can accept arguments; only problem is Im not sure what to pass to have one panel pane or panel variant override the other. So when user clicks on 'date' variant x loads when user clicks on 'conversation' variant y loads, or something like that..

Do I achieve this using 'selection rule', 'contexts' or what? Please help...

You can either use two variants or different view panes on the same variant.  It is just an organizational choice.

If you use two variants, use Selection rules to distinguish them.  For example, on one of my sites, I have two variants for the user profile, depending on whether the logged in user is viewing his/her own profile or another user's profile.  I distinguish between these two variants using a Selection  rule of logged in user != user being viewed.

Alternately, within the same variant, you can use multiple content panes (created in Views).  You can choose which of these are shown by clicking in the upper right corner of the respective pane (within the Panels UI) and adding Visibility rules.  Why would you use this approach?  If you only have a few panes.  In my case, I used two variants instead because I had about twenty different view panes on the user profiles, and it was simpler to set two Selection rules then 20 Visibility rules.

So in short, my recommendation is: Use different variants with selection rules when you have lots of different items.  Use a single variant with visibility rules when you only have a few items.


What are the array keys of $content that can be hidden? I see that with drupal 7 theming, we can mark elements of the $content array as hidden.

From http://drupal.org/update/themes/6/7 :

  <?php
    // We hide the comments and links now so that we can render them later.
    hide($content['comments']);
    hide($content['links']);
    print render($content);
  ?>

What other keys always exist? Or if they are dynamically generated, what is the best way to check the hideable content elements?

Thanks

Edit
With the devel module enabled, I found that the information I was looking for roughly corresponds to the information found at the location /node/your_nid/devel/render.
Or using PHP directly, dprint_r(array_keys($content));

Yes, it is dynamical, all modules can add new elements.

Install http://drupal.org/project/devel and then use dpm($content); Note that when you do this inside a page, you will probably only see it after another reload.


Rewrite Output of Date/Time Field Currently I have a Date/Time field that outputs in a Block View as:

Friday, April 25, 2014 - 4:00pm to 6:00pm

But i would like to output it as something like this:

Friday, April 25th from 4pm to 6pm

I was hoping that I would be able to do this by changing the way that the field outputs in the Rewrite Output option, but I did not find a way to get the the right machine names of the field I need to parse everything out as planned.

Does anybody have any other better ideas that would possibly work for this? Thank you!

Drupal 7 allows you to create custom date formats on your configuration page under "regional and language" "date and time." Once in admin/config/regional/date-time click the  "Formats" tab. Then click "add format." You can now define custom dates using the variables available on the PHP date website. The drupal config page includes a link to the PHP date website as well.

I believe the output you are looking for would be: l, F dS, Y - ga (values from the PHP date website)

Once saved go back to the date and time config page and click "Add date type." Type in a name for your new display and select your new format.

In views you can now select the new custom date format you just created as your output.


How to add alt and title attributes to an image gallery View? I am using Views to generate an image gallery. Each image is linked to the content the images comes from, but what I would also like is to add alt and/or title attributes to each of the images. How would I go about doing this?

You can modify the output by selecting the option to re-write output of the field.

Likely, you will want to change the output of your image field from an image to the "URL to file" option.  You will also likely need to add other fields to your view (e.g., image title), which you will want to hide (an option in for views fields).  Make sure these occur before your image field in the views fields dialog box.

Next you will want to rewrite your image field (check the "Rewrite the output of this field" option for your image field).  Views will now show you a box where you can specify the format of your image field, you will likely what to use something such as

<img src="[field_gallery_image_fid]" title="[title]" alt="[title]" />

Views will then replace the [field_gallery_image_fid] macro with the "URL to file" info, and replace the [title] macro with the node title (assuming you added that field ahead of the image field.

In the field rewrite interface views will provide you with a list of macros/fields you can add, all of these fields must occur prior to the field you are rewriting.  If you don't want those fields displayed (other than in the rewrite) make sure to check the "Exclude from display" option on a given field.


Programmatically created list_boolean checkbox field value won't get saved I've added a lot of fields and field instances via a custom module to some prepared content types. field_create_field() and field_create_instance() work like a charm, not a single error. Every field then works as expected, EXCEPT for the checkbox field.

It appears at the right place, has the right label, BUT when it comes to node saving the checked checkbox simply won't save. Next time I edit the node it's unchecked again, no value got written to the database. What do I miss here?

$field = array(
  'field' => array(
    'field_name'  => 'MYFIELD',
    'label'       => 'Set as default',
    'type'        => 'list_boolean',
  ),
  'instance' => array(
    'field_name'  => 'MYFIELD',
    'entity_type' => 'node',
    'bundle'      => 'MYBUNDLE',
    'label'       => 'Set as default',
    'widget'      => array(
      'type'      => 'options_onoff',
      'settings'  => array(
        'display_label' => TRUE,
      ),
    ),
    'display'     => array(
      'default'   => array(
        'label'   => 'hidden',
        'type'    => 'hidden',
      ),
    ),
  ),
);

field_create_field($field['field']);
field_create_instance($field['instance']);

Thanks @Clive, all that was missing were 'allowed_values' in $field['field]:
$field = array(
  'field' => array(
    'field_name'  => 'MYFIELD',
    'label'       => 'Set as default',
    'type'        => 'list_boolean',
    // It's mandatory to add at least two empty values here,
    // Drupal will do the rest then:
    'settings'    => array(
      'allowed_values' => array(
        '',
        '',
      ),
    ),
  ),
  'instance' => array(
    'field_name'  => 'MYFIELD',
    'entity_type' => 'node',
    'bundle'      => 'MYBUNDLE',
    'label'       => 'Set as default',
    'widget'      => array(
      'type'      => 'options_onoff',
      'settings'  => array(
        'display_label' => TRUE,
      ),
    ),
    'display'     => array(
      'default'   => array(
        'label'   => 'hidden',
        'type'    => 'hidden',
      ),
    ),
  ),
);

You simply have to declare empty On/Off values. Which may not seem too obvious, but logical at least since when you create options_onoff checkbox from the backend there's written:

On value [_____] If left empty, "1" will be used.
Off value [_____] If left empty, "0" will be used.


PDOException when creating the table: Base table or view not found I have Drupal running on MariaDB 5.5.33. When I run update.php (after upgrade to Drupal 7.28 from Drupal 6) I get an error:

  Failed: PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'webdb.location_country' doesn't exist: CREATE TABLE {location_country} ( code CHAR(2) NOT NULL COMMENT 'Primary Key: Two letter ISO Country Code', name VARCHAR(255) NOT NULL DEFAULT '' COMMENT 'Full Country Name ', PRIMARY KEY (code) ) ENGINE = InnoDB DEFAULT CHARACTER SET utf8 COMMENT 'Country data managed by location.module.'; Array ( ) indb_create_table() (line 2720 of /home/web/public_html/includes/database/database.inc).

When I try to run command

  CREATE TABLE {location_country} ( code CHAR(2) NOT NULL COMMENT 'Primary Key: Two letter ISO Country Code', name VARCHAR(255) NOT NULL DEFAULT '' COMMENT 'Full Country Name ', PRIMARY KEY (code) ) ENGINE = InnoDB DEFAULT CHARACTER SET utf8 COMMENT 'Country data managed by location.module.';

in phpMyAdmin I get an error

  #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '{location_country} ( code CHAR(2) NOT NULL COMMENT 'Primary Key: Two letter IS' at line 1

But I wasn't able to find out where is the problem.

I had the same problem, and in my case the issue was the database tables engine: By default it is InnoDB and (for some reasons I still don't have to understand) Drupal reports this error.

You must change the database engine to MyISAM. First off, you must be sure the tables that are going to be created by Drupal have MyISAM as engine: In /includes/database/mysql/schema.inc, look for createTableSql($name, $table), and change InnoDB to MyISAM; then, save it.
Since you have a few tables in your database they must be changed to MyISAM as well, so simply export the database as .sql file open it in a text editor and replace Engine=InnoDB with Engine=MyISAM. Now in the server phpmyadmin delete all the tables of the DB and import the new .sql file in there. In this way, all your tables and the tables that will be created by Drupal are MyISAM.


How can I import the configuration on a different site? I have this error when I try to import the config of an another site:

  The staged configuration cannot be imported, because it originates
  from a different site than this site. You can only synchronize
  configuration between cloned instances of this site.

I have 10 customers, and I need to sync my site configuration with 10 different websites.
The site UUID is a problem for sharing a configuration with a different website. Is there a solution?

You can get the UUID with:

drush config-get "system.site" uuid

And you can change it with

drush config-set "system.site" uuid "fjfj34-e3bb-2ab8-4d21-9100-b5etgetgd99d5"

With that you gotta have the same sites.


How to define multiple file downloads for a single library in drush make I am trying to create a make file for the closedquestion module following the instructions in the readme file.

I know the below configuration snippet doesn't work - due to the fact that I am overwriten the first declared download with the second.

; Closedquestion libraries

; * Put jquery.json in sites/all/libraries/jquery-json
;   get it from: http://code.google.com/p/jquery-json/
;   This should result in one of the files (you might have to rename it):
;   - sites/all/libraries/jquery-json/jquery.json.js
;   - sites/all/libraries/jquery-json/jquery.json.min.js

libraries[jquery-json][download][type] = "file"
libraries[jquery-json][download][url] = "http://jquery-json.googlecode.com/files/jquery.json-2.3.js"
libraries[jquery-json][download][sha1] = "2bf6472f96791d6f8a5a405fe6eabe87babf8931"

libraries[jquery-json][download][type] = "file"
libraries[jquery-json][download][url] = "http://jquery-json.googlecode.com/files/jquery.json-2.3.min.js"
libraries[jquery-json][download][sha1] = "2a4615b93c65dd50f92117c570121035a0327fee"

I also tried renaming the second to jquery-json-min & defining a directory_name, but that just throws an error that the folder already exists as would be expected.

libraries[jquery-json-min][download][type] = "file"
libraries[jquery-json-min][download][url] = "http://jquery-json.googlecode.com/files/jquery.json-2.3.min.js"
libraries[jquery-json-min][download][sha1] = "2a4615b93c65dd50f92117c570121035a0327fee"
libraries[jquery-json-min][directory_name] = "jquery-json"

Any input on how this could be solved would be much appreciated.

You are close, you should use destination instead:

libraries[jquery-json-min][download][type] = "file"
libraries[jquery-json-min][download][url] = "http://jquery-json.googlecode.com/files/jquery.json-2.3.min.js"
libraries[jquery-json-min][download][sha1] = "2a4615b93c65dd50f92117c570121035a0327fee"
libraries[jquery-json-min][destination] = "libraries/jquery-json"


Adding Custom JS to CKEditor I'm looking for a way to add custom JS to the CKEditor instance that is being created by the WYSIWYG module.

I posted a feature request on the WYSIWYG module's issue que, but sun suggested I post here as well. http://drupal.org/node/1126656

If you're wondering about why I want to add custom JS, the reason is so that I can adjust WYSIWYG input to more accurately reflect the WYSIWYG output.

You can edit/add CKEditor settings by implementing hook_wysiwyg_editor_settings_alter(), see Allow configuration of advanced editor settings - comment #52 and later comments for examples.

If you want your own script to run after CKEditor has loaded, maybe How to attach Javascript to a form so that it loads AFTER CKEditor can help you.


Implement an API to use HTTP extensions like CalDAV I want to create a calDAV API endpoint. The client would contact my API using methods mentioned in the sabre DAV client documentation https://sabre.io/dav/building-a-caldav-client/ (sabre dav seems to be used by alot of projects so I am using it as a protocol documentation).
Now I am completely lost how to implement that in Drupal. There was a webDAV module but it's abandoned for 4 years and a calDAV module that's abandoned for 9 years...
Can I use REST API and hook it to respond to HTTP request methods like PROPFIND?

I solved this.
I added method to the route and @Method({'PROPFIND'}) to the source (I am not sure if this is needed for Symfony).
class DavController extends ControllerBase {

/**
 * @Method({"PROPFIND"})
 */
 public function dav() {
     //Get the data, fill into xml twig

        $response = new Response();
        $xml = \Drupal::service('renderer')->renderRoot($build);
        $response->setContent($xml);
        $response->headers->set('Content-Type', 'application/xml');

        return $response
 }

module_name.routing.yml (this seems to be mandatory):
    entity.dav_controller.dav:
        path: 'path/to/dav/enpoint'
        methods: [PROPFIND]
        defaults:
            _controller: '\Drupal\path\to\DavController::dav'
            _title: 'my_title'
        requirements:
            _permission: 'access content'

This works in 8 and 9.
Note that this does not involve the Drupal REST API. This is supposed to be an own implementation and won't solve the issue for anyone who wants to use REST API to answer to such methods. I am not experienced enough with Drupal to explain if and how one could configure REST API to accept HTTP methods not listed in the REST API documentation. Maybe one could extend own controllers from the REST API, but I didn't inquire into how to do that.


Internal link to menu item not working I have several rows with elements and I created the delete operation for each row. When I clicked the delete link, nothing happens (it seems that don't calling the delete function).

Code of the menu item (delete function):

$items['node/%webform_menu/webform-factors/factors/%factor_component/delete'] = array(
  'page callback' => 'drupal_get_form',
  'page arguments' => array('forms_grade_factors_delete_factor', 1, 4),
  'access callback' => 'user_access',
  'access arguments' => array('access administration pages'),
  'type' => MENU_LOCAL_TASK,
);

Code of the deletion function:

function forms_grade_factors_delete_factor($form_state, $node, $component) {
    $form = array();
    $form['node'] = array(
      '#type' => 'value',
      '#value' => $node,
    );
    $form['component'] = array(
      '#type' => 'value',
      '#value' => $component,
    );
    $question = t('Are you sure you want to delete this component?');
    $description = t('Description');
    return confirm_form($form, $question, 'node/'.$node.'/webform/components');
}

Code of the table (with the deletion links):

foreach($all_factors as $factor) {
  $delete_link = l(t('Delete'), '/node/'.$nid.'/webform-factors/factors/'.$factor->fid.'/delete',
                                  array('query' => drupal_get_destination()));
  $factors[] = array($factor->factor_name, $factor->factor_formula, $delete_link);
}
$form['factors'] = array(
  '#tree' => TRUE,
  '#theme' => 'table',
  '#header' => array(t('Factor'), t('Formula'), t('Operations')),
  '#rows' => $factors,
);

Thanks for your help! :)

Just saw the your form callback, seems like you are missing argument $form. Small Change as following

From:

function forms_grade_factors_delete_factor($form_state, $node, $component) {

To:

function forms_grade_factors_delete_factor($form, &$form_state, $node, $component) {


Exclude viewing of a field in a view for a content type without excluding content I have 3 types of content (article, product, service) and a view that displays my content on a page.

In my view I added :

a title field
a description field
a content type field

How do I display all the contents in my view by excluding the display of the "content type" field only on the content type "article" (I do not want to exclude the "article" from my view, only the field) ?

I want "product" and "service" to display the "content type" field.

I do not want "article" to display the "content type"

You can achieve that using Views Conditional.

I have added some random image from the web, just for reference purposes.

If this field... Content type

Is... Not equal to

This value Article

Then output this... [type]

Otherwise, output this... (leave empty/blank)


In Tinymce editor, how to set default font family style in select list? I have TinyMCE editor configured and under font family select list, I am able to see 'styles' label as default when loading. But I want to see any font family as default. Suppose, Times new roman as default in select list.

You can try execCommand to make that work.

  Executes a specific command on the currently active editor.

Try this.

editor.execCommand("fontName", false, "Arial");

Another way is to use the content_css configuration option and name an own css file where you can overwrite the editors defaults (the content.css you were recently looking for). In your init function use something like

content_css: "http://sitename/css/my_tiny_styles.css",

and in my_tiny_styles.css or whatever file you choose you use

font-family: myfont1, myfont2, sans-serif;


With the core testing, how do I set a database variable? I am trying to establish a test suite for my project using the core testing module. But I can't get past such a trivial thing as setting a database variable.

A lot of tutorials on the web tell you to use $this->drupalVariableSet - e.g.:

public function setUp() {
  parent::setUp(array('my_module'));
  $this->drupalVariableSet('my_module_var', 42);
}

This throws "Call to undefined method Mymoduletest::drupalVariableSet()" - so it looks like it has been depreciated at some point.

Using variable_set, e.g.:

public function setUp() {
  parent::setUp(array('my_module'));
  variable_set('my_module_var', 42);
}

does not produce an error, but the setting has no effect (i.e. the variable has its default value when it is used in one of the my test cases.

Any help will be appreciated.

drupalVariableSet() has been removed as per Remove drupalVariableSet.

variable_set() is the function you should use. In fact, DrupalWebTestCase::setUp() uses it for some persistent variables used from Drupal core, right after the call to drupal_install_system().

  // Perform the actual Drupal installation.
  include_once DRUPAL_ROOT . '/includes/install.inc';
  drupal_install_system();

  $this->preloadRegistry();

  // Set path variables.
  variable_set('file_public_path', $this->public_files_directory);
  variable_set('file_private_path', $this->private_files_directory);
  variable_set('file_temporary_path', $this->temp_files_directory);

  // Set the 'simpletest_parent_profile' variable to add the parent profile's
  // search path to the child site's search paths.
  // @see drupal_system_listing()
  // @todo This may need to be primed like 'install_profile' above.
  variable_set('simpletest_parent_profile', $this->originalProfile);

As long as the following conditions are met, using variable_set() should work as expected.

The test class derives from DrupalWebTestCase and not from DrupalTestCase
variable_set() is called after parent::setUp()
The name of the persistent variable used in variable_set() doesn't contain typos


Is it possible to use the batch API with transactions? I'm using the batch api for reading large csv files and storing some information in my database. If something fails during the batch run I want all the processed information to be gone, I would like to use drupals transactions for this, but I don't know if this is supported.

If this is not supported is there any known workaround for this?

I'm afraid not.
Batch API divides task into separate steps, each in it's own PHP call. In pure PHP (for simplicity) you use transactions like that:

try {
    // First of all, let's begin a transaction
    $db->beginTransaction();

    // A set of queries; if one fails, an exception should be thrown
    $db->query('first query');
    $db->query('second query');
    $db->query('third query');

    // If we arrive here, it means that no exception was thrown
    // i.e. no query has failed, and we can commit the transaction
    $db->commit();
} catch (Exception $e) {
    // An exception has been thrown
    // We must rollback the transaction
    $db->rollback();
}

To split it into multiple calls, you would need to store PDO object and pass it between calls, but PDO objects cannot be serialized.

Workaround would be to import to a temporary table, and when (if) it was successful, use one more batch api step to move data from temporary one to real destination. And that one last move you can do in one step, so you can wrap it with transaction.


How to call a CCK Field value in a node I want to load one last post's title and call value of CCK fields. I defensibly don't want to use views module. so How can I call those CCK Fields?

anyway is this code correct to load one last post from all terms?
I wish there was a way to do it with node_load()

<?PHP
$output = '';
$terms = "*";
$count = 15;
$qry = "SELECT n.title, n.nid FROM {node} n INNER JOIN {term_node} tn ON n.nid = tn.nid WHERE tn.tid in ($terms) AND n.status=1 AND n.promote=1 ORDER BY n.created DESC";
$result = db_query_range(db_rewrite_sql($qry), 0, $count);
$output = node_title_list($result);
echo $output;
// echo [cck_field1_value];
// echo [cck_field2_value];
?>

I will tell you that the easier way it to use node_load. You do your query to simply get the last nodes according your criteria and then with the nid you load each node with node_load.

Why ? Because CCK changes his database structure according the fields that are attached or not to one or more content type. If you will change the CCK field one day, you will have to change your code, so the easier way to avoid it, its simply use node_load.


My Date in Twig is ignoring format I have a twig file with the following code in my Drupal 8.4.4 site:

{{ node.field_date.value }}

And in my content type, manage display option, I have it formatted like this:

But on the website, it shows the date as

2019-01-16T23:00:00

What am I missing?

You are printing the node value directly, which is bypassing the field formatter and other things (since you are not using the render array).

Do this instead:

{{ content.field_date }}

This will render normally and ensure field formatter settings are respected.


Why does my front page only work in one language? I have problem with language of Drupal. When I click in home page in English language, the front page contains all content, nodes and blocks. When I click on other language, the front page doesn't show any contents and shows this message:

  No front page content has been created yet

How can I make 1 front page that contains the same blocks and content and is also translated in different languages?

This is the way I use it for a website with one single language in the front end (Spanish), and backend in english.

And..

All nodes are created using default language.


Can I use Plain PHP functions in tpl file? I have a tpl.php page for login form in my drupal site in which have 4 images.

I need to display only one of these 4 images randomly on each page load.

I can easily do this in less than 10 lines of code using the php rand() function.

But is it advisable to directly use such functions in tpl files.
Could this have some sort of security risk?

UPDATE:

The 4 images that I talked about. I have just uploaded them to sites/default/files/images folder and have included them in tpl file using following code:

<img src="http://mysite.com/sites/default/files/images/image.jpg"/>

I have a feeling that this is unsafe too. Please advise.

For the first part of question:

You may output as form item the output of your custom function, where contain logic to get random image:

function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'user_login') {
        $form['img_item'] = array(
          '#type' => 'markup',
          '#markup' => my_random_image_output(),
          '#weight' => -50
        );
    }
}

function my_random_image_output() {
    $output = '';

    // your custom logic to output one image $output = '<img src=".... />'

    return $output;
}


Make a custom block to render a published content Is there way to make a custom block displays a list of published contents?

I tried...

Create a new block type with just one field of type Reference->content.
Create a new block with recently created type.
Configure visibility -> type of content to a particular type of content on this recently created block.
Place block in block layout.
Publish a new content.

But at the end nothing is rendered on my page.

Drupal 8 question.

The easier way to achieve this problem is by creating a view block. That only show the content that is been published. Then you going to add that view block on any region that you wish.

Here is the code for a export view block that only show content that have been published.

uuid: 36b6dd0f-8a30-4d08-a718-24afe8b4cfc0
langcode: en
status: true
dependencies:
  module:
    - node
    - user
id: content_published
label: 'Content Published'
module: views
description: ''
tag: ''
base_table: node_field_data
base_field: nid
core: 8.x
display:
  default:
    display_plugin: default
    id: default
    display_title: Master
    position: 0
    display_options:
      access:
        type: perm
        options:
          perm: 'access content'
      cache:
        type: tag
        options: {  }
      query:
        type: views_query
        options:
          disable_sql_rewrite: false
          distinct: false
          replica: false
          query_comment: ''
          query_tags: {  }
      exposed_form:
        type: basic
        options:
          submit_button: Apply
          reset_button: false
          reset_button_label: Reset
          exposed_sorts_label: 'Sort by'
          expose_sort_order: true
          sort_asc_label: Asc
          sort_desc_label: Desc
      pager:
        type: some
        options:
          items_per_page: 5
          offset: 0
      style:
        type: default
      row:
        type: fields
      fields:
        title:
          id: title
          table: node_field_data
          field: title
          settings:
            link_to_entity: true
          plugin_id: field
          relationship: none
          group_type: group
          admin_label: ''
          label: ''
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: true
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: value
          type: string
          group_column: value
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
      filters:
        status:
          value: true
          table: node_field_data
          field: status
          plugin_id: boolean
          entity_type: node
          entity_field: status
          id: status
          expose:
            operator: ''
          group: 1
      sorts:
        created:
          id: created
          table: node_field_data
          field: created
          order: DESC
          entity_type: node
          entity_field: created
          plugin_id: date
          relationship: none
          group_type: group
          admin_label: ''
          exposed: false
          expose:
            label: ''
          granularity: second
      title: 'Content Published'
      header: {  }
      footer: {  }
      empty: {  }
      relationships: {  }
      arguments: {  }
      display_extenders: {  }
    cache_metadata:
      max-age: -1
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - 'user.node_grants:view'
        - user.permissions
      tags: {  }
  block_1:
    display_plugin: block
    id: block_1
    display_title: Block
    position: 1
    display_options:
      display_extenders: {  }
    cache_metadata:
      max-age: -1
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - 'user.node_grants:view'
        - user.permissions
      tags: {  }


Add custom classes or theme a custom form I have a custom form generated in a module.

I want to style the individual inputs by adding classes to them.

Can I add them through the buildform()?

public function buildForm(array $form, FormStateInterface $form_state) {
  //Return array of form API elements
  $form['location'] = array(
    '#type' => 'textfield',
    '#placeholder' => 'Enter your suburb or postcode...',
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => $this->t('Go'),
  );
  return $form;
}

If yes, how would I do this? I can't seem to find a good reference for parameters that can be passed into the $form array.

Alternatively, is there a way to pass the elements to a theme template like can be done with custom blogs or controllers?

You can add classes in #attributes:

$form['submit'] = array(
     '#type' => 'submit',
     '#value' => $this->t('Go'),
     '#attributes' => ['class' => ['button']],
);


Bootstrap subtheme does not apply to main menu After adding the "html.tpl.php" and "page.tpl.html" to my bootstrap subtheme the layout of my main menu disappeard as you can see in the screenshot below:

As you can see; no bootstrap classes are applied to the menu:

Main menu

List links

Edit menu

Configure block

Lessenrooster

Over ons

Contact

Fotogallerij

The bootstrap subtheme however is active:

EDIT 1

I indeed did use the wrong .tpl files. I now have copied the correct files to the subtheme (which included the correct .info file). However the .info file does not include the main_menu region.

regions[navigation]     = 'Navigation'
regions[header]         = 'Top Bar'
regions[highlighted]    = 'Highlighted'
regions[help]           = 'Help'
regions[content]        = 'Content'
regions[sidebar_first]  = 'Primary'
regions[sidebar_second] = 'Secondary'
regions[footer]         = 'Footer'
regions[page_top]       = 'Page top'
regions[page_bottom]    = 'Page bottom'

After clearing the cache, the main menu did not change.

EDIT 2

I started all over again following this guide, but still the main menu looks like crap... and if i copy over the menu folder from bootstrap I get an HTTP ERROR 500 error

You must use the template files from bootstrap theme since all those are overridden there. the templates file you should use are under themes > bootstrap > templates > system.

copy the page.tpl.php and html.tpl.php from there to your sub-theme.

simply use the same .info file for your sub theme as well. it will give you all the regions. set "base theme=bootstrap" in template_name.info file.

remember to clear the cache


Remove link from content header The website I'm building has a lot of content that I do not want linkable to the actual node. Is there a way to remove the link in the content headers?

There are a lot of different methods for doing this.

The basic idea is to detect the content type using one of a few methods and calling drupal_not_found().  When doing this, I typically set the pathauto for these to no-view/[nid], and then detect the request_uri in a hook.  There are some variations, but the all do something really similar.

However, there is a newish module called Rabbit Hole that eliminates the need for custom modules and provides a lot of flexability to how you hide the content.  I had been working on a general use module that did something similar, and abandoned developing it when I found this.  From the project page:

  [It] works by providing multiple options to control what should happen when the node is being viewed at its own page. You have the
  ability to

  Deliver an access denied page.
  Deliver a page not found page.
  Issue a page redirect to any Drupal path.
  Or simply display the content (regular behavior).

  This is configurable per content type and per node. There is also a permission that lets certain roles override Rabbit Hole completely.


How to change the order of content types How would one go about changing the order of the content types list on a multilingual site or non-english site?

For example, by adding a content type named Émission (with accentuated É), we see the following list on admin/structure/types page:

Article
Page
Émission

Same goes when translating a content type name (E.g.: Show => Émission) and changing language.

The function node_type_get_names() calls the utility function _node_types_build().  If you look at the source, there is a call to asort() at the bottom.

If you read the documentation for asort(), you will see that it isn't called with it's second parameter, $sort_flags.  This means that it will be called with the default, which is "normal" rules.  In this case, I am prety sure normal rules means ordering based on the value of the code point, which places the English alphabet first, then "specials".

To take your characters with diacriticals into account, you would have have a proper locale defined, and then call asort() with the SORT_LOCALE_STRING option.  For example,

$types = array('Émission', 'Page', 'Article');
print_r($types);

sort($types);
print_r($types);

setlocale(LC_ALL, 'fr');
sort($types, SORT_LOCALE_STRING);
print_r($types);

results in

Array
(
    [0] => Émission
    [1] => Page
    [2] => Article
)
Array
(
    [0] => Article
    [1] => Page
    [2] => Émission
)
Array
(
    [0] => Article
    [1] => Émission
    [2] => Page
)

That explains why the ordering isn't what you expect.  A quick look through the Drupal source only reveals a single call to setlocale(LC_ALL, 'C'); (it's in the bootstrap).  See https://stackoverflow.com/questions/5231620/what-does-set-localelc-ctype-c-actually-do for what this does.

All of this means that without doing a hook_menu_alter() on the 'admin/structure/types' to change the page callback to be your own, or to hook_pager_alter() the render array for the page, you can't change the ordering.

As a stupid American :) who doesn't really understand all of the implications of localization and internationalization, I cann't comment whether the Drupal behavior is by-design or is a bug.


Change script in preprocess Possible Duplicate:
  How do I update jQuery to the latest version I can download?

I need to upgrade jQuery from 1.5 to 1.7 in Drupal 7.

In Drupal 6 I could implement a hook_preprocess_html() function and alter the $variables['scripts'] to do this; but after inspecting $variables in Drupal 7, I can see there is no index called 'scripts'.

How can I do the same thing in Drupal 7?

It's not a good Idea to change manually the jQuery lib of drupal , because It can cause lot of bugs , instead of this use jquery update module


mysql server gone away while loading drupal site in the shared environment i am getting serious error in the production server when i deploy for the first time. Please find the below PDO exception which i am getting.

PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away in variable_set() (line 977 of /var/www/htdocs/includes/bootstrap.inc).

I am not allowed to increase allowed packet size and wait timeout in the mysql end, because multiple sites are running on the DB and such a way we are not allowed to change php.ini also.

Is there any other solution for this problem I am facing this issue with the client for past one week not it has been very critical for me.

Could anyone please help me out to get ride of this issue? Thanke in advance.

Increase max allowed packet size is the only proper way of doing this.
If your host doesn't allow you to change values in your multi-site environment simply change the host because you could experience a lot more problems overtime if you're not allowed to change anything!
A quickfix solution could be to limit the number of activated modules and by this limit the number of queries executed on page loads.


Firing a Ctools Modal on a link click Once again, I am stuck asking questions on CTools that people have asked a million times before. I have a view that displays a list of custom-developed entities (built with ECK) and each one has a link that should show a Ctools-driven modal.

I looked at a few approaches (namely this) to explore any method to get Drupal to display said modal. I figured that I didn't need all this extra views hook logic to fire the modal -- ideally, if a hook_menu() click is fired, it should open the modal and any contents I send to it (which will be done through additional methods). Right now, it treats the logic as a static route, and returns the results as a page. I also explored using the Ctools Auto Modal module (seen in the example, which reflects current code), which also returns the same results when used as documented.

I'm completely lost here, mostly because of the reach of Ctools and the various conflicting forms of documentation on its use for something simple as a tie in for hook_menu(). The long hours i've been pouring into this project are clearly having a toll on my ability to implement this, does anyone have any insight?

The actual logic is below:

/**
 * Implements hook_menu()
 *
 * The sole item call in hook_menu is driven from a URL that is built
 * Within a view, from rewrite rules. When activated, it should render
 * the new modal window.
 */
function example_menu() {
  $items['selectbook/%'] = array(
    'title' => "Perk Modal",
    'page arguments' => array(1),
    'page callback' => 'example_modal_page',
    'access arguments' => array('view content'),
    'access callback' => TRUE,
    'modal' => TRUE,
  );

  return $items;
}

/**
 * Returns a test modal
 */
function example_modal_page($js = null, $attribute = null) {
  return "Test Modal"; //Right now returns as new page call not as a modal
}

You mentioned you tried ctools_automodal which is a quick way to accomplish creating a link in a view to open in a modal. With the module, you can use hook_menu_alter to add 'modal' => TRUE to the link menu router item. Nothing else is involved. Ctools_automodal handles all the rest. That means you don't need your own example_modal_page page callback, and you don't need to call ctools_modal_render. Let the Ctool_automodal module do that for you.

If your path has a wildcard, then ctools_automodal will need an actual wildcard variable defined and a "_load" function. In your example above, your path is selectbook/%. If you change it to "selectbook/%selectbook" and defined a selectbook_load function then ctools_automodal should recognize it as a modal path. Here's an example:

/**
 * Implements hook_menu().
 *
 * The sole item call in hook_menu is driven from a URL that is built
 * from rewrite rules within a view. When activated, it should render
 * the new modal window.
 */
function example_menu() {
  $items['selectbook/%selectbook'] = array(
    'title' => "Perk Modal",
    'page arguments' => array(1),
    'page callback' => 'example_modal_page',
    'access arguments' => array('view content'),
    'modal' => TRUE,
  );

  return $items;
}

function selectbook_load($selectbook) {
  // Todo: Do something with selectbook, like load an entity.
  // For this proof of concept, just return it.
  return $selectbook;
}

function example_modal_page($selectbook) {
  // If you loaded an entity in selectbook_load, then you have that
  // fully loaded entity in $selectbook.
  return "Test Modal";
}


Where do i change the settings of the redirected URL after a new user registers on my drupal 7 site? Where can i change the destination of the redirect after a user registers on my site? Currently it just hits them back to the homepage.

Hope this will help you,

In Drupal 7 you can achieve it many ways

Using Rules, create a RULE with Event - After saving a new user account and Actions - redirect the page and if you want you can also add Conditions, as per your requirement.

Using hook_form_alter

function HOOK_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'user_register_form':
      $form['#submit'][] = 'custom_user_register_submit';
    break;
  }
}
function custom_user_register_submit($form, &$form_state) {
 $form_state['redirect'] = 'YOUR_REDIRECT_PATH_HERE';
}

By using destination parameter

More simpler you can also using destination parameter. Just add
the destination parameter in the URL where you want to redirect
it. You can achieve it by using theme_menu_link. You can refer this answer
YOUR_DOMAIN/user/register?destination=YOUR_REDIRECT_PATH_HERE

Note : Instead of writing the code or installing the module you can use  Destination parameter OR RULES .


Drush Feature Update removing t() and l() function usages I have a feature that currently has things like this:

'body' => '
' . t('Welcome back') . '%user:field_first_name!
',

However, using drush fu myfeature generates this:

'body' => '
Welcome back%user:field_first_name!
',

Why is this happening? (removal of t() and l() functions).

I did not create this original feature.

Isn't this a simple as the PHP code being executed? The original feature is created so it supports any language by translating text with the "t" function. However, when the feature is activated, just the text - the executed PHP code - is written to the database (for the given langauge), and you can't ever get back the original PHP code. A feature update will just return the string in the database.


Create a Gmap with Views that connects locations of different nodes I am looking for a way to make some sort of roadtrip website.

The idea is to use two node types: a parent nodetype "Roadtrip" and a child nodetype "Day". The user can create a Roadtrip and add a different Days to the Roadtrip. Every "Day" have a location field that needs to be filled in.

Then, I want to use Views with a Gmap display that I show on the parent Roadtrip node page using contextual filters. On that map, I want to show all the locations of the different Days and connect them to eachother in ascending order by publish date. So visually, you can see which trip someone made in how many days.

I am quite familiair with Views but can't wrap my head around Gmap and it's API so, anyone an idea how to achieve this?

This answer is for D7, you'll need the folowing modules: entityreference to relate both contentypes,
 geolocation_views only D7, it displays several nodes in a single map, geolocation, and simple_gmap, this one is for for users to enter city name in a text field, handy tutorials: https://www.youtube.com/watch?v=hdzembWMgPc and https://www.youtube.com/watch?v=Pc0xPiRBb54 and https://www.youtube.com/watch?v=FVvKJlq4Wo8, you will end with something like this, each mark in map links to your day-node, enjoy.


Best Drupal module for mailing lists? I am working on a Drupal based site for a church and one of the items is a method for each group to have discussions.

I immediately thought OG would be a good fit but after consideration I'm not sure it will be enough by itself.

The goals are:

1.)  Users will be able to join a group or groups.

2.)  Each group will have private content for members only.

3.)  Each group will also have a mailing list for 2-way communication (so I don't believe SimpleNews will work).  Ideally, when a user is approved to join a group they will also be subscribed to that groups mailing list.

OG will be a good fit for the first 2 items.

I'm not sure about the third.

I've used Mailman in the past but it appears the mailman modules for Drupal are limited to Drupal 6.

What is the best way to achieve this in Drupal 7?

Use the Message module along with the message notify module. Message module is Drupal 7's answer to activity-streams and a flexible Messaging & Notifications system.

http://drupal.org/project/message
http://drupal.org/project/message_notify


Is it possible to create web service CRUD operations for contributed modules in drupal 7? I have using a privatemsg module for chating in our site,

Privatemsg

Services

Is it possible to do a web service CRUD operations through this module?

any suggestions?

Yes, the Services module has an API, details of which you can find in the module files. You can use that API to provide CRUD for anything at all. See Creating a resource for Services 3.x for a full module example.

Since private messages are entities, you might also look to the Services Entity API module for inspiration (or, it you're particularly lucky, a pre-built solution, depends what you need, and whether you can use an alpha release):

  This module provides support for all Entity API entity types to Services. All entity types get a standard resource, similar to what Services provides for code entity types such as nodes.


View to display nodes with a random term I have got a view that selects some images. Each image is tagged with a taxonomy term. I would like the view to display only images tagged with a common term that is chosen randomly at every use.

The view is used as a block.

Example:
term: a, images: img1, img2, img3;
term: b, images: img4;
term: c, images: img5, img6;

One user sees a sequence of img1, img2 and img3. Another one sees img4 only. A next one sees img4 too.

How should I do it?

I would set up an argument (D6) / contextual filter (D7) to filter the view results based upon a taxonomy term, and then for the argument/filter value, select the PHP option for providing the default, and in there randomly return one of your taxonomy terms.  Without actually testing the code, I would imagine using array_rand() would make this rather trivial, eg:

$terms=array('foo','bar','baz');
return $terms[array_rand($terms)];


Is making a feature of literally everything available actually a smart thing to do? I love features for all the benefits they have, especially for performance.

It now seems like a logical step forward to make a feature out of everything available on the "create feature" page on a launch site and enable it (of course so that it doesn't interfere with other features, but you get my point).

Does that seem like a smart idea? I don't see anything problematic with this if I assume I won't change anything on the site for the next couple of days and it's frequented by many visitors.

If you have any best practices to share, I'd be glad as well.

Yes.

Combined with placing your Feature module(s) in version control and carefully reviewing the diffs, this is a good way to keep track of administrative changes to the sites you maintain.  I do this on most sites I maintain.

However:

If you're using Strongarm, you shouldn't export literally everything.  Some system variables are caches, and will change frequently; exporting these caches to a Feature module will just cause the Feature to appear overridden all the time, without providing any maintenance value.  Over on this answer I provided a list of variables to exclude.
I wouldn't expect Features to increase performance, though.  I elaborated on that over here.


How to let public access to the sitemap page? I am using the Site map module that creates a page called sitemap. However, I cannot access it if I am not logged in, as the access is denied for that page for the anonymous users.

How can I let public access to the sitemap page?

As far as I can tell, this is permission based, so you need to give anonymous users the access site map permission.

From the module:

/**
 * Implements hook_permission().
 */
function site_map_permission() {
  return array(
    'access site map' => array(
      'title' => t('View published site map'),
    ),
  );
}

/**
 * Implements hook_menu().
 */
function site_map_menu() {
  $items['admin/config/search/sitemap'] = array(
    'title' => 'Site map',
    'description' => 'Control what should be displayed on the site map.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('site_map_admin_settings_form'),
    'access arguments' => array('administer site configuration'),
    'file' => 'site_map.admin.inc',
    'type' => MENU_NORMAL_ITEM,
  );
  $items['sitemap'] = array(
    'title' => 'Site map',
    'description' => 'Display a site map with RSS feeds.',
    'page callback' => 'site_map_page',
    'access arguments' => array('access site map'),
    'type' => MENU_SUGGESTED_ITEM,
  );

  return $items;
}


All the additional tags Drupal 7 adds Not being a developer per say, I am responsible for converting the PSDs into HTML, CSS & Js. Our Drupal Web Developer doesn't know the answer to this question so I hope someone here can answer it for me.

After handing over the HTML, CSS & Js file to the developer, this is what he brought back. All the lines of code you see in the firebug that is not green highlighted is Drupal 7 generated (we are using Adaptive Theme with sub-theme Sky which we are further modifying).

I dont understand what all these (& they are a lot) divs do, what purpose they serve.

Are they generated in every Drupal website & is code we should not be worrying about or are we doing it all wrong?

This is standard Drupal behaviour, but you can change it using one of the following modules:

http://drupal.org/project/fences
http://drupal.org/project/ds

they both allow you to override the amount of outputted html tags


How to cache a paged list? I have a list which is built by consuming an API. The data that comes from response is not stored in Drupal which mean I am using views to create the list. The list is a paged one which shows 10 items at every page. How can cache each page of the list?

What I am thinking of is setting the cache name with a variable of the page.

\Drupal::cache()->set('cache_demo_page_'.$page, $posts, CacheBackendInterface::CACHE_PERMANENT);

This will lead to a lot of cache entries as there will be 100s of such pages in many lists across the site.

What should be the best way to do this?

Yes, having hundreds of pages also results in hundreds of caches. Not just for your cache, but also for any block that varies per URL.

That's how it is, no way around it. Except not caching at all.

Note that with remote content, you need to think about cache invalidation (Well, you need to think about that anyway, but it's different with reomote content). You have two options:

Use a short cache expiration time. That also helps with the amount of cache entries, as they will get deleted when they are expired
Or you need to find a way to get notified when changes happen in the remote system or check for changes in a background process to invalidate your cache entries.


Create a simple date formatter to be used in views I am using Views Data Export to create a custom RSS feed that looks like

   My Title
   2012-05-12 22:33:00

Start date is a Date field provided by the Date module.

In order to achieve the date formatting on the second field I have to use the Plain formatter from the Date module to avoid theming tags. Unfortunately plain formatting, gives the raw date as stored in the DB ignoring timezone settings.

I have created a custom field formatter module to tackle this:

/**
* Implements hook_field_formatter_info().
*/
function rss_date_formatter_field_formatter_info() {
    return array(
        'rss' => array(
          'label' => t('RSS'),
          'description' => t('Displays a date as rss.'),
          'field types' => array('date', 'datestamp', 'datetime'),
    ),  );
}

/**
 * Implements hook_field_formatter_view().
 */
function rss_date_formatter_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
    $element = array();
    $settings = $display['settings'];
    $formatter = $display['type'];
    foreach ($items as $delta => $item) {
        $element[$delta] = array('#markup' => $item['value']);
    }
    return $element;
}

Problem is that no matter what I cannot set $element to return the localtime. $item['value'] contains a string of the date representation as it is stored in the DB (thus UTC). Converting it to a date and then back seems to output nothing. Also if I hardcode a string there, it seems the string is altered but I cannot find from which function this happens (eg. entering 'test' in the #markup returns '1est', like converting the first letter to a valid month (1-12).

Any clues on this? I never thought outputting a date in localtime without theming would be so hard.

You should:

Create a new date format: /admin/config/regional/date-time/formats
Create a new date type that uses the format you just created: admin/config/regional/date-time
Use that date type in view.


I want to use this script in Omega subteheme I want to use this script in my Omega sub-theme. How do I do it?

Short Answer: themename.info or drupal_add_js().

Long answer: If you always want it to load just use the info file and add a [js] entry. Google can help you there.

Depending on when you'd like that JS to load you might want to define it only when nodes of a certain type are displayed, etc. This changes where you put drupal_add_js() in your template.php.

If you want it only when you display nodes then stick it in THEMENAME_preprocess_node() and you can use the $vars in there to conditionally load it on a particular node type only, etc


filtered_html in theme-settings.php In my theme-settings.php i want to set text format to 'filtered_html' and display in page.tpl.php.

I used this code to display text area:

$form['options']['description'] = array(
'#type'          => 'textarea',
'#title'         => t('Description'),
'#default_value' => theme_get_setting('description'),
);

And display it using <?php print strip_tags(theme_get_setting('description')); ?> in page.tpl.php

How do i set the textarea to use 'filtered_html' format

Try this:

$form['options']['description'] = array(
'#type'          => 'text_format',
'#title'         => t('Description'),
'#default_value' => theme_get_setting('description'),
'#format'        => 'filtered_html',
);

https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7.x/#text_format


Can the Feeds module work with get parameters? Is there a way that I can use the Feeds module in Drupal 7 to connect to an API which requires specific get parameters to interact with?

The reply that the API gives will be in a simple XML format. The valuable information will be included in Content. This data will be in JSON format. I want to use this data to be put in a form which users can edit and submit back to the (API) server.

Is this possible? If not, what other solution can you recommend me?

By default, the Feeds importer is set to file upload, but you can set it up to fetch data using an HTTP request.

On the settings page for your importer, click the Change link next to Fetcher in the left menu.
Select the radio button for HTTP Fetcher and hit the Save button
Visit /import and click on the link for your importer.

There will be a field there where you can enter the URL you want it to retrieve data from.


Field depandancy module can not work for textfield in field collection I am using field dependency module for use only 1 field

I have 2 fields text and image user can use only 1 field text or image if user can select text field other will be hidden or invisible
same case with image to text field

here is conditions:

case 1:

Dependent:Image (field_image)
Dependees:Text (field_text)
Description:Image is invisible when Text is filled.

case 2:

Dependent:Text (field_text)
Dependees:Image (field_image)
Description:Text is invisible when Image is filled.

case 1 is working perfectly but case 2 is not working.

You can use Conditional Fields module which define dependencies between fields based on their states and values. Conditional Fields allows you to manage sets of dependencies between fields.

Thank you.


How to prevent granting Userpoints again after a user already passed a Quiz? I'm using the Quiz and the User Points module.

After a user takes a quiz, the points are granted. But if the quiz is taken multiple times, the points are granted multiple times also. For example;

points balance: 0
after quiz (1st time), point balance: 10
take the same quiz again, point balance becomes: 10+10=20

I don't want it to be cumulative. How can I prevent this?

You might use the Rules module to take away the role which has the permission to take the quiz once the quiz has been completed.