title: node add save in ctools modal fails

text:
# Question
Title: node add save in ctools modal fails
I'm writing a module to get a simple node add form into a ctools modal dialog. I get the form into the modal ok, but when I click save I get this ajax error

An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging information follows. Path: /itin-add1/ajax StatusText: Service unavailable (with message) ResponseText: EntityMalformedException: Missing bundle property on entity of type node. in entity\_extract\_ids() (line 7721 of /mnt/p0/data/www/docroots/mkm/includes/common.inc).

I've tried several examples, currently working with this one http://deeson-online.co.uk/labs/insert-form-pop-modal-ctools-and-drupal-7

I've also been examining the modal\_forms module and it appears to be doing basically the same thing as the link above. As I say I get the form to appear in the modal ok, but saving the form fails. I've yet to find a good complete example of a node add in a modal.

I appreciate any advice or pointers to a good example of node add in a modal.

Thanks

```
<?php

# testmodal module

function testmodal_ctools_render_alter(&$info, &$page, &$context) {
  $data = array_values($context['contexts']);
  if (is_array($data) && count($data) && property_exists($data[0], "data")) {
    testmodal_node_view($data[0]->data, 'full', '');
  }
}

function testmodal_node_view($node, $view_mode, $langcode) {
  ctools_include('modal');
  ctools_modal_add_js();
}

# Insert a form into a pop-up modal with CTools and Drupal 7
# http://deeson-online.co.uk/labs/insert-form-pop-modal-ctools-and-drupal-7

function testmodal_menu() {

# We dont' need this. Our popup links appear on the /products page
#
# 1. "/mymodule/page" - A page that a user might travel to and see the
# link that, when clicked, will cause a modal to popup with the form in it.
# 2. "/mymodule/%ctools_js" - The second is a callback which returns the HTML of
# the modal form. The second argument is a variable. It's value will be either "nojs",
# if the users browser does not handle JavaScript, or "ajax" if it does.

  $items['itin-add0'] = array(
    'page callback' => 'testmodal_form',
    'title' => "hook",
    'access callback' => TRUE,
  );

  $items['itin-add1/%ctools_js'] = array(
    'page callback' => 'testmodal_callback',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

# 3 link generator - don't need it it's for their example
# 4 page call back - need to determine correct hook to load
#               ctools_include('modal');
#               ctools_modal_add_js();

# 5. Define the ajax callback
# This is what runs when the user's browser makes a request to either "/mymodule/nojs" or
# "/mymodule/ajax". In the case of nojs, the full form must be returned as normal. In the
# case of "ajax", the ajax delivery system sends back the information on creating a modal.

function testmodal_callback($ajax) {
  ctools_include('modal');
  ctools_modal_add_js();

  if ($ajax) {
    $form_state = array(
      'ajax' => TRUE,
      'title' => t('Itinerary Item Add Modal Form'),
    );

  // Use ctools to generate ajax instructions for the browser to create
  // a form in a modal popup.
    $output = ctools_modal_form_wrapper('testmodal_form', $form_state);

  // If the form has been submitted, there may be additional instructions
  // such as dismissing the modal popup.
    if (!empty($form_state['ajax_commands'])) {
      $output = $form_state['ajax_commands'];
    }

  // Return the ajax instructions to the browser via ajax_render().
    print ajax_render($output);
    drupal_exit();
  } else {
    return drupal_get_form('testmodal_form');
  }
}

# 6. Create an example form The next thing to do for this example is to create
# the form and its submission function. In 5 above, we told ctools the forms name
# was "mymodule_form", so lets create that form now with a textfield and a submit
# button. You'll note that there is nothing special about the form itself and any Drupal
# form could therefore be used.

function testmodal_form() {

        global $user;

        module_load_include('inc', 'node', 'node.pages');

        $node_type = 'itinerary_item';
        $form_id = $node_type . '_node_form';

        $node = new stdClass();
        $node->type = 'itinerary_item';
        node_object_prepare($node);
        $node->language = LANGUAGE_NONE;
        $node->body[LANGUAGE_NONE][0]['value']='';
        $node->uid = $user->uid;
        $node->title = 'testmodal title';

        $node->status = NODE_PUBLISHED;
        $node->promote = 0;
        $node->comment = 0;
        $node->active = 1;

        $form = drupal_get_form($form_id, $node);

        return $form;
}

# 7. Create the submission function When submitting the form we want to send back
# ajax commands to the browser to dismiss the modal and change the text on the link we
# clicked. You can see the ajax_command_replace function is targeting the div with the
# id set by our helper function back in 3. In situations where you are not using your
# own form but some other in the Drupal system you might need to add additional ajax
# actions by including your own submission functions to the form.

function testmodal_itinerary_item_node_form_submit($form, &$form_state) {
#  $form_state['ajax_commands'][] = ctools_modal_command_dismiss();
}

/**
 * Drupal form submit handler.
 */
function itinerary_item_node_form_submit($form, &$form_state) {
// Generate the new link using the submitted text value.
#  $link = _mypopup_make_link($form_state['values']['new_link_text']);

// Tell the browser to close the modal.
  $form_state['ajax_commands'][] = ctools_modal_command_dismiss();

// Tell the browser to replace the old link with the new one.
#   $form_state['ajax_commands'][] = ajax_command_replace('#magical-modal-link', $link);
}

```

# Answer
> 4 votes
Here is my testing code (`custom.module`). Works fine:

```
function _my_module_includes_modal() {
  static $added = FALSE;
  if ($added == FALSE) {
    $added = TRUE;

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

    $custom_modal_style = array(
      'custom-modal-style' => array(
        'modalSize' => array(
          'type' => 'fixed',
          'width' => 800,
          'height' => 'auto',
          'addWidth' => 20,
          'addHeight' => 20,
          'contentRight' => 20,
          'contentBottom' => 20,
        ),
        'modalOptions' => array(
          'opacity' => (float) 0.6,
          'background-color' => '#000000',
        ),
        'closeText' => 'Close',
        'loadingText' => 'Loading data...',
        'animation' => 'fadeIn',
        'animationSpeed' => 'fast',
        'modalTheme' => 'my_module_modal',
        'throbberTheme' => 'my_module_throbber',
        'throbber' => '',
      ),
    );

    drupal_add_js($custom_modal_style, 'setting');
  }
}

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

  $items['my-path/%ctools_js'] = array(
    'title' => 'Node Form',
    'page callback' => 'nodeFormCallback',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function nodeFormCallback($js = NULL) {

  global $user;

  if (!$js) {
    drupal_access_denied();
    drupal_exit();
  }

  ctools_include('node.pages', 'node', '');
  ctools_include('modal');
  ctools_include('ajax');

  $node_type = 'tets'; //This is my content type. You need to change this to yours
  $node = (object) array(
    'uid' => $user->uid,
    'name' => (isset($user->name) ? $user->name : ''),
    'type' => $node_type,
    'language' => LANGUAGE_NONE,
  );

  $form_state = array(
    'title' => t('NODE FORM'),
    'ajax' => TRUE,
  );

  $form_state['build_info']['args'] = array($node);
  $commands = ctools_modal_form_wrapper($node_type . '_node_form', $form_state);
  if (!empty($form_state['executed'])) {
    $commands = array();
    $commands[] = ctools_ajax_command_redirect('<front>', 1000);
  }

  print ajax_render($commands);
  exit;
}

// This is just an output for modal link.. You can generate it differently
function custom_block_info() {
  $blocks['custom_node_modal'] = array(
    'info' => t('Node Form'),
    'cache' => DRUPAL_NO_CACHE,
  );

  return $blocks;
}

function custom_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'custom_node_modal':
      $block['subject'] = t('Node Form ');
      $block['content'] = custom_node_modal_content();
      break;
  }

  return $block;
}

function custom_node_modal_content() {

  // This function must be called in that places where your link is located.  Or even you can call it globally in hook_init() or template_preproccess_page() fnctions
  _my_module_includes_modal();

  $output = array();
  $output['custom_modal'] = array(
    '#markup' => ctools_modal_text_button(t('OPEN'), 'my-path/nojs', t('My Path'), 'ctools-modal-custom-modal-style'),
    '#attached' => array(
      'js' => array(
        drupal_get_path('module', 'custom') . '/custom.js' => array(
          'type' => 'file',
          'group' => JS_DEFAULT,
        ),
      ),
    ),
  );

  return render($output);
}

```

And JS (`custom.js`):

```
(function($) {
    Drupal.behaviors.CUSTOM_MODULE = {
        attach: function (context, settings) {

            Drupal.theme.prototype.my_module_modal = function () {
                var html = '';
                html += '<div id="ctools-modal" class="popups-box">';
                html += '  <div class="ctools-modal-content ctools-sample-modal-content c">';
                html += '     <div class="popups-container">';
                html += '       <div class="modal-header popups-title">';
                html += '        <span id="modal-title" class="modal-title"></span>';
                html += '        <span class="popups-close"><a class="close" href="#">' + Drupal.CTools.Modal.currentSettings.closeText + '</a></span>';
                html += '         <div class="clear-block"></div>';
                html += '         </div>';
                html += '         <div class="modal-scroll"><div id="modal-content" class="modal-content popups-body modal-content-fixed"></div></div>';
                html += '         <div class="popups-buttons"></div>';
                html += '         <div class="popups-footer"></div>';
                html += '      </div>';
                html += '  </div>';
                html += '</div>';
                return html;
            }

            Drupal.theme.prototype.my_module_throbber = function() {
                var html = '';
                html += '  <div id="modal-throbber">';
                html += '    <div class="modal-throbber-wrapper">';
                html +=        Drupal.CTools.Modal.currentSettings.throbber;
                html += '    </div>';
                html += '  </div>';

                return html;
            }
        }
    };
})(jQuery);

```

I'll explain a little what's going on here :)

1. We created a custom module. Tutorials can be found here;
2. added Ctools' required files and our custom style with `_my_module_includes_modal()` function and sent our style's settings to javascript;
3. created router with hook\_menu and specified its action (callback) as `nodeFormCallback`. In `nodeFormCallback` action we generated empty node object of our type and added to `form_state` array as argument and passed it to ctools\_modal\_form\_wrapper function which wraps the form so that AJAX can be used properly;
4. specified our custom style's template in `custom.js` file. `my_module_modal` and `my_module_throbber` elements of Drupal object are coming from `_my_module_includes_modal()` function;
5. we finished all the requirements of ctools modal, now we can generate our link which will fire our modal. LInk can be generated with  function but the easist way is to use ctools\_modal\_text\_button function which includes modal classes to anchor tag. There are many ways to display it, it's up to you.. you can create a block with hook\_block\_info and hook\_block\_view hooks or put it into template file, etc. But don't forget to call `_my_module_includes_modal()` function in that place..

# Answer
> 0 votes
I think the down votes might have been because even though code that works was provided, there was no explanation as to what it was that was wrong with the previous code, or why it didn't work.

I ran into this same problem (with relations, not nodes) and and the answer for me was to use `drupal_build_form` instead of `drupal_get_form`.

Note that when passing parameters to `drupal_build_form` they need to be in the initial `$form_state` variable (second parameter), not added as an additional (third) parameter like in `drupal_get_form`. That may mean a little code tweaking, but in the end Drupal will stop complaining about missing entity bundles ;)

before: (does not work)

```
    $form = drupal_get_form('relation_ui_edit_form', $form_state, $relation);

```

after: (does work)

```
    $form_state['build_info']['args'] = array($relation);
    $form = drupal_build_form('relation_ui_edit_form', $form_state);

```

I'm still not entirely sure myself why using `drupal_get_form` doesn't work within modals (ajax) when that approach does work on stand-alone forms.

---
Tags: forms
---


# Question
Title: Form problem : calendar pop up overriden by an autocomplete field
Drupal 7. I use a bootstrap theme with some customized css. I have a node/edit form with a date field with calendar popup widget and an entityreference field with autocomplete widget.

When I click on the date field, a part of the calendar is missing : it is overriden by the autocomplete field.(see picture below)

If I change the widget for the entityreference field and choose select widget, the calendar is OK.

With the original bootstrap theme (without customized css), the calendar is OK.

Is there something I can change in CSS to prevent the calendar to be overridden by the autocomplete field ? (should I change the date css ? or the autocomplete css ?, which setting ?)

# Answer
Try:

```
input{
  position: relative !important;
  z-index: 0 !important;
}

```

You can change the "input" selector to meet your needs and try this without "!important" also.
> 0 votes

---
Tags: forms, theming
---


# Question
Title: What do I have to do to get hook_form_alter picked up?
Trying to move from Drupal 7 to Drupal 8. First step is to get a custom module with `hook_form_alter()` and the Devel module working so that I can see how bad I am messing things up.

To do so, I made a custom module with the following files.

**mymodule.info.yml**

```
name: My Module
type: module
description: "Custom module"
package: Custom
core: 8.x

```

**mymodule.module**

```
<?php

function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  dpm($form);
  print_r($form);
}

```

**Other steps**

* I enabled both the Devel module and this custom module.
* I gave anonymous users permission to view devel information.
* I made sure the Status block was enabled on the Block Admin page.
* I cleared all caches via the Pantheon admin interface.
* I tried using `print_r($form)`, `dpm($form)`, and `var_dump($form)`.

However, when I refresh `/user/login`, I don't see any output from `dpm()`, so the hook isn't getting picked up for some reason. What else do I need to do?

# Answer
It turns out this was something related to MultiDev, a Pantheon-specific feature. By cloning back and forth between the main dev branch and my multidev branch, I was able to get the custom `hook_form_alter()` to work.
> 0 votes

---
Tags: hooks, 8
---


# Question
Title: Field value not coming in template.php for published node
I am trying below code to get node field value into template.php.

```
$field_items = field_get_items('node', $node, 'field_read_more_title');
$variables['readmoretitle'] = $field_items[0]['value'];

```

But $variables\['readmoretitle'\] is empty for published node, for unpublished node I am getting correct value.

How can I get the published node field value in template.php?

# Answer
> 0 votes
The right way to doing this is `hook_node_view_alter(&$build)` where you can alter teaser link or any other $links. You reference from here

---
Tags: theming
---


# Question
Title: How does Drupal handle update of multiple module bundles of features without breaking stuff?
Let's say I have modules A, B and C.

I create a feature and it makes them into a single module.

Then one day, an update makes A, B and C not compatible, or maybe one deprecated or something.

Then my feature is broken...

Drush installs fresh modules of the newest version automatically, is there a way to do a drush command that bundles the modules inside the feature module?

# Answer
> How does Drupal handle update of multiple module bundles of features without breaking stuff?

It doesn't - that job falls to the developer.

Drupal/Drush doesn't know which versions of unrelated modules work with each other; I imagine that would probably be quite complicated to describe generically.

One method Drupal offers to handle this scenario is using advanced `dependencies` in your module .info file. For example, when you know that the current versions of A, B and C you have installed work with one another, then lock them down in your feature module's .info:

```
dependencies[] = A (1.x)
dependencies[] = B (>7.x-1.5)
dependencies[] = C (>1.0, <=3.2)

```

That way a Drush (or other) updates won't interfere, you'll always have versions that you've manually verified are compatible.

When you're ready to think about updating those modules, download them to your dev version of the site, run all the updates, and all of your tests, and see where you're at. If things work, great, update your .info file with the new dependency versions, release the code, and you're good to go.

If not, then you need to look into whether it's something that you need to fix yourself, whether it's a known bug with the new version and has a patch, a known incompatibility between the two modules, and so on. Beyond writing an excellent test suite that you can trust, I doubt there's an automated or shortcut method for doing this.
> 2 votes

---
Tags: drush, features
---


# Question
Title: Make link translatable in Admin from a PHP string in a tpl-file
In a custom `user-login-block.tpl.php` file i want to make a link in the *Create an Account* -button which links to `/doctor/register`. Here the link to the example page (*you are redirected to this page from specific nodes who needs permission* (by Content Access module).

How do i make this link in PHP so i am able to make it multilingual and translate it in `Administration » Configuration » Regional and language » Translate interface` to:

* `benl/doctor/register` (for Belgium dutch site)
* `befr/doctor/register` (for Belgium French site)

I think i need somehow the `base_url` because otherwise it gives the string from the restricted page (in this example `benl/producten/injectables`).

How do i manage this?

**Update:**

To make it more clear this is my HTML:

```
<div class="well">
    <a class="btn btn-large btn-primary" href="HERE THE LINK"><?php print t('Create an Account'); ?></a>
</div>

```

So where is written **HERE THE LINK** i have to insert the php-code.

# Answer
> 2 votes
You can use path aliases for this. Go to /admin/config/search/path/add and create a new alias with the following settings:

* Language: Dutch (or whatever it is called in your site)
* Existing system path: 'doctor/register'
* Path alias: 'dokter/registreer' (or whatever suits your fancy)

Repeat for the French site. Drupal core and contrib modules should automatically pick up the language-dependent aliases. If you're creating a link in a template yourself, make sure you use the l() function to build the entire `<a>` tag. To get the result in your question, you need something like this:

```
<div class="well">
  <?php
    $link_options['attributes']['class'] = array('btn', 'btn-large',' btn-primary');
    print l(t('Create an Account'), 'doctor/register', $link_options);
  ?>
</div>

```

---
Tags: 7, i18n-l10n
---


title: Content type or taxonomy term?

text:
# Question
Title: Content type or taxonomy term?
When we want some specification for a content, how should we decide whether to make that specification a separate content type or a taxonomy term?

For example, I had to build a music store site. The main content was music tracks, albums, label, music director, and producer. I made a content type (Music Tracks) and albums, label, music director, and producer were taxonomy terms which were given as entity references in the Music Tracks. Then, I was suggested to make the site scalable and thus making album, producer, and label a separate content type.

So how do content types help in making the website scalable?

# Answer
There are also other solutions to your problem.

# Field Collection

You can use field collection and field collection views modules to store and organize contents. Using this approach the `Issue` and `Magazine` are going to be Field Collection type, `Issue` is a field of `Article` and `Magazine` is a field of `Issue`. I have experience of implementing such structure. In my case the requirement was a `Library` that should contain books (with Title, Publisher and ... fields), Every book contains multiple volumes (Number of pages, translator, ... ) and each volume also contains unlimited number of some other items (like the scan of some pages that are not the same among the books).

I implemented this using Field Collection approach and it is very nice. You can easily create a link to edit every individual items of every field collection and you can also filter by items of field collection. I posted an answer to Group items in Views by value in Field Collection which shows how to work with Field Collection Views

# Entity View Attachment

Also known as EVA module.

> "Eva" is short for "Entity Views Attachment;" it provides a Views display plugin that allows the output of a View to be attached to the content of any Drupal entity. The body of a node or comment, the profile of a user account, or the listing page for a Taxonomy term are all examples of entity content.

*You can use EVA to display only fields values for a particular piece of content, giving incredible control over the display and formatting flexibility of the fields. For example you may desire to have two fields concatenated in some special way. You can add your fields to your EVA display, set the contextual filter to NID, add a Global: Text Field, and using tokens format your fields with HTML. Don’t forget to exclude your fields from display if you are going to use them together in a Global: Text Field. Example: You may have a city, state, and zip fields. You can combine them in a Global: Text Field in Views to display as “City, State ZIP”. When you manage the display for your content type add the EVA just created to the display and whenever a node the type is displayed it will pass its nid to the EVA and the EVA will return the fields you select, formatted as you desire. (source : EVA and Entity Reference Use Case How-to)*

This module is perfect, It attaches a View as a field to nodes of a content type. I used this module to create an `Album`. The album contains `singer` (with some information about each one) and `songs` that contains a File, Title, Rate and ... . So I created a View of type *EVA* and I attached it to a node. So on the node page of every Singer, I displayed this View which gets it's appropriate information from the node. The Views with Entity Reference is a perfect tutorial of how to use this module.

# Taxonomy Terms V.S Entity Reference

I recommend you to read Entity reference vs. taxonomy and Are there any benefits/caveats with using Entity Reference over Term Reference? , As it says *Taxonomies are best used when organizing similar items in a hierarchical fashion. Like tags*.

Taxonomy allows you to use free tagging (it can be disabled using **Content Taxonomy** module), which enables the creation of new tags on-the-fly. It is very easy to modify the skeleton of contents. Using this approach, regular or at least some authenticated users (who have no knowledge of programming) can change this skeleton. Hierarchical Select module is perfect example of such approach.

Even though Taxonomy is easy to use but I myself prefer Entity Reference, it opens up lot's of possibilities and scalability and allows of creation very complex structures. The concept of entity in this context is not limited to content. It can be comments, users, taxonomies and ... . It is much more scalable so you will not be worry about the customizing content types, or modifying it in the future (as it was pointed out in *Entity reference vs. taxonomy*). I believe the Entity approach is more powerful than Taxonomy.

There are also some other combinations of these approaches which it is unnecessary to mention them.

Anyway I recommend you fully understand Entity approach and it's related modules. If you use it in multiple projects, despite of it's complexity it will be very easy to you to use it. Not only in the yours current requirement but also in the future it is going to be a **Very Reliable Tool** for you.
> 1 votes

---
Tags: nodes, taxonomy-terms
---


title: Views 'OR' Operator acting as an 'AND'

text:
# Question
Title: Views 'OR' Operator acting as an 'AND'
This should be very easy, but I cannot figure out why this is not working?

* I have 2 different content types: Type1 & Type2
* I currently have a view which displays all nodes of content Type1.
* I would then like to manually add specific occurrences of Type2.
* So far, I have done this with a Taxonomy term reference field called TaxType (terms: Tax1 & Tax2)

I have set the view to filter by content Type1, which displays all fine. I then add filter for the Taxonomy Field with the operator of 'OR' but as soon as I add this, it stops showing content Type1?

I would expect this to happen if I left the operator as 'AND'. But with 'OR' it should keep showing Type1 or any occurrences of Tax2.

Drupal 7 Views 3.11

# Answer
> 0 votes
I'm not sure if i can help you out with out a screenshot cause i'm also new to Drupal. But my guess is the filters work in a different way from what you think. It might be something like this...

> Type1 AND (TAX2 OR xxx OR yyy .. etc.)

Hope this helps. Cheers!

---
Tags: views
---


# Question
Title: Make Backup & Migrate backups smaller in size
I have a 2MB upload cap on my school's server and get an error from backup and migrate that it cannot restore the file.

Is there any way the backups from backup and migrate module be compressed in some way and upload them when are needed?

I often take a backup before making new changes on the site and revert to the last one if I make a mistake or get an error, so ideally all files(DB and Directory) need to still be backed up...

# Answer
> 2 votes
Backup & Migrate module by default backs up all the data that is in your database. That includes cache\_%, watchdog, and other tables data that is not essential for a backup. By excluding data that lives in those tables from your backup (Advanced Backup settings) you can save a great deal of MB. Read more about tables recommended for exclusion here -Backup and Migrate exclusion recommendations?.

---
Tags: 7, backups
---


# Question
Title: Change weight of CSS file loaded in custom module with #attached?
Im working on a custom module which loads a CSS file:

```
$content['#attached']['css'] = array(
  path_to_theme() . '/new.css',
);

```

How can I change the weight of the file so that its loaded after the other CSS files? I thought it would be something like this:

```
$content['#attached']['css'] = array(
  path_to_theme() . '/new.css',
  'weight' => 1000,
);

```

Or this:

```
$content['#attached']['css'] = array(
  path_to_theme() . '/new.css',
  '#weight' => 1000,
);

```

# Answer
> 0 votes
You want something more like this:

```
$content['#attached']['css'] = array(
  array(
    'data' => path_to_theme() . '/new.css',
    'type' => 'file',
    'weight' => 1000,
  ),
);

```

---
Tags: theming
---


# Question
Title: How to add an existing variation to a product
How to add an existing variation to a product? When I create a product the form forces me to create a new variation, but I also want to add an existing one to the same product.

# Answer
Turns out I know what you're talking about Nikolaos, and you're in luck! There's a checkbox!

Here's an animated gif that walks you through the steps that I've outlined below:

1. Navigate to your Content Types
2. Manage Fields on your Product Display (you may have more than one of these)
3. Locate the Product Reference or Product Variations Field, click "Edit"
4. Scroll to the middle and locate the checkbox "Allow users to add existing variations"
5. ...
6. Profit!
> 0 votes

---
Tags: commerce
---


# Question
Title: Get blank value if field value is not available
I have following query on my D7 project

```
$query = db_select('payment_logs', 'p');
$query->join('field_data_field_frequency', 'd', 'd.entity_id = p.nid');
$query->join('field_data_field_maid_id', 'm', 'm.entity_id = p.nid');
$query->join('field_data_field_coupon_code', 'c', 'c.entity_id = p.nid');
$query->join('field_data_field_tip_amount', 't', 't.entity_id = p.nid');
$query->fields('p');
$query->fields('d', array('field_frequency_tid'));
$query->fields('m', array('field_maid_id_uid'));
$query->fields('c', array('field_coupon_code_value'));
$query->fields('t', array('field_tip_amount_value'));
$query->condition('p.section','booking','=');
$result = $query->execute();
$res = $result->fetchAll();
return $res;

```

this query returns data where `field_tip_amount_value` and `field_coupon_code_value` are available. I want to get all data with blank field values if not available. these two fields are optional other fields will be there always. so if tip or coupon is not there data must return blank for this field.

I was doing it with separate queries before but it was taking too much time with multiple loops. is there a way to get it done with join ?

# Answer
You can change `$query->join` to `$query->leftjoin`.

This will cause the query to return a row, even if there's no entry in the joined table.

Hope this helps.
> 2 votes

---
Tags: 7, database
---


# Question
Title: Feeds mapping to Entity ref by Entity ID not working
I’ve created a Feeds importer for a commerce product variation type. The product type is a commerce mp3 file. In it’s content type the mp3 refers to an album product. So in the Feeds mapping there is a target that reads ‘Album reference (Entity reference by Entity ID)’.

so far nothing has worked to get the mp3 product to refer correctly to it’s album reference. The album btw, is also a commerce product.

In my latest test example, the album name is ‘So Open’. I confess i’m not clear exactly on what an Entity ID is?! In looking at the Album on it’s Devel page i see the vid and nid are both 626.

my attempts have include the following: ’So Open’ -\> error, So Open (no quotes) -\> error 626.

This latter 626 does not generate an error but also does not populate the field correctly once the product is created. That ref. is simply left blank.

Perhaps the problem is I don’t understand what an Entity ID really is.

Does anyone know what i should be putting there? and how to find out that product’s Entity ID?

# Answer
> 1 votes
Might be important: Are the product displays (the albums) already in the site or are you importing those as well?

Entity IDs are generic unique identification numbers that entities use to reference each other. Nodes are a certain kind of entity and their id is "Node ID" but you are looking for the Product ID, which, Kickstart 2 does a really good job of hiding from the site builder. Try going to `admin/commerce/products/variations` to see all your products and when you click edit on one, the number in the url is your entity id for that product.

So, when you create an album with mp3s, the structure looks like this:

```
Album (node id: 123)
  |__ commerce_product (field), Value: 23,24,25

MP3-1 (product id: 23)
MP3-2 (product id: 24)
MP3-3 (product id: 25)

```

All of the "id"s are entity ids.

Regardless, you can use the entity field query finder function of the feeds\_tamper module to locate an entity reference while importing a CSV using Feeds.

---
Tags: commerce, feeds, importing-exporting
---


# Question
Title: How can I set an API key, which contains equal sign set at Drush site-install?
When I use the drush site-install command and a form value contains the equal sign (an API key for example), then Drush cuts the value at the equal sign. For example:

> drush si -y profile\_name --account-name=... --account-pass=... --db-url=mysql:... form\_name.field\_name="e+gklgfssdk=jgfsfg/11iXP6VJM0MjDpRk2MEKyc="

The value of the form\_name.field\_name at install will be "e+gklgfssdk", the last characters are missing, Drush cuts the value at the equal sign. This is a bug? Or how can I set the correct value?

# Answer
It looks like there isn't a way to do this, actually. The site installation code splits the string on the '=' and doesn't do any unescaping nor does it look like it would support this. I haven't tried `escape()`ing the value and then passing it in (so that `=` would become `%3D`) but unless you were expecting an escaped value this would probably still not work.

Depending on what you're setting, your best bet might be to do some sort of `drush variable-set` and set the values after the site install completes.
> 0 votes

---
Tags: drush
---


# Question
Title: Does having too many cck fields negatively affect site speed and performance?
I building a site that could potentially utilize 50 different content types. The most of the content types have more than 40 CCK fields, including multiple field\_collections entity\_reference.

How can i take care about performance of site Specially for CCK fields level ?

# Answer
Yes. The more fields you have, the more load you should expect on your database server; that's a given.

What it means in real terms depends on your hardware, configuration and usage - you'll need to benchmark your site in that actual environment to come to any meaningful conclusion. If you get one request a day, for example, your pages are cached, and you have a brand new shiny server, then you probably won't need to think about changing anything.

If you get thousands of requests per second, all your pages are non-cacheable, and your server isn't great, then you might have to think about re-structuring that data so it's more performant (e.g. creating custom field types to combine data from multiple other field types into a single table).

In short, there's no general answer to what you're asking. You need to see what problems your application develops under load, if any, and deal with them then. Premature optimisation is rarely a good idea.

All of that said, Drupal's main defence against this kind of thing is caching. There's a great post here: How do you improve Drupal performance?
> 1 votes

# Answer
This is the sort of question that's almost impossible to answer without benchmarking on your actual hardware. Sure, the number of content types and CCK fields will affect performance, but if most of the activity is browsing by logged out visitors, the page content can be cached, so displaying the pages should put relatively little strain on your server. On the other hand, if they are highly dynamic pages constantly being updated my multiple users, you could find your server is quickly dragged to its knees.
> -1 votes

---
Tags: performance, entities
---


# Question
Title: How to create a "read more" button using AJAX in a module?
I'm working on a really simple module in Drupal 8 to get the hang of things. What it does (or rather, what the page I'm asking about in this question does) is grab some data of a bunch of simple article-style entries, and display them.

What I would like to be able to do is to have it only display the first few (say, 5), and then have a "Read more" button, which uses AJAX to display the next 5, lengthening the page so it now shows 10.

Here is the controller as I have it at the moment. The `routing.yml` file points to `MyController::build`. For the sake of simplicity, I've left out exactly how it gets things from the database, and some simple processing (in particular, `image` gets converted from a `managed_file` in the database into a URL to the image).

```
class MyController extends ControllerBase {

  public function build() {
    $stuff = $this->getStuff();
    return array(
      '#theme' => 'my_theme',
      '#stuff' => $stuff,
      '#attached' => array(
        'library' => array(
          'my_theme/style',
          'my_theme/readmore',
        ),
      ),
    );
  }

  private function getStuff() {
    $stuff = getStuffFromDatabase();
    $result = array();
    foreach($stuff as $key => $item) {
      $tmp = new \stdClass();
      $tmp->id = $item->id;
      $tmp->title = $item->title;
      $tmp->description = $item->description;
      $tmp->image = $item->image;
      $result[] = $tmp;
    }
  }
}

```

Which then gets sent to a template file:

```
<section>
  <ul>
    {% for item in stuff %}
      <li>
        <h3><a href="stuff/{{ item.id }}">{{ item.title }}</a></h3>
        {% if item.image is not empty %}
          <a href="stuff/{{ item.id }}">
            <img src="{{ item.image }}" />
          </a>
        {% endif %}
        {% if item.description is not empty %}
          <p>{{ item.description }}</p>
        {% endif %}
      </li>
    {% endfor %}
  </ul>
</section>
<form method="post" action="" onsubmit="readmore()">
  <button name="read-more" type="submit">Read more</button>
</form>

```

What I want is a way to change this set up so that at first the controller only sends a few of the entries, but when the button is pushed, it sends the next few, and the template displays the new ones as well as the old.

Thanks

---

Okay, I *think* I may have worked out to at least make a start on this problem. I've followed this tutorial, and want to get a small message displaying at the bottom, to at least get a feel for how Ajax works with Drupal 8. I've added

```
<div id="current-msg">
  <h2></h2>
  <p></p>
</div>

```

to the bottom of the `.html.twig` file.

I created a file identical to his `ReadMessageCommand.php`, except named mine `MyMessageCommand.php` (and renamed the class inside it accordingly). The function render has `myMessage` in place of `readMessage`.

I added a method called `myMessageCallback` into `MyController`, which works the same as in that guide, but with `my_module_load_message` and `MyMessageCommand` in the appropriate places.

To `readmore.js`, I added the function from the above guide, but with `readMessage` replaced by `myMessage`. I also added the following, just so I can know more easily if the function is at least being called.

```
console.log(response.subject);
console.log(response.content);

```

And I added the `core/drupal.ajax` dependency to the readmore library.

My question is, how do I actually get this function to be called. As far as I can tell, the guide that I've used has no indication of it. How to I get a message to be displayed in the div at the bottom? Once I've figured that out, I feel extending it so that the button acts as a "read more" shouldn't be *too* much trouble.

# Answer
That tutorial won't help you. That's for more advanced stuff.

I would not use a form, but a simple link with an ajax response.

But if you want to use a form you need to create a proper Drupal form. Too much to write here to explain that so just take a look here https://www.drupal.org/node/2117411

Your buildForm should be something like

```
/**
 * {@inheritdoc}
 */
public function buildForm(array $form, FormStateInterface $form_state) {
  // The default value for working with non JS should be taken from the route and adding 1.
  $form['page_number'] = array(
    '#type' => 'hidden',
    '#default_value' => 0,
  );
  $form['my_stuff'] = array(
    '#type' => 'value',
    '#value' => [],
  );
  $form['actions']['#type'] = 'actions';
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => $this->t('Read more'),
    '#button_type' => 'primary',
    '#ajax' => array(
      'callback' => 'Drupal\example\Controller\MyController::myFormSubmit',
    ),
  );
  return $form;
}

```

You can call this form in your page with (changing accordingly):

$form = \Drupal::formBuilder()-\>getForm('Drupal\example\Form\ExampleForm');

You do all the stuff you want in your submitForm, and not in the callback if you want the form to work without JavaScript. If you don't care you can do in the ajax callback. I will assume you do it in the submitForm.

```
/**
 * {@inheritdoc}
 */
public function submitForm(array $form, FormStateInterface $form_state) {
  $page = $form_state->getValue('page_number');
  $stuff = getStuffFromDatabase($page);
  $result = array();
  foreach($stuff as $key => $item) {
    $tmp = new \stdClass();
    $tmp->id = $item->id;
    $tmp->title = $item->title;
    $tmp->description = $item->description;
    $tmp->image = $item->image;
    $result[] = $tmp;
  }
  $page++;
  // Here for non JS you probably would just redirect to the proper page
  $form_state->setValue('page_number', $page);
  $form_state->setValue('my_stuff', $result);
}

```

Then in your MyController::myFormSubmit

```
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\AfterCommand;
use Drupal\Core\Ajax\HtmlCommand;
use Drupal\Core\Ajax\InvokeCommand;

public static function myFormSubmit(array $form, FormStateInterface $form_state) {
  $response = new AjaxResponse();
  $selector = $form_state->getValue('my_stuff');

  // Here you build the render array based on the output you want on the page
  $build = [
    '#prefix' => '<div>',
    '#suffix' => '</div>',
  ];
  // The selector is as if you did this in jQuery
  $response->addCommand(new AfterCommand(
    '.some-selector',
    $build
  ));
  $response->addCommand(new HtmlCommand(
    '.some-selector-that-wraps-the-form',
    $form
  ));
  return $response;
}

```

That's the gist of it. It should put you on the right track.

If you want to use a simple link. You need your initial function to take that into account and send what you have now for non JS and a response as in the ajax submit callback when it's called through JS.

Note that if you add a class "use-ajax" to a link and write the link as "/some/path/nojs" Drapal.Ajax will change that to "/some/path/ajax" so its easy to know if the called was made through Ajax or not.
> 1 votes

---
Tags: 8, ajax
---


# Question
Title: Alter main menu button text and URL path depending on OG Role
I know you can change menu links depending on drupal based roles (authenticated, non authenticated...) and by using Rules module also.

I am using Organic Group roles and I am having difficulties in showing different links on the menu bar depending whether my site's user IS or ISN'T a member of a group.

When he/she signs up a 'join' button is on the nav bar --\> after joining a group he can now write content so the 'add' button replaces the join button on the nav bar with the appropriate URL paths.

Can a hook be used to do this?

# Answer
> 0 votes
You can do this using the `access callback` of the items array in hook\_menu\_alter. The implementation of the user menu gives a good example. To make it work with Organic groups, you could declare an access callback function using og\_is\_member or og\_user\_access:

```
function MY_MODULE_menu_alter(&$items) {
  $items['MY/PATH'] = array(
    'access callback' => 'MY_MODULE_custom_menu_access_callback',
    // Assuming your group is a node and the menu appears on the nodes
    // page (/node/[nid]), then array(1) would pass the node ID to your
    // function, which in this case acts as a group ID.
    'access arguments' => array(1),
    // etc...
  );
    return $items;
}
function MY_MODULE_custom_menu_access_callback($gid) {
  return og_is_member('node', $gid);
}

```

Where `MY/PATH` would be the path to the entity type representing the group. If you are using a node as a group, this would be `node/%`. As `'access arguments'` we use the arg function. `0` would be `node` and `1` would be the node ID of the node.

---
Tags: 7, hooks, organic-groups, navigation
---


# Question
Title: Drupal 7 Views - Date Filter Cannot See Year
I am trying to create a view with exposed filters for a date field with a start date and required end date.

However, I cannot see the year for the date when I created the filter. I can only see the day and the month. I am using Views 7.x-3.11. I also have both the Date module and Date Views module installed and enabled.

Does anyone know how I can have the year show up in the filter option? I have searched and searched for a solution, but I have not found anything yet.

# Answer
> 1 votes
To anyone who may be curious, I discovered the issue that was causing the year not to show. @75thTrombone put me on the right track.

After digging through the date popup module, I found that the views filter defaults to the Short date type format, which for my site had been set to `M j` (e.g. Jan 28). Once I added the year back to the Short date type format, the filter worked as expected.

It may be possible to configure which date type is used in the views filter, but I did not see a way to do that. The date popup module is using `variable_get('date_format_short', 'm/d/Y - H:i')`. I will also update the module and see if that allows for a custom configuration.

---
Tags: 7, views, datetime
---


# Question
Title: Changing drupal project folder breaks links
I have a drupal project working in the server home directory. I want to move this from the server home directory to a subdirectory to make way for other drupal projects.

I move the whole drupal project from `www/var/html` to `www/var/html/old_project`

I change the `$base_url` in the drupal project settings to `http://localhost/old_project`

In the web browser I navigate to localhost/old\_project. The home page displays but image links are broken. Links are broken to any other page I navigate to on the site. I can see that the urls are missing the .../old\_project/...' part of the url.

Why is it omitting this and how can I fix it?

EDIT

Even when I access the urls directly typing in the '.../old\_project/...' part I get 404 errors.

I have also tried adding `RewriteBase /old_project` in the `.htaccess` in `/sites/default/files/` and rebuilding the registry.

Many thanks

# Answer
> 1 votes
You need to rebuild theme registry. Download Registry rebuild module. and apply the following command `drush @site rr`

---
Tags: 7, navigation, configuration
---


title: hook_form_alter help (almost there!)

text:
# Question
Title: hook_form_alter help (almost there!)
There are two parts of a third-party module that I am trying to alter.

* When the user clicks submit
* When the user clicks reset

This is the function from that module.

```
function linkedin_user_settings_form($form, &$form_state, $account) {
  // Just fetch forms from submodules.
  $form['linkedin']['elements'] = module_invoke_all('linkedin_user_settings_page', $account);
  // We will need the account at submit
  $form['#account'] = $account;

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Save',
  );
  $form['linkedin']['reset'] = array(
    '#type' => 'submit',
    '#description' => t('Click here to unlink your LinkedIn account.'),
    '#value' => t('Unlink'),
  );

  return $form;
}

```

This is the code in my module.

```
function my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'linkedin_user_settings_form') {
    $form['#submit'][] = 'my_module_form_submit';
  }
}

function my_module_form_submit($form,$form_state) {
  // on submit do this
  drupal_set_message(t('You Saved'));

  // on reset do this
  drupal_set_message(t('You Reset'));
}

```

How can I check which button on the form has been clicked from the users?

# Answer
> 1 votes
You should be able to just copy what that linkedin code is doing in it's own linkedin\_user\_settings\_form\_submit submit function:

```
$op = $form_state['values']['op'];
if ($op == $form['linkedin']['reset']['#value']) {
 drupal_set_message(t('LinkedIn preferences have been reset'));
} else {
  drupal_set_message(t('LinkedIn preferences have been saved'));
}

```

---
Tags: 7, forms
---


# Question
Title: Can I reference field item & label in node.html.twig?
In Drupal 8, I defined a content type (say example) and made a separate template for it: node--example.html.twig.

I wonder if I can reference the item or label of a specify field in node--example.html.twig, instead of reference them in field.html.twig? By which I mean can I use something like the following, which I know is not working?

```
{{ content.field_example_field.label }}

```

# Answer
If you can't find the label somewhere inside of `content`, then the code, which will prepare the label for rendering did not run at this point.

If you are inside the node twig, then there is a fully loaded node object. You can use this to get the field definition and the label:

```
{{ node.field_myfield.fieldDefinition.label }}

```

Or the first field item:

```
{{ node.field_myfield.0.value }}

```
> 2 votes

---
Tags: theming, entities, 8
---


title: form in a .tpl.php file

text:
# Question
Title: form in a .tpl.php file
This is the code in my template.php file.

```
function studiga_theme_theme($existing, $type, $theme, $path) {
    $items['add_property_form'] = array(
        'render element' => 'form',
        'template' => 'node--14',
        'path' => drupal_get_path('theme', 'studiga_theme') . '/templates/node',
    );

    return $items;
}

 function custom_add_property_form($form, &$form_state) {
    $form['first_name'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('First name')),
    );
    $form['last_name'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('Last name')),
    );
    $form['address'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('Address')),
    );
    $form['city'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('City')),
    );
    $form['state'] = array(
        '#type' => 'select',
        '#options' => array(
            'default' => 'State',
            '...' => '...',
        ),
    );
    $form['zip'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('Zip')),
    );
    $form['email'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('Email')),
    );
    $form['phone'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('Phone')),
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit',
    );

    return $form;
}

```

This is the code in node--14.tpl.php.

Contact Information
```
<div class="row">
    <div class="small-12 medium-12 large-8 large-offset-2 columns">
        <?php print render($form['submit']); ?>
    </div>
</div>

```

But no fields are appearing - what am I doing wrong? You can't have a straight forward in a tpl.php file can you?

# Answer
> 2 votes
Given your definition of `studiga_theme_theme()`, Drupal will never call `custom_add_property_form()` because there isn't any relation between the theme template you define, and that function. Eventually, you could implement the preprocess function for that theme template, and set there a variable that is passed to the template.

```
function studiga_theme_preprocess_add_property_form(&$variables) {
  $variables['form'] = /* define here the form */;
}

```

Now your theme template will get a `$form` variable.

Keep in mind that, except in a case, themes don't define forms; that is the task for a module. Eventually, themes can alter a form provided by a module, but (generally speaking) you will never see a theme that defines a form that is not for its own settings.

# Answer
> 0 votes
I think your theme name(studiga\_theme) is wrong. Try making it just "studiga". "\_theme" is reserved word in Drupal. I also faced similar issue once. Hope that will resolve your problem.

---
Tags: nodes
---


title: How to link to dblog filtered by type?

text:
# Question
Title: How to link to dblog filtered by type?
In my custom D7 module, I'd like to link to admin/reports/dblog/, however, I'd like to have it filtered by a certain type so when you navigate to that link, the type is already filtered for you.

Is this possible?

# Answer
> 2 votes
It is possible, but the values used to filter that list are put in `$_SESSION['dblog_overview_filter']`. Linking to that page and making it shows the messages filtered by type is only possible if you set that session variable with the right value. Looking at the code of `dblog_filters()`, I get that the following line would cause that list to show the logs about cron tasks.

```
$_SESSION['dblog_overview_filter']['type'] = array('cron');

```

### References

---
Tags: 7, navigation
---


title: db_update with a hook

text:
# Question
Title: db_update with a hook
Have a field called url\_time in the users table. I have this function in place, though it does not update the table on the else part.

Does this code look correct?

```
function my_module_form_submit($form,$form_state)
{
global $user;
$account = user_load($user->uid);
$op = $form_state['values']['op'];

if ($op == $form['linkedin']['reset']['#value']) {
    if (db_field_exists('users', 'url_time')) {
        db_update('users')
            ->condition('uid', $account->uid)
            ->expression('url_time', 0)
            ->execute();
    }
}
else {
    $date = time();
    if (db_field_exists('users', 'url_time')) {
        db_update('users')
            ->condition('uid', $account->uid)
            ->expression('url_time', $date)
            ->execute();
    }
}
}

```

This is the linkedin function that I am trying to implement, so when the user authorities, the "else" will write a date.

```
function linkedin_user_enable_form($form, $form_state, $uid) {
$form = array();
$form['#user'] = $uid;
$form['#action'] = url('linkedin/token/' . $uid);
$form['submit'] = array(
 '#type' => 'submit',
 '#value' => t('Go to LinkedIn'),
'#suffix' => '<p class="description">' . t('You will be taken to the LinkedIn website in order to complete the process.') . '</p>',
);
return $form;
}

```

# Answer
> 0 votes
This wouldn't delete just the field, it would delete the row for a user whose `uid` equals `$account->uid`. The `->expression()` and subsequent `->execute()` as @kiamlaluno points out, wouldn't work right anyway.

If you want to simply delete the value, you are better off doing something like this:

```
// $account is defined up ^^ there somewhere.
$account->url_time = '';
user_save($account);

```

# Answer
> 0 votes
Your code is wrong: To set the value of *url\_time* for the user row matching a user ID, you need to use the `UpdateQuery::fields()` method.

> Adds a set of field-\>value pairs to be updated.

The correct code is the following one.

```
if (db_field_exists('users', 'url_time')) {
  db_update('users')
    ->condition('uid', $account->uid)
    ->fields(array('url_time', 0))
    ->execute();
}

```

This is similar to the following code used by Drupal core, which updates *expire* for the records matching the conditions.

```
  // Insure that the timeout is at least 1 ms.
  $timeout = max($timeout, 0.001);
  $expire = microtime(TRUE) + $timeout;
  if (isset($locks[$name])) {
    // Try to extend the expiration of a lock we already acquired.
    $success = (bool) db_update('semaphore')
      ->fields(array('expire' => $expire))
      ->condition('name', $name)
      ->condition('value', _lock_id())
      ->execute();
    if (!$success) {
      // The lock was broken.
      unset($locks[$name]);
    }
    return $success;
  }

```

---
Tags: hooks
---


title: Base theme no longer recognized

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

To clarify,

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

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

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

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

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

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

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

---
Tags: 7, theming, debugging
---


# Question
Title: How can I use configuration management to "snapshot" config on my dev server while I try new things out?
I was a heavy Features module user in Drupal 7 so I'm trying to use Configuration Management in Drupal 8 to recreate my old workflow.

In Drupal 7, when I wanted to try making changes, I would:

1. Add my current config to a feature (store the values of variables with Strongarm)
2. Export the feature.
3. Commit the code.
4. Mess around with the variables and see if I like my changes better. If yes, update the feature. If no, revert the feature.

The key to this workflow was that I was storing the config in code on the same dev server that I was using; in other words, I wasn't syncing between two servers, but rather using the Features module to store a snapshot of a working configuration while I made changes that would potentially need to be reversed.

I see that I can use Configuration Management to export configuration, but this is in archive format, which isn't very easy to `diff`. Also, committing a bunch of archives to my git repository seems like the wrong way, and a big step backward from Drupal 7.

**My question:** In Drupal 8, is it possible to export configuration such that it can be committed to a git repo, then `diff`ed and used as a "reset button" when making changes that go awry?

**What I tried**

In the Configuration Management documentation, it has the following solutions:

* UI-based
* Drush-based
* File--system-based

But what I'm looking for is **code-based**. I thought this might be "file-system-based", but these files are in the `/files` directory, which is usually exempt from git by the `.gitignore` file.

# Answer
I would suggest to only use features for reusable components between projects. The configuration management system works quite well for me for the workflow that you are suggesting.

To export all configuration to a directory (by default `./sites/default/config`)

```
$ drush config-export # or use the alias: drush cex

```

This exports your active configuration into a bazillion files, then you can add it to git as usual:

```
$ git add -A sites/default/config # -A includes deleted and new files
$ git commit -m "config: my config changes here"

```

Now you have your snapshot, you can play with your site and if you end up in a state that you are not happy with, you can always import your exported files back to the active configuration by

```
$ drush config-import # or the shorter: drush cim

```

You can also use `drush config-diff name.of.config` to see the differences. Or you could just export again and `git diff` them

If you like your new configuration better, you can just start again: export, commit, repeat.

This is also useful to push your configuration to your test server. You just need to deploy the new code with the exported configuration and import it with

```
$ drush @stagingsrv cim

```

For some advanced cases check out the config\_devel module
> 2 votes

---
Tags: 8, features, configuration
---


# Question
Title: Missing group audience field(og) from node add form by panel
I have 2 content types, and they are Organization(group) and Contact(group content) From Contact, I add the group audience field and bundle with Organization.

When I use the node/add/contact from default node add form, everything is great.

I am trying to create another node/add/contact form from other url (organization/add\_contact). However, my problem is after setup a page(page management) and add the context with node add form, I find out my new add node form is missing the group audience field.

Is anyone have same problem or some setting was missed.......

# Answer
It's a bug in "og/includes/og.field.inc". When the form is built twice "og\_field\_widget\_form()" returns an empty array, thus the element has no options and seems to be missing.

Here is a link to the bug tracker: https://www.drupal.org/node/2481709

Issue is still open. For now I just commented the offending if-block out.
> 0 votes

---
Tags: panels, organic-groups, chaos-tool-suite
---


# Question
Title: How to select a specific row in views-view.tpl.php?
I'm customizing a specific views block and trying to separate the 2 first rows in a "top" div(wrape it)

# Answer
This type of question has come up for me and I found that going a few layers back (or up) and head towards `rows style output` solved my issue. If you edit that view you want to override, then go to the `Advanced` column, expand it, then click on Theme: `information.` In that overlay window you can see they will suggest what to call a .tpl.php to override the different levels. I would choose the one that has `row style output.` From there, with a debugger, I am sure you can figure out how to isolate the first two rows. Hope this helps you find the solution you need.
> 1 votes

---
Tags: 7, views, theming
---


# Question
Title: Custom Javascript doesnt work unless JQuery is set to Default jQuery Version
I spent the entire day trying to figure out why my custom JavaScript was not working.

Eventually I stumbled into the JQuery Update configuration and set it so that the JQuery that I use for my site was the "default (provided by Drupal)" setting and then it worked. Before it was set to 1.7 jQuery version. Looks like someone set it to 1.7 perhaps for magnific.js because that is now spitting out errors in my console "TypeError: a.off is not a function." Not sure what we use that js file for, but I find it strange that I never found anything on line about this being a potential issue when I was trying to troubleshoot my custom javascript.

Does anyone know anything about this? or am I just in left field? I know it wasn't the same issue the gentleman had in this post.

My custom code was not complex and it never worked. So I reduced it all down to just console out a simple message. But that proved to not work either. My simple console out code for my `pulsing.js` is: `(function ($) {
 Drupal.behaviors.notWorking = {
 attach: function () {
 console.log("finally is working");
 }
 };
}(jQuery));`

Ill just show the screen shots. The first one is the image where my custom code doesnt work because of jQuery update settings as I said above.

The second one is what makes my custom code actually work - but like I said magnify.js then breaks - which maybe i'll hack at it or look for a newer version or something.

# Answer
> 0 votes
magnific.js clearly needs the .off() function which was added in jQuery 1.7. If you need magnific.js, you will need jQuery 1.7 and it is your job to upgraded your custom JavaScript accordingly.

You may find the changes you need are minimal.

---
Tags: javascript
---


# Question
Title: How to Allow User to Choose to Pay by Invoice OR Credit Card with Drupal Commerce
does anyone know if its possible to have a Drupal Commerce checkout form that allows a user to choose whether they want to pay by credit card OR have us send them an invoice so they can pay by check? The form should allow the user to submit the form regardless of which option they choose.

Note: if they choose credit card they would of course have to fill out their credit card information. IF they chose invoice they wouldn't have to pay at this time.

# Answer
> 2 votes
If you have multiple payment options available, the customer will be prompted to choose the payment option they want.

If you're not picky, you can use Commerce Custom Offline Payments and just create a payment type for an invoice.

---
Tags: commerce
---


title: Commerce invoice checkout

text:
# Question
Title: Commerce invoice checkout
I have enabled the Pay pal module as a checkout option but I need to add a new option for the customer to request an invoice. I realize I need to modify some rules but it seems that the first item I need is a Payment method which the customer can choose that will fire off the Billy invoice. I have looked everywhere but cannot seem to find a suitable method. Should I use the Exmaple paymnet method and try to modify this?

Cheers /bo

# Answer
> 1 votes
You can use Commerce Custom Offline Payments to handle this.

---
Tags: commerce
---


# Question
Title: Programmatically create a new node from an existing NID
Essentially I want to take a node and duplicate it. Take a node ID and programmatically create a copy of the node.
I want to be able to edit the newly created node, and maintain the data on the old node.

# Answer
On entities, you can use `is_new` to signify a new entity to save, but you still need to unset `nid` (iirc), `vid`, and `tnid` manually. This saves unsetting `log`.

```
$new = clone $node;
$new->is_new = true;
unset($new->nid);
unset($new->vid);
unset($new->tnid);
node_save($new);

```

Interestingly, the node\_clone module incorrectly sets the properties to `null`, which is significant for databases that support NULL and DEFAULT separately (e.g. PostgreSQL).
> 8 votes

# Answer
You may be happy with the replicate module which provides an API to do just that for any entity.

As stated in its README file (You'll find more in it) :

**Very basic usage example:**

```
/**
 * Replicate Basic test function.
 *
 * In this example we will suppose that there is a node with nid = 1 we want
 * to replicate.
 */
function replicate_test_function() {
  // Load a newly created node as an entity.
  $entity = array_shift(entity_load('node', array(1)));

  // Duplicate the entity and save the replica.
  replicate_entity('node', $entity);

  // You can use replicate_clone_entity() instead, alter the replica afterward
  // and manually save the entity, but if you want to implement a generic
  // code like adding ' [Replicate]' to the end of every replicated node title,
  // use the API hook hook_replicate_entity_ENTITY_TYPE().
}

```
> 5 votes

# Answer
You can load your node with `node_load()` and unset the nid and vid and then save the new node with `node_save()`

```
  $nid = 4;
  $node = node_load($nid);
  $new_node = $node;
  unset($new_node->nid);
  unset($new_node->vid);
  node_save($new_node);

```
> 2 votes

---
Tags: 7, nodes
---


# Question
Title: For "parent" node, how do I show list of child nodes related by child field of type "Entity Reference"?
CONTEXT: Let's say I have a one-to-many relationship between parent "companies" and child "contacts". Each is its own content type. The contacts content type has a field of type Entity Reference that can be used to associate a child Contact node to a parent Company.

QUESTION: How, when I am on the display of an individual Company node, can I see a list of related contacts right beneath the Company node fields?

Essentially this functionality would be like a "related list" in Salesforce.

Surely there is a module or modules that enable this without having to resort to code?

I've seen the Views Field View module. It looks promising. The Panels module looks promising but apparently it is not just for use on its own; it just enables other modules.

# Answer
Thanks in part to @Niall Murphy's response, I was able to find a Drupal Community Doc that got me further along, though I had to do some translation from Drupal-7 terminology to Drupal-8 terminology before I reached a solution/answer. I've updated the Doc accordingly so you can read it for the solution/answer details.

Note: No additional modules were needed. I was able to do everything with freshly-installed out-of-the-box Drupal 8.0.2 functionality.
> 3 votes

# Answer
In your relationships for views, there are two options per entity reference. Check those.. I believe they're called referenced by and referencing.
> 2 votes

# Answer
In your view, for RELATIONSHIP, click add and select referenced entity. If not try Referencing entity, but I am confident that it's referenced.
> 2 votes

# Answer
As EVA: Entity Views Attachment doesn't have Drupal 8 version, you can use the Display fields module.

> This module provide display field types used only in "display" mode.
>
> The UI are located in the entity type: display settings form additional settings tabs. The display fields are build and cached within the entity content like the regular fields. The weight and display settings are set on the entity display settings form like the regular fields.
>
> **Features**
>
> * Embed a view, set the display, provide values for arguments from the context (the entity being displayed). Example: list of blog post for a homepage of a blog.

So, you can make a View with the "parent" nid as argument and load all its childs, then embed this View in the node display.
> 1 votes

---
Tags: views, 8
---


title: Panels settings modal not working

text:
# Question
Title: Panels settings modal not working
I am trying to make changes to a saved "selection rule" on one of my Panels, but when I click the settings gear icon, the icon moves on top of the "Delete" icon for a second, then moves back alongside - but no modal pops up.

Tried: \- disabling javascript in browser (results in a page of code after clicking gear) \- Using a different browser

* Checked status page for errors
* Switching versions of jQuery (via jQ update) as well as source CDN
* Clearing caches
* Restarting httpd
* Testing it on my dev server with a similar environment - works fine
* Tried the same operation in another Drupal installation on the same server, and the same modal works fine with that one.

The site is on a Centos 6 VPS running CPanel, APC and memcached, and behind Varnish.

I see nothing related in /var/log/messages, domlogs, error logs or watchdog, nor in the console.

When a Panels modal works (e.g. clicking the gear icon for a rule in the Context section of the same Panel) the console shows "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/." But on the site where it works, this message doesn't show up in the console. This is the closest thing to a clue I've been able to find, but I don't know what it means.

Any suggestions how to fix it, or even how to diagnose what the problem is?

# Answer
Figured it out. I was using Adminimal for my admin theme, and I changed the skin to "Alternative" and tried again ... and it worked. So it was something in the theme that caused the conflict, though I don't know what.
> 1 votes

---
Tags: javascript, panels
---


# Question
Title: Title in page does not change with different page of the same View
I have a View which displays a list of content. The content is paged, like this

```
http://www.exampple.com/en/products?product=all&brand=0&page=4

```

I keep the parameter **page** as exactly provided by default View pager. However, when clicking on different pages, the TITLE of the page does not change, it is "Products | WEBSITE\_NAME" all the time. I would have expected the page number to be added automatically, as the site domain name is. For instance:

```
 "Products Page 1 of 3 | WEBSITE NAME"

```

Is there a module or a config to achieve this, or must I do it through a hook and `drupal_set_title` function in my custom module ?

The above different title for each page is necessary to avoid SEO penalization by Google and other seo bots.

# Answer
If you are using AJAX in your view, the title won't change. Also, try adding !1 or %1 to your view title.
> 1 votes

---
Tags: views
---


# Question
Title: Why is the default Search module not returning partial results?
Drupal 7 default Search module not returning partial results

I.E. I have a series of SKU #'s:

* S0160-0003
* S0160-0004
* S0160-0005
* S0160-0006

Searching for S0160 returns no results. I only get results when I search for the exact SKU number.

Any recommendations as to how to fix this?

# Answer
Actually there's a quick way to set this up with the Search API and the Search API Database Search modules. **No need for Solr**.

1. Enable both the modules and go to the Search API configuration page (admin/config/search/search\_api)
2. *Add a server* and give it a recognizable name (such as "MySQL"), make sure it's *enabled*
3. Choose the following service class: *Database service* (normally the only option. If you don't see it, make sure that the "Search API Database Search" module is enabled).
4. Selecting this service class will provide you the option **Search on parts of a word** (make sure you enable it). Now hit "Create server". Next, go back to the Search API configuration page, and *add an index*. Again give it a recognizable name, such as "Contentindex", and make sure it's enabled.
5. Select the server you recently created (in this example "MySQL"). Datasource options: check the content types you want to index (the description of this field may be a bit confusing, but make no mistake: you should check the content types you want to index, not the ones you want to leave out).
6. You could check "Index items immediately", but that depends on the size of your content. This option is alright for smaller websites. In the other case: let cron take care of it. Hit "Create index".
7. Next, you want to enable the *fields* (in the fields tab) to that very index, e.g.: contant type, title, status and author - and hit "Save changes" (we'll take care of the related fields later).
8. Then you want to configure the *filters* (in the filter tab). Here you can enable the *bundle filter*, if you want to finetune the content types once again (probably won't need to).
9. Down below you'll find the *highlight filter*, to highlight the search word in the results.
10. Now return to the fields tab and unfold the "Add related fields" tab. Add all the fields of which you want to get the content indexed, and hit Save Finally go to the "view" tab of the index, and *index now* all the items.

The last step is to create search results page and search block in Views, which only takes a few minutes.

1. Make sure the submodule **Search Views** is enabled and create a view page which will *show "Contentindex"* (select the name you gave to your index configuration instead of "content" which is selected by default.
2. Add all the fields (make sure your format is "fields") that every search result should consist of (title \[link to content\], body, …). You'll notice that these field look like this *Indexed Node: Title*
3. Add an **exposed filter**: *Search: Fulltext search*; and select the following in its settings: *Contains any of these words*, and use as: Search keys.

You're done!

There's an excellent video tutorial on this partial search method without Solr, which also incorporates faceted search (which is not necessary for partial search, but in case you're interested…). If you're only looking for a partial search option, you can watch the video until 5:08 and after that skip to 6:45.
> 3 votes

# Answer
Just add the following line to the type definition after the first occurrence of "solr.SnowballPorterFilterFactory" (inside of the `<analyzer type="index">` element; not after the second occurrence):

```
<filter class="solr.EdgeNGramFilterFactory" minGramSize="2" maxGramSize="25" />

```
> 3 votes

# Answer
1. I would recommend to use solr search with solr configurations as http://www.wunderkraut.com/blog/apache-solr-configuring-partial-word-search-functionality/2012-12-12
2. In case you do want to have solr as search backend then you can use Search Api String Filter module with in turn will use search\_api replacement of core search and search\_api\_db so to use drupal database for search index.
> 0 votes

---
Tags: 7, search
---


# Question
Title: Where can I find the link between field answers and the user who submitted it?
Noob here. I can't figure out how entity forms stores which user submitted each answer for it's fields on the database.

All I can see is a table for each field, and the columns within being: Entity\_type, bundle, deleted, entity\_id, revision\_id, language, delta & Field\_(the name of my field).

None of which tells me which user submitted each answer. Yet drupal and entity forms clearly knows which user submitted each answer, because when I go to (Administration \> Structure \> entityform types \> my form \> form submissions) I can see a table of every submission with the name of each user who submitted it, and I can see all their answers.

So where the heck is this being stored on the database? If it matters, my database was built with phpmyadmin.

Thanks in advance for your help, I really appreciate it. I'm sorry if my terms are all jumbled and wrong.

# Answer
> 1 votes
Look for "entityform" table - column "uid" gives you user id of the user who submitted the form.

---
Tags: 7, users
---


# Question
Title: How to detect same user when they submit two webforms?
User A submit a newsletter form and come to thank you page. At the thank you page there is another general comment form.

Here is my question: How to detect both of them are belong to User A?

Reason: So that I can extract both information together from database.

# Answer
Another less obvious solution if using the rules module already is https://www.drupal.org/project/rules\_session\_vars

Set the variable when the first form is submitted and check for it when the second is submitted. The use rules to do whatever is needed.

Your own prepopulate solution is perfectly fine however. This one just stops someone from hacking the url.
> 1 votes

# Answer
I find out a solution. Get URL and pass it to webform's hidden field. When User Submitted a form and redirect to thank you page, in the URL will show unquie sid. With this sid, I can know they the forms submit by same person.

I wonder is there any better solution.
> 0 votes

---
Tags: 7, webforms
---


title: Current search block: edit (-) link

text:
# Question
Title: Current search block: edit (-) link
I'm using search api and solr, with facet api. If I display a "current search block", if I click on a facet the system add to the block a "(-) facet name", and if I click to "(-)" it removes the facet from the search. Is there a way to theme this behaviour? I want to display it as an image.

# Answer
> 2 votes
Look at `theme_facetapi_deactivate_widget` function in facetapi.theme.inc. Of course, you can override it in your theme.

# Answer
> 0 votes
try like this

```
function hook_facetapi_deactivate_widget(&$variables) {
  return '';// fill with your required data
}

```

---
Tags: 7, search
---


# Question
Title: Creating a filter programatically with views_get_view
I have a lot of views and I want to add a filter to just one of them. This view is called **soccer\_news\_feed** and I want it to check out my custom field: **field\_data\_field\_is\_score** and display if it's not 1.

So in a hook\_update\_n I have this code:

```
$view = views_get_view("soccer_news_feed");

$view->add_item(
  $view->current_display,
  'filter',
  'field_data_field_is_score',
  'field_is_score_value',
  array('operator' => '<>','value' => array('value' => 1))
);

```

So I thought maybe this work but I get this error when I run updb:

```
PHP Fatal error:  Call to a member function get_option() on a non-object in /var/www/public/sites/all/modules/contrib/views/includes/view.inc on line 2450

```

I'm very lost on this.

# Answer
> 0 votes
The first key to enlightenment is to at error message. It says the fatal error happened in views/includes/view.in, around line line 2450. I don't know your exact version, but in one of my Drupal 7 installs, here's what's close to line 2450:

```
  /**
   * Add an item with a handler to the view.
   *
   * These items may be fields, filters, sort criteria, or arguments.
   */
  function add_item($display_id, $type, $table, $field, $options = array(), $id = NULL) {
    $types = views_object_types();
    $this->set_display($display_id);

    $fields = $this->display[$display_id]->handler->get_option($types[$type]['plural']);

```

My line numbers don't match in my version, but notice the last line of the excerpt. Best guess that $this-\>display\[$display\_id\]-\>handler ($this is your view) is either NULL, or is not an object.

$this-\>display is an array of view\_display objects; and $this-\>display($display\_id) should either be a view\_display, or perhaps, NULL or FALSE.

I'd recommend trying the following to debug this:

* First, perhaps it's possible that $view-\>current\_display is not initialized, or isn't what you think it is. Try substituting it with 'default', which usually works with Views.
* If you look at your view's definition and know the machine ID of one of your displays for that view (say, 'page\_1'), try substituting that and see if it works.
* If you're using an IDE with a source debugger, this is a good time to learn to use it a bit. Views can be pretty opaque as to what it's doing under the hood, and sometimes, seeing what the data actually is in real time can save you a lot of time.

That's as much as I can suggest w/o knowing the exact version of Views you're using, but it may get you started.

Good luck, in any case.

---
Tags: entities, views
---


# Question
Title: How do I save a file with managed_file in a theme?
I'm developing a theme that it requires to have a header image on the front page, so I have this.

**casper.theme**

```
function casper_form_system_theme_settings_alter(&$form, &$form_state) {

$form['theme_extra']['front_page_background_image'] = array(
    '#type' => 'managed_file',
    '#title' => 'Front Page Background Image',
    '#description' => 'Add background image for the front page',
    '#required' => FALSE,
    '#weight' => -4,
    '#upload_location' => file_default_scheme() . '://theme/backgrounds/',
    '#default_value' => theme_get_setting('front_page_background_image' , 'casper'),
    '#upload_validators' => array(
        'file_validate_extensions' => array('gif png jpg jpeg'),
    ),
 );
}

```

However, after it, while the file been missing and after some reading, I find out that is because managed\_file does not save your image permanent.

There are similar questions:

How can I save my image permanently?

# Answer
> 4 votes
The way it was done in Drupal 7 was that you wrote a function for `hook_form_submit` where you would

```
// Get the File ID (fid).
$fid = $form_status['values']['managed_file_field'];

// Load the file.
$file = file_load($fid);

// Set the status to permanent.
$file->status = FILE_STATUS_PERMANENT;

// Finally save the file.
$file->save();

```

You can read more about this with a great Drupal 7 example here. I'm sure there's something similar on Drupal 8. You'll just need to register a submit handler for the form. Take a look at the docs for managed\_file if you want to go that route. here for it.

# Answer
> 1 votes
I have created a method that does exactly this. I can confirm that it does indeed work.

```
public static function saveFile($fid, $moduleName, $fileType){

  if(isset($fid) && is_string($fid)){

    /**
     * @var $file File
     */
    $file = File::load($fid);

    // save the file
    /**
     * @var $file_usage DatabaseFileUsageBackend
     */
    $file_usage = \Drupal::service('file.usage');
    $file_usage->add($file, $moduleName, $fileType, 1); // or $themeName

    return true;
  }

  return false;
}

```

# Answer
> 0 votes
While I had thought that you could include a submit callback string, it looks like the theme file is not included when the form is submitted. This can be worked around dirty by making the submit callback a function in the form callback. Closures won't work because they cannot be serialized.

```
// @todo Please fix me, Drupal-Core Kenowbi!
$submit = function($form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $values = $form_state->getValue('front_page_background_image', []);
  if ($values) {
    $fid = $values[0];
    $file = \Drupal\file\Entity\File::load($fid);
    $file_usage = \Drupal::service('file.usage');
    $file_usage->add($file, 'casper', 'theme', 1);
  }
};

$form['#submit'][] = $submit;

```

Realistically this seems like a good case for a core fix or a contrib module that would provide a way for themes to call their own submit callbacks.

# Answer
> 0 votes
### Drupal 7

I used many places file\_managed to save my files. Please find the below code in my bartik theme, working fine:

**bartik.info**

```
settings[front_page_background_image] = headerimage.png

```

**template.php**

```
function bartik_form_system_theme_settings_alter(&$form, &$form_state) {

$form['theme_extra']['front_page_background_image'] = array(
    '#type' => 'managed_file',
    '#title' => 'Front Page Background Image',
    '#description' => 'Add background image for the front page',
    '#required' => FALSE,
    '#weight' => -4,
    '#upload_location' => file_default_scheme() . '://theme/backgrounds/',
    '#default_value' => theme_get_setting('front_page_background_image' , 'bartik'),
    '#upload_validators' => array(
        'file_validate_extensions' => array('gif png jpg jpeg'),
    ),
 );

}

```

**page.tpl.php**

```
$file =  file_load(theme_get_setting('front_page_background_image'));

$image = image_load($file->uri);

$content = array(
        'file' => array(
            '#theme' => 'image_style',
            '#style_name' => 'large',
            '#path' => $image->source,
            '#width' => $image->info['width'],
            '#height' => $image->info['height'],
        ),
        );
echo drupal_render($content);

```

---
Tags: forms, files, 8
---


# Question
Title: Mouseover overlay for images using Views Photo Grid
Trying to add a hover overlay for node title and a couple of other fields for images using the views photos grid module.

The fields to be used in the overlay need be excluded from the display as the module only uses one image field, however I am not managing to add the excluded fields.

If I the preprocess to template.php

```
`function THEME_preprocess_views_photo_grid_style(&$vars) { $vars['raw_result'] = $vars['view']->style_plugin->rendered_fields;}`

```

I can print the titles using

```
`foreach ($raw_result as $row) {print $row['title']; }`

```

which prints the titles on the page outside the container as a row, but I can only add the last title to the overlay. Need to be able combine each title to each image that is shown using

```
`foreach ($items as $key => $item):

```

`print $item;` `endforeach;`

# Answer
As the arrays line up, added an index and combined the arrays

```
$index = 0; foreach ($items as $key => $item):
print $raw_result[$index]['title']; $index++
print $item;

```

Works
> 0 votes

---
Tags: theming
---


# Question
Title: Features doesn't recognize my drupal version
I looked in Status report:

```
Drupal 7.41

```

I get this error:

```
Please enter a valid version with core and major version number. Example: 7.x-1.0

```

I've tried all sorts of combinations but nothing works, what should I put in there?

Additionally, the feature downloads as a .tar file, can I get it to download as a Zip file?

# Answer
Ok, got it...I thought the X in 7.X was supposed to be my sub drupal 7 version = 41, but actually the X has to remain X, not a variable for the version name...got confused...I thought I had to substitute the X with 41 –
> 0 votes

---
Tags: files, features
---


title: Post image with raw json?

text:
# Question
Title: Post image with raw json?
Using `Content Type: application/json` I tried like:

**EDIT:**

```
{
 "type": "article",
 "title": "Test article with image1",
 "body": {
 "und": [{
     "value": "test body!"
   }]
  },
 "field_image":{
 "und":[{
  "fid":{
  "filename": "bar.jpg",
  "target_uri": "sites/default/files/styles/large/public/field/image/bar.jpg",
  "filemime": "image/jpeg",
  "file":        "iVBORw0KGgoAAAANSUhEUgAAAKQAAAFzBAMAAABC179RAAAAD1BMVEUYooorZrPZwVO3Sd0M9BOSfwC2VwFIl7c9aAAAAABJRU5ErkJggg==",
   "filesize": "12345"
       }
     }]
    },

  "language": "und"
 }

```

**Problem:** `Image` is not created.

# Answer
You need to use the `file` resource to upload the file first; that will provide you with a `fid` (file ID), which gets attached to the field on the node. The payload for that request might look something like:

```
{
    "filename": "foo.jpg",
    "target_uri": "bar/foo.jpg",
    "filemime": "image/jpeg",
    "file": "iVBORw0KGgoAAAANSUhEUgAAAKQAAAFzBAMAAABC179RAAAAD",
    "filesize": "12345"
}

```

And then to attach it the field your existing code will change to something like:

```
"field_image":{
  "und": [{
    "fid": [FILE ID RECEIVED FROM FILE SERVICE HERE]
   }],
}

```
> 0 votes

---
Tags: nodes, services
---


title: Adding form to .tpl

text:
# Question
Title: Adding form to .tpl
This is definitely being called

```
function studiga_theme_theme($existing, $type, $theme, $path) {
    $items['add_property_form'] = array(
        'render element' => 'form',
        'template' => 'node--14',
        'path' => drupal_get_path('theme', 'studiga_theme') . '/templates/node',
    );

    return $items;
}

```

But which should set up the form fields isn't and I have no idea why

```
function studiga_theme_preprocess_add_property_form(&$variables) {

  // Shorten the form variable name for easier access.
  $form = $variables['form'];

  $form['first_name'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('First name')),
    );
    $form['last_name'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('Last name')),
    );
    $form['address'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('Address')),
    );
    $form['city'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('City')),
    );
    $form['state'] = array(
        '#type' => 'select',
        '#options' => array(
            'default' => 'State',
            '...' => '...',
        ),
    );
    $form['zip'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('Zip')),
    );
    $form['email'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('Email')),
    );
    $form['phone'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('Phone')),
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit',
    );
}

```

Thanks

# Answer
> 3 votes
As marcvangend mentioned already, theming functions are not the right place for altering forms.

I suppose you are using Drupal 7 and like to alter a form that has already been added to the node before. In this case you should have a look into hook\_form\_alter() or hook\_form\_FORM\_ID\_alter():

https://api.drupal.org/api/function/hook\_form\_alter/7

https://api.drupal.org/api/function/hook\_form\_FORM\_ID\_alter/7

These hooks can be used within your custom module to alter forms even before theming takes place. For getting the ID of the form in question, just debug the $formid parameter of the hook\_form\_alter() while visiting the node.

For adding a custom form to your node you should write a custom module implementing the following hooks:

```
/**
 * Implements hook_block_info().
 */
function MYMODULE_block_info() {
  $block = array();
  $block['mymodule_form'] = array(
    'info' => t('My Form'),
  );
  return $block;
}

/**
 * Implements hook_block_view().
 */
function MYMODULE_block_view($delta = '') {
  $block = array();
  if ($delta == 'mymodule_form') {
    $block['content'] = drupal_get_form('MYMODULE_my_awesome_form');
    $block['subject'] = t('My Form Title');
  }
  return $block;
}

/**
 * My Form
 */
function MYMODULE_my_awesome_form($form, $form_state) {
  $form = array();

  // define your form here...

  return $form;
}

/**
 * My Form Submit Handler
 */
function MYMODULE_my_awesome_form_submit($form, $form_state) {
  // do your magic on the submitted form values in $form_state['values']
}

```

Then you will find the form within **/admin/structure/block** and can add it to the desired page region of your node. Filter the node within the block settings by choosing 'Only the listed pages' under **Pages/Show block on specific pages** and entering your **node/14**.

---
Tags: theming
---


# Question
Title: Entity reference default value to first value
I have an entity reference field using a view to dynamically create a list based on a contextual filter from a user ID in URL. Works perfectly.

Question is, how can I default the value to the first result in the list, instead of displaying -None- or -Please select-

# Answer
You can do easily using jQuery

```
$("#target").val($("#target option:first").val());

```
> 0 votes

---
Tags: entities, users
---


# Question
Title: How to reorder nodes in Drupal 7 using Drag and Drop feature?
Can anyone please help me that, how I can reorder the nodes in Drupal 7 using drag and drop feature?

# Answer
Create a view to list your nodes and use Drupal draggable views module to order your nodes.

> From the documentation page,
>
> * Order any type of entity
> * Set different order for different set of arguments
> * Create one view that sets the order, and create as many views as you like that shows that order
> * Use core tabledrag.js or jQuery UI draggable javascripts to set the order

Steps to use this module and views to order nodes:

* Download draggable views and views module and enable in your site.
* Create a view to list your nodes say field will be node title and choose Format as Table.
* Add draggable fields as additional field in Fields section. You can use submit as well as ajax submit once you ordered your nodes.
* Add Draggable weight as ascending order in sort criteria.
* Save the view and view it in the page.
* My list will be like this:
    + Drag and drop the pointer to order the nodes and hit submit.
> 8 votes

# Answer
There are many modules for this purpose. You can use Node Order module

> The nodeorder module gives users an easy way to order nodes within their taxonomy terms.
>
> By default, the taxonomy module orders listings of nodes by stickiness and then by node creation date -- most recently posted nodes come first.

Or to choose from the list of modules for this purpose, you can have a look at the Comparison of Node/Entity Ordering Modules page.
> 3 votes

# Answer
Nodequeue module was built exactly for the same reason :)

> The Nodequeue module allows users to collect nodes in an arbitrarily ordered list. The order in the list can be used for a any purpose, such as:
>
> * A block listing teasers for the five top news stories on a site
> * A user’s favorite music albums
> * A group of favorite from which one is randomly displayed
>
> Nodequeue provides a simple drag-and-drop interface to manually order any queue. Additionally, it allows nodes to be added and removed from queues without needing edit permissions to the node. Nodes can be added to queues either from a queue management tab or by links on the node teaser.

Follow this tutorial to create a nodequeue.
> 2 votes

# Answer
There is a comparison of "node ordering modules" at https://www.drupal.org/node/398508
> 0 votes

---
Tags: nodes
---