# Question
Title: I have no fields available for sorting with Search API sorts module
This question is similar to another question I had, but now in a different context. My previous question was: Search text box for Search API + Database + Search Views + Facets API + Facets Bonus

That option worked, except I can't use Current Search to reset the search box. I can reset the filters, but not search box. I also can't find an option to allow the user to sort the fields. I installed the Search API Sort module, but was unable to get any fields to be available. I kept hosing my index trying to enable/disable fields, and couldn't figure it out.

My question is how can I use a search form box with Search API + Views that will let me reset the search box with Current Search box, and, how can I have a sort box that will let the visitor select the field to sort by?

My view is rendering nodes via Display Suite view modes. Right now, I am using exposed search and sort filters, but of course, they are grouped in one block. The whole point of my having to use the Search API was to provide filters and decouple my search and sort filters from each other. My sort option will be placed at the top right of the UI, and the sort in the left sidebar.

EDIT: **Using Search API Sorts**, per giga's advice below, I went back and tried to get my fields sortable. I stripped down fields and still no luck getting them sortable. It's a Commerce site, and I'm using the Commerce Search API, which gives me a Product Display index. I originally move fields of content out of the index, so I'm only left with my product display and product fields.

My indexed fields right now are (field, type, boost):

Content type -- String -- 1.0
Title -- String -- 1.0
Date created -- Date -- 1.0
Date changed -- Date -- 1.0
Product Tags -- Taxonomy term
Product Ref -- Commerce Product
Item Type -- Taxonomy term
Weight Sort -- Integer -- 1.0
Product Ref \>\> Price \>\> Amount (decimal)(Min) -- Decimal -- 1.0
Product Ref \>\> Price \>\> Amount (decimal)(Max) -- Decimal -- 1.0
Title (Fulltext) \[search\_api\_aggregation\_1\] -- Fulltext -- 1.0
Product Tags (Fulltext) \[search\_api\_aggregation\_4\] -- Fulltext - 1.0
Item Type name (Fulltext) \[search\_api\_aggregation\_5\] -- Fulltext - 1.0
Product tags \>\> Name -- String -- 1.0
Proudct Ref \>\> Serving Size -- String -- 1.0
Product Ref \>\> Portion Size -- Fulltext -- 1.0
Item Type \>\> Name -- String -- 1.0
Product Ref \>\> Price \>\> Amount (decimal) -- Decimal -- 1.0

The only fields I'm trying to index are Title, Min and Max price, and the Weight Sort as the initial default sort. None of them are showing up in my table of sortable fields under the Sorts tab.

# Answer
It is a known problem in the Sort module's last update. Commenting out the block of code posted here fixes my issue.

To fix the issue use the latest dev version.

https://drupal.org/node/2202093
> 3 votes

# Answer
Search API Sorts only lists the fields of supported types. Make sure the fields you want to sort on are single value strings or numbers.

If the fields are mutli-value you can use Search API Ranges to give you max/min value fields that you can use.

If a field is full-text, one trick is to create an aggregated field containing just that field and assign it a string type.
> 12 votes

# Answer
worked this out...with the help of answer 3,

Commerce kickstart, Search API,

Added Aggregation Field here : admin/config/search/search\_api/index/product\_display/workflow

under the "filters" tab then look for "Callback settings" Click on "Aggregated fields" to turn it in to the active tab

I Added a taxonomy weight field and named it something like "Aggregation Taxonomy Weight " I selected "full text" as the format.

Then Save & Reindex

Then in the "fields" section of admin/config/search/search\_api/index/product\_display/workflow

My new field was showing up for indexing....;-)

Tick new field to be index ...make sure it is a "string"

Save & Reindex

Go to view ...

Add a new CONTEXTUAL FILTER ....look for your new field "Aggregation Taxonomy Weight "

Goto SORT CRITERIA in your view....you new field is available to sort....

Took me three days to work it out LOL!

SO just had to share...Good Luck!
> 4 votes

# Answer
For multi value fields you need denormalization provided by this module https://www.drupal.org/project/search\_api\_grouping
> 0 votes

# Answer
Well, I will try to explain my approach.

I didn't use Sorts module. The steps I took are the following:

1. I made a custom field with this hook: hook\_entity\_property\_info\_alter() in a separate module.
2. In my getter callback I found the weight of the term I wanted and returned it as INTEGER like: return intval($weight);
3. I ticked the newly created field to index it and chose Integer as format. Re-indexed the index.
4. Lastly, in my view in Sort criteria I chose Sort ascending and voila!!
> 0 votes

---
Tags: 7, search, views
---


# Question
Title: Unable to sort view based on search index by taxonomy weight
I have a search index created using search api and I have a view created based on the search index. I have a taxonomy term field called subscription which is indexed. I need to sort my view based on the subscription field and it should be based on the taxonomy term weight and not by the term name. I am able to add the subscription field in my sort criteria but it doesn't seem to be working the way it is expected.

I referred to multiple links but those seem to work only for views based on content and not based on search index.

How do I sort the view(based on Search index) by taxonomy term weight?

# Answer
> 2 votes
I'm not sure if you have figured this out yet, but I found the solution to this, so I'll post it here in case anyone else comes along this page.

If you go to your search index and go to the Fields tab, you'll see at the very bottom there is text that says "Add related fields". It took a while for me to see this there, since it's kind of inconspicuous and under the form submit button. But if you click that and select your taxonomy, it will add the set of taxonomy fields to the available list of fields to index. Check "Weight", then that will be available in your view.

# Answer
> 0 votes
Well, I will try to explain my approach.

I didn't use Sorts module. The steps I took are the following:

I made a custom field with this hook: hook\_entity\_property\_info\_alter() in a separate module. In my getter callback I found the weight of the term I wanted and returned it as INTEGER like: return intval($weight); I ticked the newly created field to index it and chose Integer as format. Re-indexed the index. Lastly, in my view in Sort criteria I chose Sort ascending and voila!!

---
Tags: 7, views, taxonomy-terms, search
---


# Question
Title: how can I use jquery autocomplete in drupal 7
I want to use jquery autocomplete jquery plugin, I test below code but nothing happend, I check, the file added correctly and there is not js error.

```
function imodbdev_form_alter(&$form,$form_state,$form_id){
  if($form_id='movie_node_form'){
      drupal_add_library('system', 'drupal.autocomplete');
      drupal_add_js(drupal_get_path('module', 'imodbdev') . '/js/jquery.livequery.js', array('scope' => 'footer'));
      drupal_add_js(drupal_get_path('module', 'imodbdev') . '/js/imodbdev.js', array('scope' => 'footer'));
  }

}

```

and `js/imodbdev.js` file

```
(function($) {
    Drupal.behaviors.imodbdev = {
        attach: function(context) {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$( "#edit-title" ).autocomplete({
source: availableTags
});
        }
    }
})(jQuery);

```

I had install `jquery update` module and set jquery version to 1.8 .
where is the problem?

**update**

after sometimes I type in textfield to test , I saw `TypeError: c.curCSS is not a function` in firebug, I search this error in google and suggestion in upgrade jquery ui to 1.9.3 but drupal not has version higher than 1.8.

# Answer
> 4 votes
Yes, jQuery UI is available in drupal core.

To include libraries like that you need to call the drupal\_add\_library() function to load the required js & css.

For exmaple:

```
drupal_add_library('system', 'drupal.autocomplete');

```

So where you are adding your javascript, add that first.

For example:

```
// Add the jQuery UI autocomplete library.
drupal_add_library('system', 'drupal.autocomplete');
// Load the custom js for this module.
drupal_add_js(drupal_get_path('module', 'MODULE_NAME') . '/js/SCRIPT_FILE.js');

```

The caps lock parts need to be changed to suit your module.

As for where you would put this, I can't say unless I know where you are putting your code. It could be in your theme or in a custom module.

If it is in your theme then the drupal\_add\_js() part would be drupal\_add\_js(drupal\_get\_path('theme', 'THEME\_NAME') . '/js/SCRIPT\_FILE.js');

I'm also assuming your scripts are in a js sub-directory.

You also need to make sure that any custom js you have is inside a drupal behavior (or $(document).ready() at the very least). Otherwise your javascript will run to early in the page load before the text field even is on the page, so it will do nothing.

It will be like this:

```
(function ($) {
  Drupal.behaviors.yourThemeAutocomplete = {
    attach: function (context, settings) {
      // Your code goes here.
    }
  };
})(jQuery);

```

For more info see https://drupal.org/node/756722#behaviors (the whole page is useful info)

# Answer
> 3 votes
Gleaned from above and a few different sources, this is what worked for me.

1. add jquery.autocomplete to your render array
2. add your data source to your render array
3. add your custom JS to your render array
4. code your custom JS

```
'#attached' => array(
  'library' => array(
    array('system', 'ui.autocomplete'), // 1. add JQUI autocomplete
  ),
  'js' => array(
    array(
      'data' => array(
        'MYMODULE_autocomplete_list' => $my_php_array, // 2. add data
      ),
      'type' => 'setting',
    ),
    drupal_get_path('module', 'MYMODULE') . '/js/autocomplete.js',
    // 3. add custom js
  ),
),

```

);

and in your MYMODULE/js/autocomplete.js as step 4:

```
(function ($) {
  Drupal.behaviors.myModuleAutocomplete = {
    attach: function (context, settings) {
      $("#ID-OF-INPUT-FIELD", context).autocomplete({
        source: Drupal.settings.MYMODULE_autocomplete_list
      });
    }
  };
})(jQuery);

```

# Answer
> 0 votes
It is because of jquery 1.8 used in drupal jquery, according to this issue just need to set jquery to 1.7 and everything work correctly,

---
Tags: javascript
---


# Question
Title: Add a query string to Entity reference Auto complete CCK Field
I have a CCK field that is a Entity Reference with auto complete. And in the "Manage Display" `Link label to the referenced entity`.

How can I add a query string to this URL?

Is there any hook avialabe? I had tried using `<themename>_preprocess_field` but no luck.

Current URL is : example.com/abc Need Query String : example.com/abc?cid=asdfasdf

This is my array. I didnt find `['entity']` entity in the array. Actually it is an taxonomy reference.

```
[field_article_tags] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [tid] => 707
                            [taxonomy_term] => stdClass Object
                                (
                                    [tid] => 707
                                    [vid] => 2
                                    [name] => free prescriptions
                                    [description] =>
                                    [format] => plain_text
                                    [weight] => 0
                                    [uuid] => d185d2a4-59e5-470d-8692-ea23348d7a63
                                    [vocabulary_machine_name] => article_tags
                                    [rdf_mapping] => Array
                                        (
                                            [rdftype] => Array
                                                (
                                                    [0] => skos:Concept
                                                )

                                            [name] => Array
                                                (
                                                    [predicates] => Array
                                                        (
                                                            [0] => rdfs:label
                                                            [1] => skos:prefLabel
                                                        )

                                                )

                                            [description] => Array
                                                (
                                                    [predicates] => Array
                                                        (
                                                            [0] => skos:definition
                                                        )

                                                )

                                            [vid] => Array
                                                (
                                                    [predicates] => Array
                                                        (
                                                            [0] => skos:inScheme
                                                        )

                                                    [type] => rel
                                                )

                                            [parent] => Array
                                                (
                                                    [predicates] => Array
                                                        (
                                                            [0] => skos:broader
                                                        )

                                                    [type] => rel
                                                )

                                        )

                                )

                        )

                    [1] => Array
                        (
                            [tid] => 2157
                            [taxonomy_term] => stdClass Object
                                (
                                    [tid] => 2157
                                    [vid] => 2
                                    [name] => prescription charge
                                    [description] =>
                                    [format] =>
                                    [weight] => 0
                                    [uuid] => 6bf69030-99b9-42e2-83dd-1f63e5a7d1d4
                                    [vocabulary_machine_name] => article_tags
                                    [rdf_mapping] => Array
                                        (
                                            [rdftype] => Array
                                                (
                                                    [0] => skos:Concept
                                                )

                                            [name] => Array
                                                (
                                                    [predicates] => Array
                                                        (
                                                            [0] => rdfs:label
                                                            [1] => skos:prefLabel
                                                        )

                                                )

                                            [description] => Array
                                                (
                                                    [predicates] => Array
                                                        (
                                                            [0] => skos:definition
                                                        )

                                                )

                                            [vid] => Array
                                                (
                                                    [predicates] => Array
                                                        (
                                                            [0] => skos:inScheme
                                                        )

                                                    [type] => rel
                                                )

                                            [parent] => Array
                                                (
                                                    [predicates] => Array
                                                        (
                                                            [0] => skos:broader
                                                        )

                                                    [type] => rel
                                                )

                                        )

                                )

                        )

                    [2] => Array
                        (
                            [tid] => 1515
                            [taxonomy_term] => stdClass Object
                                (
                                    [tid] => 1515
                                    [vid] => 2
                                    [name] => prescription charges
                                    [description] =>
                                    [format] => plain_text
                                    [weight] => 0
                                    [uuid] => 9fed77c3-42c3-421b-ba05-d62b18428702
                                    [vocabulary_machine_name] => article_tags
                                    [rdf_mapping] => Array
                                        (
                                            [rdftype] => Array
                                                (
                                                    [0] => skos:Concept
                                                )

                                            [name] => Array
                                                (
                                                    [predicates] => Array
                                                        (
                                                            [0] => rdfs:label
                                                            [1] => skos:prefLabel
                                                        )

                                                )

                                            [description] => Array
                                                (
                                                    [predicates] => Array
                                                        (
                                                            [0] => skos:definition
                                                        )

                                                )

                                            [vid] => Array
                                                (
                                                    [predicates] => Array
                                                        (
                                                            [0] => skos:inScheme
                                                        )

                                                    [type] => rel
                                                )

                                            [parent] => Array
                                                (
                                                    [predicates] => Array
                                                        (
                                                            [0] => skos:broader
                                                        )

                                                    [type] => rel
                                                )

                                        )

                                )

                        )

                )

        )

```

# Answer
> 0 votes
This is one approach that might work for you, using the preprocess\_page hook (see this tutorial for more background info).

In your theme's template.php, add this:

```
function YOURTHEMENAME_preprocess_page(&$variables) {
   if ($variables['node']->type = 'YOUR_CONTENT_TYPE') {
     debug ($variables['node'], 'Node:', TRUE);
   }
}

```

Then look through your node object and find your CCK field HTML which contains the link, and drill it down on the debug by adding the array/object children until you get the exact path to the link, my guess is it will be something like $variables\['node'\]-\>field\_YOUR\_FIELD\_NAME\['YOUR\_LANGUAGE'\]\[0\]\['entity'\]... and the rest will depend on your entity structure.

Now replace the 'debug' line with your link path and append the value to your link, something along this:

```
$variables['node']->field_YOUR_FIELD_NAME->['YOUR_LANGUAGE'][0]['entity']->value = $variables['node']->field_YOUR_FIELD_NAME->['YOUR_LANGUAGE'][0]['entity']->value . YOUR_QUERY_STRING;

```

---
Tags: 7, entities
---


# Question
Title: Open link as modal form or normal form based on user role
I wish to have a link 'Post Ad':

For anonymous user: a modal login form will be displayed to request log in.

For logged in user: a normal ad posting form.

I managed to use the ctools for modal login form, but i have no idea how to get the normal form to display. (Exception happens when open the normal form, an ajax http error occurred.)

How to achieve this without create two links?

Thanks!

# Answer
> 0 votes
You can look at Menu per Role module, ie link to login form for anonymous users, and link to normal form for authenticated users. another alternative would be to add a hook into the menu in your custom module and change your link based on user's status that way. You can look at this post for info and examples.

---
Tags: 7, chaos-tool-suite
---


title: Get menu item of a node

text:
# Question
Title: Get menu item of a node
I have a node (in D8) which is placed in the menu "Main navigation". How do I get the menu item (in code)? In Drupal 7 you could use `$node->menu` but in 8.x, the object is not populated with menu information. So, how do I retrieve it? I also want to support another type of menus in the future, so something which works with more than the `menu_link_content` module is appreciated.

# Answer
You can try this code:

```
use Drupal\menu_link_content\Entity\MenuLinkContent;

$node_id = 1;
$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$result = $menu_link_manager->loadLinksByRoute('entity.node.canonical', array('node' => $node_id));

dpm($result);

```
> 11 votes

---
Tags: 8
---


title: How to insert form in DataBase

text:
# Question
Title: How to insert form in DataBase
I created my form but inserting the base does not work also radios type does not appear in the form

```
<?php

/**
 * @file
 * Contains \Drupal\contact_form\Form\ContributeForm.
 */

namespace Drupal\contact_form\Form;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Component\Utility\UrlHelper;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ChangedCommand;
use Drupal\Core\Ajax\CssCommand;
use Drupal\Core\Ajax\HtmlCommand;
use Drupal\Core\Ajax\InvokeCommand;

/**
 * Contribute form.
 */

class ContributeForm extends FormBase implements FormInterface{
    protected $accepted_domains = ['gmail.com', 'yahoo.com'];

    /**
     * {@inheritdoc}
     */
    public function getFormId() {
        return 'contact_form_contribute_form';
    }

    /**
     * {@inheritdoc}
     */

    public function buildForm(array $form, FormStateInterface $form_state) {

        $form['FullName'] = array(
            '#type' => 'textfield',
            '#title' => $this->t('Full Name'),
            '#required' => TRUE,

        );
        $form['Email'] = array(
            '#type' => 'email',
            '#title' => $this->t('Email address'),
            '#required' => true,
            '#size' => 60,
            '#maxlength' => 128,

        );

        $form['Feedback'] = array(
            '#type' => 'radios',
            '#title' => $this->t('Feedback'),
            '#description' => t('Type of feedback'),
            '#default_value' => 0,
            '#options' => array(
                0 =>'Comments or suggestions',
                1 => 'Questions',
                2 =>'Report a problem(s)',
                3 =>'Other',
            )
        );
        $form['Subject'] = array(
            '#type' => 'textfield',
            '#title' => $this->t('Subject'),
            '#required' => true,
        );
        $form['Message'] = array(
            '#type' => 'textarea',
            '#title' => $this->t('Your Message'),
            '#required' => true,
            '#cols' => 90,
            '#rows' => 10,
        );

        $form['captcha'] = array(
            '#type' => 'captcha',
            '#captcha_type' => 'recaptcha/reCAPTCHA',
            '#title' => $this->t('Captcha:'),
            '#required' => true,
        );

        $form['save'] = array(
            '#type' => 'submit',
            '#input' => TRUE,
            '#value' => 'save',
            '#submit' => array('buildForm')
        );

        return array(
            '#form' => $form,
            '#theme' => 'contribute',

        );

    }

    /**
     * {@inheritdoc}
     */

    public function validateForm(array &$form, FormStateInterface $form_state) {
    }

    /**
     * {@inheritdoc}
     */
    public function submitForm(array &$form, FormStateInterface $form_state) {
        $name = $form_state->getValue('FullName');
        $email = $form_state->getValue('Email');
        $subject = $form_state->getValue('Subject');
        $type = $form_state->getValue('TypeFeedback');
        $msg = $form_state->getValue('Message');
        $field = array(

            'FullName' =>  $name,
            'Email' => $email,
            'TypeFeedback' =>  $type ,
            'Subject' => $subject,
            'Message' =>  $msg,
            'Etat_message'=>  '',
            'Date_contact'=>  '',
            'adresse_IP'=>  '',
        );
        db_insert('contact')
            ->fields($field)
            ->execute();
        drupal_set_message("succesfully saved");

    }
}

```

# Answer
> 1 votes
Removing the `#submit` key fixed the submission issue for me:

```
$form['save'] = array(
    '#type' => 'submit',
    '#input' => TRUE,
    '#value' => 'save',
    //'#submit' => array('buildForm')
);

```

DB insert works correctly.

If you do `return $form;` in the `buildForm()` method, the radios form element is rendered correctly. Looks like your theme might be causing the issue.

---
Tags: forms, 8
---


# Question
Title: Creating an alternative login page other than /user/login
I have managed to do this in Drupal 7 with the following code:

```
function my_special_paths_menu() {

    $items['authenticate'] = array(
        'title' => 'Log in',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('user_login'),
        'access callback' => 'user_is_anonymous',
      );
     return $items;
    }

```

My question, is this code complete or is it missing some configuration in the menu item array? Is the code safe the way it is?

# Answer
> 7 votes
Yes, your code is complete, and is as safe as the default login form.

However, do bear in mind that if you want to replace the `/user/login` form, you will need to think about all scenarios in which users might end up there (e.g. `[site:login-url]` token, other modules, etc.) and handle them appropriately via redirects or access denied response (e.g. if you will be the only registered user on the site).

Here are the basics:

### Redirecting

If you want to redirect users from `/user/login` to `/authenticate` for whatever reason, you will either need to use the Redirect module, or implement `hook_menu_alter()` in your custom module:

```
function YOUR_MODULE_menu_alter(&$items) {
  $items['user/login']['page callback'] = 'drupal_goto';
  $items['user/login']['page arguments'] = 'authenticate';
}

```

### Replacing

If you want to make `/user/login` inaccessible to all other users, you can simply disable that path by again implementing the `hook_menu_alter()` in your custom module:

```
function YOUR_MODULE_menu_alter(&$items) {
  $items['user/login']['access callback'] = FALSE;
}

```

However, do bear in mind that you will have to test everything thoroughly and make sure that you have no modules that depend on the system `/user/login`, as well as that there are no workflows that will be affected (e.g. `[site:login-url]` tokens).

Hope this helps.

# Answer
> 0 votes
I've used Rename Admin Paths on one of my sites to have another URL instead of /user/... and /admin/... Works great, right out of the box.

---
Tags: 7, forms, users
---


# Question
Title: A non-Views, Panels-compatible slideshow?
The common way to create some variety of slideshow within Drupal is to use Views Slideshow and then display content that way.

However, what if I just want a simple slideshow that appears in all of one Panel on the front page? Creating a new content type (and the requisite nodes) seems fairly overkill.

To that end — is there a slideshow that is both compatible with Panels and able to be invoked without using Views (or otherwise creating a bunch of nodes)?

# Answer
umm sure. you can always make a Block using `admin/structure/blocks` with like `full_html`. You could then easily make whatever HTML markup you need to get your images on the page.

Then in your theme file include a `scripts[] = /path/to/your/js-slideshow.js`.

A slideshow is just a slideshow. For example the slideshow at www.ucsb.edu is simply some HTML for images, 1 custom JS file, and CSS to hide all but the first image initially -- this is easily reproducible with Core Drupal. You could then place the block wherever you want with Panels.

The only caveat with this approach is uploading images from Drupal to power the slideshow is obviously harder since your keeping it very lean and not 100% drupal integrated.

**Edit**

Another example of getting remote images into drupal could be seen here by Fago making Entities from Google Picasa images and slideshows. Unless your comfortable with all this custom code, I dont recommend this type of approach. Drupal may have many approaches to getting something done, but as I mention in my last comment dont fight drupal's conventions or default way of doing something simply learn to embrace it. I've seen this idea spread by MerlinofChaos telling themers (im paraphrasing) "learn to use Views css, even though its ugly -- its feature complete". The same applies to drupal 7 "table per field" default storage structure. When you try to work around what you perceive is a shortcoming you simply fight an uphill battle to make drupal do what you want.
> 1 votes

# Answer
To make a slideshow of all the panels within a panel region, use the Slideshow style in Panels Style Pack. As for the panels to put in that region, if you don't want to use nodes you can do what @tenken says and use custom blocks. Otherwise you can also use Fieldable panels panes to create a Drupal entity just for use in panels. These entities will be more lightweight than full nodes and won't clog up your node management.
> 0 votes

# Answer
I have been experiencing the same issue. In the end I have found the Gallery Formatter module is compatible.
> 0 votes

---
Tags: 7, javascript, panels
---


# Question
Title: A way to make one Drupal site act like several sites
I would like to create several sites each with same number of features (content types) but the ability to select different theme. If I go with multisite feature of Drupal I will have difficulty in setting up and managing all the sites.

I can achieve different sites with Organic groups. But the spaces module is pretty much not working and needs serious development for 7.x version. I tried with all the patches but still it gives me a lot of trouble.

My requirements are more or less same as OpenScholar distribution but I would rather like to use Panopoly (panels) than boxes and context.
Also Openscholar has way too many features that I dont care of and exerts some serious load on the server.

Are there any alternatives to spaces module? Any help would be appreciated. a Case study perhaps.

# Answer
Have you looked at the Domain Access project?
> -1 votes

---
Tags: organic-groups, subsites, distributions, 7
---


title: View with arguments

text:
# Question
Title: View with arguments
Can I build a view with parameters for the app? for example: articles by author and articles that WILL show only the registered user .. Is there an example of module done or I have to build only sight and go. Thank you very much

# Answer
> 0 votes
Thank you for pointing out the lack of documentation on **Page Arguments** for DrupalGap. I went ahead and added a clear example of page arguments here: http://docs.drupalgap.org/7/Pages/Page\_Arguments

A combination of `page_arguments` and a Views Render Array will get the job done.

---
Tags: views, javascript
---


# Question
Title: Use a custom module to add JS to every page in Drupal 8
How can I use a custom module to add JS to every page with Drupal 8?

I've found lots of example scattered over the internet that maybe used to work but no longer work.

# Answer
Assume the custom module is called example.

First create a example.libraries.yml file in your module root folder like this:

```
example:
  version: 1
  js:
    example.js: {}
  dependencies:
      - core/jquery

```

Next in example.module use `hook_page_attachments()` too add your JS to every page:

```
/**
 * Implements hook_page_attachments().
 */
function example_page_attachments(array &$attachments) {
  $attachments['#attached']['library'][] = 'example/example';
}

```

So now the custom module has 4 files:

* example.module
* example.info.yml
* example.js
* example.libraries.yml

`hook_page_build()` and `hook_page_alter()` are now deprecated so can no longer use them.

There is a page drupal.org on adding CSS and JS using a custom module with more information.
> 10 votes

---
Tags: 8, theming
---


# Question
Title: How to alter HTML generated for $messages?
I'm building a theme from scratch using Bootstrap 3. I really don't like the HTML being generated for Drupal's `$messages`. I know I could change the look by using CSS. But I want more control than that, I want to generate different HTML based on type of message (warning, error, etc). I've custom classes & custom images & other custom elements to be used for these messages. I want complete control over the messages. What should I do?

# Answer
You just need to override the theme function...

**theme\_status\_messages($variables)**

https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme\_status\_messages/7

```
function YOURTHEME_status_messages($variables) {
// code goes here...
}

```
> 6 votes

# Answer
Another option here is just to alter the `$_SESSION['messages']` array before they are rendered, say in `hook_page_alter()`.

E.g.

```
/**
 * Implements hook_page_alter().
 */
function example_page_alter(&$page) {

  // I know the message I'm looking for is a status message so if there are non
  // then we have nothing to do here.
  if(!isset($_SESSION['messages']['status'])) {
    return;
  }

  $tracking_code = <<<EOD
<!-- Example traking code -->
<script type="text/javascript">
// code would go here
</script>
EOD;

  // Loop the status messages
  foreach($_SESSION['messages']['status'] as &$message) {
    // If the message matches the pattern then we've found it
    $pattern = '/^You are now subscribed to the ".+" list./';
    if(preg_match($pattern, $message)) {
      // Here I'm adding a tracking code to the end of the message but you could
      // alter or replace the html
      $message .= $tracking_code;
    }
  }

}

```
> 0 votes

---
Tags: theming, status-messages
---


# Question
Title: How to link the file icon to the file and to hide the filename?
I have uploaded files to be displayed in a table together with some other informations (title, tags etc). One row of this table the filename which links to the downloadable file. Next to the filename a file icon is displayed be daefault, which isn't linked.

That's how it looks now:

I want the filename to be hidden and the file icon linked to the downloadable file.

What functions would I have to override to make that happen? Or what other way may exist?

# Answer
> 5 votes
The problem with generic file display is that icon is not linkable, therefor a CSS solution is useless.

So in order to make the icon linkable you need to create another file display formate or alter `theme_file_link`

My solution is to add additional display formate, code as follow:

```
/**
 * Implements hook_field_formatter_info().
 */
function mymodule_field_formatter_info() {
  return array(
    'mymodule_link_icon' => array(
      'label' => t('Linkable icon'),
      'field types' => array('file'),
    ),
  );
}

/**
 * Implements hook_field_formatter_view().
 */
function mymodule_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();

  switch ($display['type']) {

    case 'mymodule_link_icon':

      foreach ($items as $delta => $item) {

        $file = (object) $item;

        $url = file_create_url($file->uri);

        $icon_directory = variable_get('file_icon_directory', drupal_get_path('module', 'file') . '/icons');

        $icon = theme('file_icon', array('file' => $file, 'icon_directory' => $icon_directory));

        $options['attributes']['title'] = check_plain($file->filename);

        $options['html'] = TRUE;

        $link_icon = '<span class="file">' . l($icon, $url, $options) . '</span>';

        $element[$delta] = $element[$delta] = array('#markup' => $link_icon);
      }

      break;
  }

  return $element;
}

```

After you implement the above code in a module and enable it, make sure to change field formatter option in your view to **Linkable icon**

# Answer
> 2 votes
Finally with a lots of help, I created a **views-view-field--nameofmyview--nameofmycontenttypefield.tpl.php** inside the sites/all/themes/mytheme/templates folder.

First I clicked on that link inside that view: There a lot of templates are suggested referring to different fields of that view. I had to choose and create one template as suggested from **field content: file (id: nameofmycontenttype\_field)**.

Every suggested template has another range, where to take effect. Clicking on **field content: file (id: nameofmycontenttype\_field)** also shows you the default code you have to add to that template file.

As said in the beginning, I created **views-view-field--nameofmyview--nameofmycontenttypefield.tpl.php** and after some dpm($rows) and finding out which variables, obects and arrays I need I had to add the following code inside that template file:

```
<?php
if (!empty($row->field_nameofmycontenttype_field["0"]["raw"]["fid"])) {

  $file = file_load($row->field_nameofmycontenttype_field["0"]["raw"]["fid"]);
  $icon = theme("file_icon", array("file"=>$file));
  $url = file_create_url($file->uri);

  $output = l($icon, $url, array("html"=>true));

  print $output;
}
?>

```

...and that works fine for me. Clickable icons linking to the original file. Only visible in the frontend though, not in the backend preview.

That one helped me a lot, too: http://drupal.org/node/600798 (but it's for D6).

# Answer
> 1 votes
I tried a little trick to solve this. Cause I had the same problem.

* I override theme\_file\_link() and place the icon inside the .
* To hide the file name, I use CSS, and hide the text-link.

```
 function ufdesign_file_link($variables)
 {
  $file = $variables['file'];
   $icon_directory = $variables['icon_directory'];

  $url = file_create_url($file->uri);
  $icon = theme('file_icon', array('file' => $file, 'icon_directory' =>            $icon_directory));
  // Set options as per anchor format described at
  // http://microformats.org/wiki/file-format-examples
  $options = array(
  'attributes' => array(
  'type' => $file->filemime . '; length=' . $file->filesize,
  ),
 );

  // Use the description as the link text if available.
 if (empty($file->description)) {
   $link_text = $file->filename;
  }
  else {
   $link_text = $file->description;
   $options['attributes']['title'] = check_plain($file->filename);
   }
    return '<a href=' . $url . '>' . $icon . ' <span class="file">' .    l($link_text,    $url, $options) . ' </span></a>';
  }

```

---

//And the CSS

```
.brochurelink {
 float: left;
 padding: 0.5em;
 text-align: left;
 width: 176px;
 white-space: nowrap;
 overflow: hidden;
 text-overflow: ellipsis;
 max-width: 11px;
}

```

# Answer
> -1 votes
Edit file **file.module** in path **/modules/file**

Returns HTML for an image with an appropriate icon for the given file.

> * @param $variables
> * An associative array containing: -file: A file object for which to make an icon.
> * + icon\_directory: (optional) A path to a directory of icons to be used for files. Defaults to the value of the "file\_icon\_directory" variable.
> * + alt: (optional) The alternative text to represent the icon in text-based browsers. Defaults to an empty string.
> * @ingroup themeable

```
function theme_file_icon($variables) {
  $file = $variables['file'];
  $alt = $variables['alt'];
  $icon_directory = $variables['icon_directory'];

  $mime = check_plain($file->filemime);
  $icon_url = file_icon_url($file, $icon_directory);
  $url = file_create_url($file->uri); /*Thêm đường dẫn file */
  return '<a href='.$url.'><img class="file-icon" alt="' . check_plain($alt) . '" title="' . $mime . '" src="' . $icon_url . '" /></a>'; /* Thêm link vào icon */
}

```

Then using css to hide the filename. Thanks **Mahyar Farshi** for share.

---
Tags: 7, files
---


# Question
Title: how to add a remove coupon button to commerce checkout page
I assumed this would be included in the module, but as far as i can see it isn't. Im using the latest versions of Commerce, Rules, and Commerce Coupon.

I want a "remove" button next to the added coupons in case someone wants to remove it and try another one.

# Answer
> 0 votes
I was not able to recreate your issue. 'Remove' button was available next to the applied coupon.

The version of coupon code, I'm using is 7.x-2.0-rc2.

The steps I took were:

1. Added a discount and associated a coupon code with it.
2. Added an item to cart and checked out.
3. After confirming checkout was given option to add coupon code.

Checkout settings:

**Note:**

> The problem could be with checkout page. You can use `order_coupon_list` view block below the coupon code apply form.

---
Tags: commerce
---


# Question
Title: Copy path to variable in array using Kint
In D7 using `dmp()` with Krumo in produced output like this:

Double clicking on a variable value, in this case "foobar" shows the path through the array to that value (the highlighted text in the image above).

Now with D8 it's using Kint not Krumo and produces output like this:

Is there anyway to copy the path to "foobar" using kint?

This is the text that I want: `['example']['#attributes']['class'][0]`

# Answer
It seemed there was no solution so I just copied the search\_krumo module and changed it a bit so it works with Drupal 8 and kint and made search\_kint.

I've only just done the first push so isn't showing as a download yet; and there is only a development snapshot release, at the moment, but it's something to get started with.

So far, it has worked well with my testing.

EDIT: search\_kint now has a full release.
> 6 votes

---
Tags: 8, debugging
---


# Question
Title: How to load nodes that are associated with the child of a taxonomy term
This questions has some similarities with How to display list of nodes that share the same Parent taxonomy term as current node, but I've not managed to figure out how I can get to what I need to do given the answers there.

A have a set of nodes that are associated via term reference with a taxonomy, that is two levels deep. I'll call the parent level area and the child level task.

This is a migration from another website that has pages for publications associated with each area but in my current data structure I only associate the publication nodes with the tasks (children of the areas). The areas each have a legacy\_area\_id field populated with the area id that was used in the url on the old site.

What I want to do now is create a view that will listen on pub/by/area/% and take a legacy area id as a contextual filter, and show a list of all nodes associated with a child of the taxonomy term that has that value in its legacy id field.

An example:

With a data setup like this, a request to /pub/by/area/1

Should return a listing containing Nodes 1, 3, and 4

---

One option would be to go back and change my migration to associate the publications with areas too, but that seems likely to make the task of moving tasks between areas later quite a bit more complicated.

Another option would be to add the legacy area id to the tasks as well, but that provides similar challenges.

In reality, my end goal is to redirect these pub/by/area/# requests to a different view with the area name in the url similarly to what I've done for other old addresses in How to redirect based on matching a node field?. So really I suppose all the view really needs to give me is the data required to redirect to another view. I'll keep working on this, but help would be appreciated.

# Answer
# My solution in two parts

I got it, and I couldn't have gotten to it without the other answers, but in the end it turns out that this solution wasn't necessary. The end goal was to redirect to a named area page and nothing about the view below gets me easy access to the tid for the appropriate area and redirect to the right page. I put in my custom module code below this. Really all the view needs to be is something that takes the legacy area id as an argument from the url

## The View

I created a page and added two relationships to it:

* Content: Taxonomy terms on node (Identifier term)
* (term) Taxonomy term: Parent term (Identifier Area)

and a contextual filter:

* (Area) Taxonomy term: Legacy Area ID

I still have some testing to do to make sure it is grabbing the right things, but so far it seems to be working correctly.

## Getting the tid and redirecting

```
/**
 * Implements hook_views_pre_render().
 */
function env_views_views_pre_render(&$view)
{
    if ($view->name == 'pub_by_docid') {
        if ($view->current_display == 'pub_by_area') {
            $areaid = (int) $view->args[0];
            $query = new EntityFieldQuery();
            $query->entityCondition('entity_type', 'taxonomy_term')
                ->entityCondition('bundle', array('area'))
                ->fieldCondition('field_tax_legacy_area_id', 'value', $areaid, '=');
            $result = $query->execute();
            $tid = array_shift($result['taxonomy_term'])->tid;
            drupal_goto(drupal_get_path_alias('taxonomy/term/' . $tid), NULL, 301);
        }

    }

    // any other pre_render()ing here

}

```

If you can think of how I could do this better, I'd love to hear about it!
> 1 votes

# Answer
visabhishek answer gave me an idea.

Create a tax term page view:

* Add Legacy ID as your contextual filter
* In FIELDS add term ID (so you will get the term ID of Area 1. You can hide it using exclude from display.)

Then using the Views Field View module

> This module allows you to embed a view as a field in a view.

* Add the view from visabhishek answer as a field. For Contextual filter you can pass the term ID as a token (using replacement patterns)

Problem solved :)
> 1 votes

# Answer
Just try once following points

* Go to admin/structure/views, find the view named Taxonomy term, and enable it
* Go to admin/structure/views/view/taxonomy\_term/edit or Clone this view and create new view with different path
* Click Advanced (on the right)
* Click Content: Has taxonomy term ID (with depth)
* Select a Depth of 1 or more (how much depth term nodes you want)
* Save all your changes

Hope it will help you...

:)
> 0 votes

---
Tags: 7, views
---


# Question
Title: how to select particular product from bunch of products
I have two fields in my content type. one field(seat) has more than 10 products( product reference ) and another field (default). while selecting one product in the seated field ,should be shown in the default field. I do not know how to get that product from seat to default. How to solve this ?

# Answer
You could use the Rules module to react on a node save, check if the field has only one value and alter the values of the node as needed.

Or you can write your own module and use the form\_set\_value() function to change the submitted values in a (custom) validation function. Your validation function can be attached to the node edit form by implementing hook\_form\_FORM\_ID\_alter() and adding the function to the `$form['#validate']` array.
> 0 votes

---
Tags: commerce
---


# Question
Title: How to restrict who can VIEW content of selected content types using Organic groups?
Using Organic groups 7x-2.7, how can I restrict which users are able to view certain content types?

# Answer
> 0 votes
Maybe you want to give it a try to use the Group module, either as an alternative for Organic Groups (as more and more people seem to be doing), or as an addition to it.

Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. It is designed to be an alternative to Organic Groups. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

For this specific question, you'd enable the `gnode` submodule, and for each group type you would define the appropriate permissions (view, edit, delete, etc) for the various Content Types. That's it.

For more details about how Group compares to Organic Groups, refer to my answer to "What are the features of the Group module versus Organic Group module?".

# Resources

---
Tags: 7, users, organic-groups
---


title: Order discounting

text:
# Question
Title: Order discounting
I am using the Drupal Commerce module. On the checkout page, I need to add 'Subtotal' and 'Discount' fields above the 'Order total'.

The discount will be calculated by iterating through all products in the cart and (using some unique and complex PHP business logic that I won't get into here) calculating how much discount each product is eligible for.

The discount total will then be displayed in a 'Discount' field between 'Subtotal' and 'Total'. The product prices should not be discounted.

Any Suggestions?

# Answer
> 0 votes
So you will have to use the Rules modules with this

I guess its would something like : Calculating the sale price of products. Data comparision conditions should be added to this, then multiply the unit price by a certain amount, This would remove some % of the individual products which would give you the feature of removing it from the total amount.

Hope this help you

Commerce Conditions

This link, might also give you closer indicator of how to solve the problem

# Answer
> 0 votes
Check out the Commerce Price Savings Formatter module.

---
Tags: 7, commerce, rules
---


# Question
Title: How to programmatically create new revision and publish it?
(I am using Revisioning.) I call `node_load(nid, vid)` (with the latest version id), give new values to some fields, and then save the node. Setting `$node->is_current = TRUE` before saving will ensure that this version of the node is now published. However, it does not create a new revision. So I try setting `$node->revision = TRUE` also, but this creates a new **unpublished** revision which is not what I would expect.

How can I edit a node, and save it as a new revision *and also as* the current published revision? Not sure if it is a bug in the module.

```
// Node has some new revisions since the version that is currently published.
$vid = revisioning_get_latest_revision_id($nid);
$node = node_load($nid, $vid);
$node->revision = TRUE;
$node->is_current = TRUE;
$node->status = 1;
node_save($node);
// New revision created, but not published.

```

# Answer
I think it will work when you explicitly set `revision_moderation` to `FALSE`. If moderation is not required, it should be published right away.

```
$vid = revisioning_get_latest_revision_id($nid);
$node = node_load($nid, $vid);
$node->revision = TRUE;
$node->is_current = TRUE;
$node->status = 1;
$node->revision_moderation = FALSE;
node_save($node);

```

From the example here: http://drupalprogrammatically.com/anwsers/7/create-node

Poster of above url also sets `$node->revision = FALSE;`, but that would give me the impression no new revision is saved, which is not what you want. I hope it helps.
> 3 votes

# Answer
Too easy - just separate the steps. First set a new revision and save, then load it again and adjust the fields and set published and save.
> -1 votes

---
Tags: 7, nodes
---


# Question
Title: Drupal Commerce: Get selected payment method programmatically
Is there any way to get programmatically the selected (by customer) payment method from the $order\_wrapper variable in Drupal Commerce?

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

```

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

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

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

```
> 3 votes

# Answer
Each payment method is a rule. Let's get the rule name than:

```
$payment_method = '';
$order = commerce_order_load($order_id);
$r = explode('|', $order->data['payment_method']);
if (count($r) > 1){
  $rule = rules_config_load($r[1]);
  $payment_method = $rule->label;
}

```
> 3 votes

# Answer
Based on Clive's answer above here's a rules condition set up for order is payment method.

Replace custom\_commerce with the name of your module.

```
// custom_commerce.rules.inc

/**
 * Implements hook_rules_condition_info().
 */
function custom_commerce_rules_condition_info() {
  $conditions = array();

  // We have two or more payment methods we sometimes need to distinguish
  // between them.
  $conditions['custom_commerce_order_is_payment_method'] = array(
    'label' => t('Order is Payment Method'),
    'parameter' => array(
      'commerce_order' => array(
        'type' => 'commerce_order',
        'label' => t('Order'),
      ),
      'commerce_payment_method' =>array(
        'type' => 'text',
        'label' => t('Payment Method'),
        'options list' => 'custom_commerce_payment_method_option_list',
      ),
    ),
    'group' => t('Custom Commerce'),
    'callbacks' => array(
      'execute' => 'custom_commerce_order_is_payment_method',
    ),
  );

  return $conditions;
}

/**
 * @param stdClass $order
 * @param string $expected_payment_method
 * @return bool
 */
function custom_commerce_order_is_payment_method($order, $expected_payment_method) {
  $query = new \EntityFieldQuery();
  $query->entityCondition('entity_type', 'commerce_payment_transaction')
    ->propertyCondition('order_id', $order->order_id);

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

/**
 * Returns key value pairs for the rules parameter drop down.
 */
function custom_commerce_payment_method_option_list() {
  $payment_methods = commerce_payment_methods();

  return array_map(function($v) {
    return $v['title'];
  }, $payment_methods);
}

```
> 1 votes

---
Tags: commerce
---


# Question
Title: how to count the results from the exposed filter
I have created the content type named candidate\_profile, included fields like candidate\_name, current\_position\_description, location , Current\_Salary\_Range, New\_Business\_Achievements and Categories\_ of\_Experience and I have created a view named display\_candidate and also I am using better-exposed filter for current\_salary\_range field hence how should I proceed to count the results from the exposed filter...?

# Answer
You can get that in the `view` itself.

```
view->Header->"Global: Result summary"

```
> 2 votes

---
Tags: views
---


# Question
Title: Is it important to reset the $user object when accessing global $user?
I see that some developers reset the $user object in a manner similar to the following:

```
function my_example_callback($args) {
  global $user;
  $account = $user;
  $user = user_load(1); // Bypass access checks with User 1.
  $data = views_embed_view('my_view', 'page', $args);

  // Do things..

  // Reset the $user to the original value.
  $user = $account;

  return $data;
}

```

My question, is this really necessary? If so in what situations?

# Answer
> 3 votes
It depends..

Since you load the user object from the global scope, everything you change on it will affect other functions further down the line.

If you make alterations to the user object that only apply to your module, you might want to reset those changes so other modules won't be able to see the alterations you made. Think about adding something like adding a security key, then run it through some of your functions. You don't want other modules and functions to see the key, so you want to remove it from the user object after your functions are done with it.

For only loading the user and reading it, I'd say it doesn't make sense to reset the variable.

Update

As for your example, to bypass the access check the global user object (current logged in user) is swapped with the object of user 1. In this case it is very important to switch back, otherwise all other functions will see you as user 1 rather than your own account!

See https://www.drupal.org/node/218104 for documentation on impersonating other users.

---
Tags: users
---


# Question
Title: 'After update' event firing when node is deleted
I have a rule set up that uses the following action:

> After updating existing content of type

It's working fine when a node is updated, but I just discovered that this rule also fires when nodes of the specified type are deleted. This makes sense, since changing the status of a node is technically an update, but this is not the desired effect as emails should not be sent when the node is deleted.

I added a small chunk of PHP inside the email generated by the rule to see what the value of $node-\>status is in this rule, but it is still 1, not 0 as I expected.

How can I use the '`After updating existing content of type`' event, but not have it react when a node of that type is deleted?

# Answer
> 1 votes
Have you tried adding a rules condition for the published status of the updated node? That should stop the rule from firing.

# Answer
> 1 votes
I dont think it will react on node deletion also, as I had tested it.

'After updating existing content of type' event it will use hook\_node\_presave(), so it will never trigger hook\_node\_delete()

Have a look on any other Rules overriding that.

---
Tags: rules
---


title: How to get feature in list?

text:
# Question
Title: How to get feature in list?
I created a feature and I can download it directly.

But how do I get it in the list (/admin/structure/features) in order to recreate it?

# Answer
> 1 votes
When you create a feature it will make that feature as a module. So, after it got downloaded you need to put those files in to `sites/all/modules/` and then enable it from `admin/modules`. So you can see that `(/admin/structure/features)` .

---
Tags: features
---


title: How to build an Offer System?

text:
# Question
Title: How to build an Offer System?
I'm looking for a solution to build an offer system relatively similar to upwork:

* Offer system (fieldable) attached to a Node.
* User can make only 1 offer per node.
* User can only view his own offer and its replies by the node author.
* Node author can view all offers and can accept, reply, and reject.

I tried to do it with the comments system but it wasn't as flexible as I thought.

Any suggestions?

# Answer
You might want to start from the Answers module. Here are some details about it (from its project page):

> Answers enables the implementation of a Question & Answer system in a Drupal site. Users can post questions and other users can answer them.

Head over to its project page for more details.

The **question** would be about something being searched for (wanted, aka the demand), like goods, properties or services for sale or for rent. And the **answer(s)** consists of one of more possible offers (the fullfilment of the request in the demand). Variation of this are Classified Ads or Auctions.

At its core, this module exists of 2 typical content types:

* Question.
* Answers.

The Answers module comes with integrations with other modules such as the Rules module and the Userpoints module (and supports voting, which in this use case may not be needed, unless you want users that evaluate offers to use it).

I see these enhancements you'd have to do to fit your requirements:

* If you'd add the Content Access module you should be able to tune its permission to fit your needs.
* To enforce your "User can make only 1 offer per node" requirement, you could use the Rules module to create a custom rule for that.

To be complete:

* Since Questions and Answers are just nodes, "(fieldable) attached to such node" is just out-of-the-box.
* You can use the "Best Answer" submodule for implementing "Node author can accept". And you could make the Rules module trigger all sorts of subsequent things to happen "when an answer gets marked as best answer".
* Posting replies is just standard "node comments", but you may also want to use the "subscribe" feature (based on the "message stack").
* The "Reject" feature could be as simple as an extra flag implemented via the Flag module (which is a dependency of the Answers module already).

To decide between the **7.x-3.2** and the **7.x-4.0-rc2** release, I would recommend the 7.x-4.0-rc2 (which also has the shiny new theming stuff ...). Even though it is not yet an official release, it is fairly stable/functional, and only has a few more minor glitches to be resolved. Pretty soon an rc-3 (the last 'rc' release?) should become available also, which will include the newest features as you can see in the demo site already. More important: if you're just starting with the module, you won't have to "migrate" from 3.x in the future (some type of migration will be needed, which is still an open issue for now).

Disclosure: I'm a (co-)maintainer of this module.
> 1 votes

---
Tags: 7
---


# Question
Title: is it possible to edit default output of services module?
Is it possible to edit/customize the default output we get using Services Module ?

For example I want to edit output which I get from this URL : http://example.com/api/node/39

And I want to edit output of this URL : http://example.com/api/user/39

OR is there any way to create a View for single user profile ?

# Answer
Using the Services API this is possible: http://cgit.drupalcode.org/services/tree/docs/services.alter.api.php?h=7.x-3.x

```
/**
 * Implements hook_services_request_postprocess_alter().
 */
function example_services_request_postprocess_alter($controller, $args, &$result) {
  switch ($controller['callback']) {
    case '_node_resource_retrieve':
      $result->foo = 'bar';
      break;
    case '_user_resource_retrieve':
      $result->bar = 'chew';
      break;
  }
}

```

You could use the Views JSON module (a sub module of the Views datasource module) to build a View with a User ID contextual filter, and then return the field(s) you want for that particular user.
> 2 votes

# Answer
Are you aware of the Services Views module?

It allows you to create a services path and you can control the output with Views.

From the question:

> Is there any way to create a View for single user profile ?

From the module:

> ## Executing view via views resource
>
> After enabling "views" resource in your services endpoint you can do GET request to:
>
> `http://example.com/<endpoint path>/views/<view name>`
>
> This will execute a view and pass results.
>
> Possible arguments:
>
> * display\_id: views display
> * args: array of view arguments
> * filters: array of view filter values
> * offset: views offset
> * limit: limit views number of results
> * format\_output: boolean whether we would like to get themed view or data

This module supports Views arguments (args), which are known as 'Contextual filters' in the Views UI. So if you create a contextual filter for the `uid`, and you pass the `args` in your request it should work.

Something like `http://example.com/rest/views/users?args[uid]=5` or `http://example.com/rest/views/users?args[0]=5` probably works.

Please note that this method does not alter the output of the existing services endpoints, but creates a new path.
> 0 votes

---
Tags: views, services
---


# Question
Title: How do I get kint() to include the variable name in output?
My understanding that normally kint will display the variable name in the output, e.g. `$abc`. But in my code `kint($abc)` never outputs the `$abc` label so when I have multiple `kint`s it becomes very confusing. Any idea how to force this or label kint output?

# Answer
Put the variables in an array. Then you see the variable names and you have the advantage, that if the first variable is a big array you can collapse it to see the second one:

```
kint(array(
  'abc' => $abc,
  'def' => $def,
));

```
> 2 votes

---
Tags: 8, debugging
---


# Question
Title: Drupal 7: Menu item being accessed even with false access callback?
I have a menu item:

```
$items['login-now'] = array
(
    'title' => 'Log In',
    'page callback' => 'some_or_other_method',
    'access callback' => 'the_permissions_function',
    'menu_name' => 'menu-ecommerce-nav',
    'type' => MENU_NORMAL_ITEM,
    'weight' => '5',
);

```

And then I have:

```
function the_permissions_function {
    $isAnonymousUser = user_is_anonymous();
    if (!$isAnonymousUser) {
        return FALSE;
    }
    return TRUE;
}

```

This works if I am logged out. I can see the "log in" button. But when I log in, it STILL shows this login button. Why?

What's interesting is, I added this above the "return false"

```
print 'xxxx'; die();

```

And it hits this code!! But for some reason, it still shows the menu item? Why is it not hiding the menu item?

**UPDATE**

Even if I just do this:

```
'access callback' => 'user_is_anonymous',

```

It STILL shows the "log in" menu item when I am LOGGED in. Why on earth is it doing this? What am I missing?

# Answer
user\_is\_anonymous() returns TRUE if the user is a menu administrator: see function user\_is\_anonymous

Try user\_is\_logged\_in() instead, e.g.:

```
function the_permissions_function {
    $isLoggedIn = user_is_logged_in();
    if ($isLoggedIn) {
        return FALSE;
    }
    return TRUE;
}

```
> 0 votes

# Answer
Your menu gets cached, so you need to clear the caches after you change something in you hook\_menu() or hook\_menu\_alter().
> 0 votes

---
Tags: users
---


# Question
Title: What is the difference between the config and the settings directories?
I can see a folder named config in Drupal 8 core modules which contains sub directories like optional, schema and install.

I can see it is like a settings folder which is initialised during module installation. But how do they differ from each other?

# Answer
* *schema*
This folder is used for schema related things. This is most often used to tell Drupal how custom configurations and configuration entities will be saved.
* *install*
The folder can contain configurations, for example a view. All configurations will be installed; if any configuration fails, the module can't be installed.
* *optional*
The folder can contain configurations, for example a view. All configurations will be installed if possible. If a configuration has missing dependencies, it won't be installed.

Configuration installation only happens when the module itself is installed. Optional configurations can install missing configurations when dependencies are met by a new installed module.
> 8 votes

---
Tags: 8, configuration
---


# Question
Title: Features + user permissions: what are the pros and cons of all in one versus separate?
I need to carry out a review of our user roles and permissions. Currently some roles and permissions are already bundled into existing features (usually custom content types), but most are not. I would like to get everything committed into features to kick-start the review.

**What are the pros and cons of either of these approaches:**

1. Have one 'roles and permissions' feature that collects all of the roles and permissions? (This adds a lot of modules as dependencies.)
2. Include roles and permissions into other features when needed? (This might still require a separate feature for the permissions that don't fit into other features.)

Alternative methods (eg to help reduce the amount of roles/permissions) welcome too!

Note: a lot of our custom content types share reusable fields, which will need to have user permissions defined for them.

# Answer
In terms of the user experience, listing the permission along with the feature is the better option. You will need to be searching a very long list if your permissions are complex and extensive.

The even more compelling reason to keep the feature and permissions together is for exporting. If you only plan to export a particular feature, it takes a long with it dependencies from a bunch of other modules.
> 1 votes

# Answer
I'm not a features expert (or fan), but the approaches you wonder about are a ('the'?) typical challenge (pain?) in using Features. Therefor I think you should give it a thought if you can simplify the roles/permissions you are currently using. Read on for a possible approach about that, using the Group module, considered as an alternative for Organic Groups (which many people are familiar about).

Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. The Group module creates groups as entities, making them fully fieldable, extensible and **exportable**.

For this specific question, you'd enable the `gnode` submodule, and for each group type you would define the appropriate permissions (view, edit, delete, etc) for the various Content Types. That's it.

So it'd take some thought about how your groups and group types should look like, and what the Groups related "**roles**" and "**permissions**" would have to be for your various users. Those roles and permissions are specific to the Group module, and even though they have the same name as in Drupal core, they are not the same. After you complete your Group based roles/permissions, I bet you could get rid of quite a few of your existing roles/permissions (which make the remaining one more manageable).

After you've configured the Group module to fit your needs, you can "export" your roles/permission. Using Features I would recommend 1 single feature for this, obviously using the Group module (only?) as a dependency.

# Resources
> 0 votes

---
Tags: 7, users, features
---


# Question
Title: Trouble passing PHP variables to JS using "attach"
Module-noob here. I've seen plenty of threads on this topic in general but haven't found any concerning use of "attach." I'm working on a fairly simple module that applies some JavaScript to every page on the site. It was working fine, but pareview told me not to use drupal\_add\_js() in hook\_page\_build(), instructing me to use attach instead. I can't figure out how to get my PHP variables over to my JS using this method.

The JS file itself is loading, but it is not receiving the data from the PHP variables. From what I have read, I understand that the following is the way to accomplish what I am trying to do, but obviously I've got something wrong somewhere. Here is my code:

**mymodule.module:**

```
function mymodule_page_build() {

  $page['#attached']['js'] = array(
    array(
      'data' => drupal_get_path('module', 'mymodule') . '/mymodule.js',
      'options' => array(
        'preprocess' => TRUE,
        'every_page' => TRUE,
      ),
    ),
    array(
      'data' => array(
        'mymodule_status' => variable_get('mymodule_status', 0),
      ),' => 'setting',
    ),
  );
}

```

**mymodule.js:**

```
(function ($) {
  "use strict";
  Drupal.behaviors.myModule = {
    attach: function (context, settings) {
      var moduleStatus = Drupal.settings.mymodule.mymodule_status;
      var milk = 'milk';
      $(document).ready(function () {
        // Debug:
        console.log('first');      // works
        console.log(milk);         // works
        console.log(moduleStatus); // Says mymodule is undefined
    }
  };
})(jQuery);

```

Thank you for any help you can offer.

# Answer
It turns out there were two problems.

First, I needed to be using `function mymodule_page_build(&$page)`. I was originally leaving out the `&$page`.

Second, it turns out that to use `#attached` on the page itself, you have to access the 'content' property of the page.

So, instead of:

`$page['#attached']['js']`

It should be:

`$page['content']['#attached']['js']`
> 1 votes

# Answer
Have a look on this page

For getting the value of a variable that has been set in the module you have to use like this `Drupal.settings.<modulename>.<variablename>`

In your module file

```
function mymodule_page_build() {
  $status = variable_get('mymodule_status', 0);
  drupal_add_js(array('MODULENAME' => array('mymodule_status' => $status)), 'setting');

  $page['#attached']['js'] = array(
    array(
      'data' => drupal_get_path('module', 'mymodule') . '/mymodule.js',
      'options' => array(
        'preprocess' => TRUE,
        'every_page' => TRUE,
      ),
    ),
  );
}

```

So in your case it should be

`Drupal.settings.mymodule.mymodule_status`
> 1 votes

---
Tags: 7, javascript
---


# Question
Title: Allowed types for DataDefinition::create()
I'm creating a new Field Type in Drupal 8. What types can I pass to `DataDefinition::create()`?

# Answer
> 7 votes
The types are defined as DataType plugins. You could also implement additional ones, but that's not necessary very often, since all the basic scalar data types exist already.

# Answer
> 3 votes
Do a file search for `@DataType` you will find every data type in the system.

---
Tags: entities, 8
---


# Question
Title: How do I group by and display only first row of each group?
I want to apply aggregation on my view so that only first row of each group should be displayed after group by aggregation.
I have a view with two fields Subject and Due\_Date and sorted values like,
Subject Due\_Date
A 2016-03-24
A 2014-06-28
A 2012-10-15

B 2013-11-21
B 2011-10-18
B 2010-03-04

C 2013-07-13
C 2012-12-09

After group by aggregation I want it to have like this,
Subject Due\_Date
A 2016-03-24
B 2013-11-21
C 2013-07-13

It should only have the first row of each group.

I have tried Views aggregator plus, but it is just hiding the values and not eliminating them. With that I couldn't get my filters working the way I need.
Is there any solution for this to work?

# Answer
If you are using D7 - View Merge Rows module can provide the functionality that you need.

In your scenario, select field subject as Grouping field Nr.1.

Access Merge setting in Advanced section of your View.

For the `Subject` field - select the setting "`Use values of this field as a filter`".

For the `Due_Date` field - select the setting "`Use the first value of this field`".

If your View contains more than two fields, you will need to select the settings for `Merge rows` to accommodate processing of added fields.
> 1 votes

---
Tags: views
---


# Question
Title: AJAXX AutoComplete joins and unions causing error
I am a bit out of my depth here.

I have successfully implemented my own autocomplete field of an entityform, the following link was my roadmap Textfield that uses AutoComplete.

But I am trying to do something much more fancier. I need to search for a users name, and autocomplete it for the user. The issue I am having is that I must check multiple tables for the user to select from, tables like: `field_data_field_first_name`, `field_data_field_othername`, `field_data_field_nickname`, `field_data_field_fullname`.

Because some people's names have changed, or have a nickname.

So I have begun checking multiple tables and think I got a good start, but I keep getting the following error: `"SQLSTATE[21000]: Cardinality violation: 1222 The used SELECT statements have a different number of columns"`

I want to be able to incorporate this:

```
 SELECT fn.*, ln.* FROM field_data_field_first_name as fn
    left join field_data_field_last_name as ln ON fn.entity_id = ln.entity_id
    WHERE fn.field_first_name_value LIKE '%bun%'
UNION
SELECT fn.*, fo.* FROM field_data_field_first_name as fn
    left join field_data_field_other_name as fo ON fn.entity_id = fo.entity_id
    WHERE fn.field_first_name_value LIKE '%bun%'
UNION
SELECT ni.*, ln.* FROM field_data_field_nickname as ni
    left join field_data_field_last_name as ln on ni.entity_id = ln.entity_id
    WHERE ni.field_nickname_value LIKE '%bun%'
UNION
SELECT ni.*, fo.* FROM field_data_field_nickname as ni
    LEFT JOIN field_data_field_other_name as fo ON ni.entity_id = fo.entity_id
    WHERE ni.field_nickname_value LIKE '%bun%'

```

into Drupal 7 `db_select`. I have some of this query in my Drupal query (not all of it, for the moment) but I am getting the column discrepency error (1222), my column counts aren't matching. Can't I just grab every field, like I do in my MySQL string and call it a day? I thought `fields('alias')` would of solved this, since that is grabbing every column, but it doesn't seem to be doing the trick! This is what I got now:

```
$secondQuery = db_select('field_data_field_first_name', 'f') ->fields('f')
      // check the first_name_value, but we want to do a leftJoin to show the left_name_value as well! like Larry, Adams, not just Larry
      ->condition('field_first_name_value', '%'. db_like($string) .'%', 'LIKE');
    $secondQuery->leftJoin('field_data_field_last_name', 'l', 'f.entity_id = l.entity_id');
    $secondQuery->fields('l');

  // Make the query
  $result = db_select('field_data_field_user_name', 'u')
      ->fields('u')
      ->condition('field_user_name_value', '%' . db_like($string) . '%', 'LIKE')
      ->union($secondQuery)
      ->execute();

```

# Answer
> 1 votes
So, I figured out how to convert MySQL to Drupal SQL, of a join and union sql transaction, I am not done - but this is the start and the rest is just copy / paste and massage.

```
$matches = array();
  $debug_stop = "";

  // Firstname and Lastname - Larry Adams
  $firstname_lastname_query = db_select('field_data_field_first_name', 'f')
     ->fields('f')
    ->condition('field_first_name_value', '%'. db_like($string) .'%', 'LIKE');
  $firstname_lastname_query->leftJoin('field_data_field_last_name', 'l', 'f.entity_id = l.entity_id');
  $firstname_lastname_query->fields('l');

  // Username checks - lAdams
  $username_query = db_select('field_data_field_user_name', 'u')
      ->fields('u')
      ->condition('field_user_name_value', '%' . db_like($string) . '%', 'LIKE');
  $username_query->leftJoin('field_data_field_last_name', 'l', 'u.entity_id = l.entity_id');
  $username_query->fields('l');

  // Unionize the query to previous query
  $firstname_lastname_query->union($username_query);

  // Nickname checks - lar-bear Adams
  $nickname_lastname_query = db_select('field_data_field_nickname', 'ni')
      ->fields('ni')
      ->condition('field_nickname_value', '%' . db_like($string) . '%', 'LIKE');
  $nickname_lastname_query->leftJoin('field_data_field_last_name', 'l', 'ni.entity_id = l.entity_id');
  $nickname_lastname_query->fields('l');

  // Unionize the query to previous query
  $firstname_lastname_query->union($nickname_lastname_query);

  // Execute the query
  $result = $firstname_lastname_query->execute();

  $debug_stop = "";
  // save the query to matches
  foreach ($result as $row) {
    // If we returned back a user_name accessible field
    if (isset($row->field_user_name_value)) {
      $matches[$row->field_user_name_value] = check_plain($row->field_user_name_value);
    }
    // If we returned back a first_name_value accessible field
    if (isset($row->field_first_name_value)) {
      // with a last name
      if ($row->field_last_name_value) {
       $first_last_name = $row->field_first_name_value ." ". $row->field_last_name_value;
       $matches[$first_last_name] = check_plain($first_last_name);
      }
    }

  }

  // Return the result to the form in json
  drupal_json_output($matches);

```

---
Tags: 7, database, ajax
---


# Question
Title: Alter views 'Has taxonomy term' filter Programatically using views_get_view
Im am having some problems setting TID filter values programatically. I have an array of term ids form a taxonomy field that I need apply to a views filter via views\_get\_view.

This is the code that I have within a DS field that Im trying to alter via the view's display\_handler - Im not even sure if this is the best way to do this. Hopefully someone can explain how this can be done.

Any help would be much appreciated. Thanks

```
    $pager_count = field_get_items('node', $fields['entity'], 'field_pager_count');
    $pager_count = isset($pager_count[0]['value']) ? $pager_count[0]['value'] : 10;
    $node_tags = field_get_items('node', $fields['entity'], 'field_tags');
    $current_node = (arg(0) === 'node' && is_numeric(arg(1))) ? arg(1) : '';
    $tags = array();

    // Alter view to set TID filter and pager
    $view = views_get_view('list_control');
    $view->set_display('block_1');
    $view->set_arguments(array($current_node)); // Remove current NID
    $view->set_items_per_page($pager_count); // Set pager Items
    $view->pre_execute();
    $view->execute();

    foreach($node_tags as  $node_tag) {
      $tags[] = $node_tag['tid'];
    }
    //Set filter values base on $tags array
    $filters = $view->display_handler->get_option('filters');
    $filters['tid']['value'] = $tags;

    // Return DS field.
    $field =  $view->render();

```

# Answer
I managed to achieve this using the following

```
$view = views_get_view('list_control');
$view->set_display('block_1');
$view->set_arguments(array($current_node)); // Remove current NID
$view->set_items_per_page($pager_count); // Set pager Items

// Set filter based on $tags.
$filter = $view->get_item($display_id, 'filter', 'tid');
$filter['value'] =  $tags;
$view->set_item($display_id, 'filter', 'tid', $filter);
$view->pre_execute();
$view->execute();

```
> 1 votes

---
Tags: views
---


# Question
Title: How to use mmenu without breaking core Overlay
How can I use mmenu jquery library without breaking core Overlay. Overlay works, but when I do a page refresh (F5) the overlay is blank. When I prevent the mmenu library from loading it works again.

I load the library in hook\_preprocess\_html in my custom zen theme:

```
drupal_add_css(drupal_get_path('theme', 'zen_sub') . '/css/mmenu/jquery.mmenu.all.css');
drupal_add_js(drupal_get_path('theme', 'zen_sub') . '/js/mmenu/jquery.mmenu.min.all.js', 'file');
drupal_add_js(drupal_get_path('theme', 'zen_sub') . '/js/zensub.js', 'file');

```

I then add the menu to the zen theme in hook\_preprocess\_page through a preprocess variable:

```
$menu_left = menu_tree_all_data('main-menu');
$menu_left = menu_tree_output($menu_left);
$menu_left = drupal_render($menu_left);
$vars['mmenu_markup'] = array(
      '#markup' =>
        '<div id="menu-left">' . $menu_left . '</div>',
);

```

And finally I include placeholders for the menu, as well as the preprocess variable in my page.tpl.php

```
<div id="header-nav">
 <a href="#menu-left" class="menu-left"></a>
 <?php print variable_get('site_name', "ZenSub");?>
 <a href="#menu-right" class="menu-right"></a>
</div>

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

```

And Finally this is my js file (zensub.js) to set it all in motion:

```
(function ($, Drupal, window, document, undefined) {
    Drupal.behaviors.zensub = {
        attach: function(context, settings) {
            $('div#menu-left').once().mmenu({
               offCanvas: {
                   position: "left",
                   zposition: "front"
               },
               header   : true
            }, {
                // configuration object
               classNames: {selected: "active"}
            });

        }
    };

})(jQuery, Drupal, this, this.document);

```

# Answer
You should consider using Mobile Sliding Menu. It could save you a lot time and pain.

> The mobile sliding menu module integrates the mmenu jQuery plugin for creating slick, app look-alike sliding menus for your mobile website.
> 1 votes

# Answer
Using the Mobile Sliding Menu, the way I found to deal with stated problem is add custom module with:

```
function MYMODULE_mmenu_alter(&$mmenus) {

  // Disables left mmenu on some specific pages.
  if ( (arg(0) == 'admin' || arg(1) == 'add' || arg(1) == 'edit' || arg(2) == 'edit') && (arg(2) != 'mmenu') ) {
    $mmenus['mmenu_left']['enabled'] = FALSE;
  }
}

```
> 0 votes

---
Tags: javascript, modal-dialogs
---


# Question
Title: Custom entity to load another custom reference entity fields
I have two custom entities (Car and Car Type) and I am using one as a reference for the other.

When I load the "Car" entity I can only get the ID from "Car Type". I know I can then run entity\_load to get the fields on "Car Type", but when I have multiple results of "Car" querying every record become inefficient.

Is there any way to load the "Car Type" entity fields when loading "Car" entity?

# Answer
> 1 votes
You might want to take a look at Entity metadata wrappers. They are not really efficient as they load even more data, but they simplify the working with entity properties and fields and also resolve nested entities (so you would be able to do something like `$car->field_car_type->field_length->value()`).

But under the hood (a car joke :D), it still performs an `entity_load` to get the values. It is less code for you though.

To answer your question:

Drupal makes the assumption a field is always attached to an entity, it would be very difficult to properly load some fields without actually loading the entity (I suppose that is what you are after). The function which loads field values and attaches those fields to entities (`field_attach_load`) already required loaded entities as input. (This function is often called during entity\_load). You could attempt to replicate its behaviour without loading the entities, but you will probably run into a lot of issues. The same applies for fetching a single field's value; `field_get_items()` and `field_view_value()` also expect a loaded entity. So my advise would be to just load the entity, possibly using entity metadata wrappers as they make your life easier.

---
Tags: 7, entities
---


# Question
Title: File validation when the file field isn't required
I have a Drupal 7 custom form where the image or file field is not required. When the form is submitted and no file/image has been uploaded, I get the following errors.

> Notice: Undefined index: storage in jobform\_my\_form\_submit() (line 136 of /var/www/html/drupaltst/sites/all/modules/jobpackage/jobform.module).
> Warning: Creating default object from empty value in jobform\_my\_form\_submit() (line 141 of var/www/html/drupaltst/sites/all/modules/jobpackage/jobform.module). Notice: Undefined property: stdClass::$uri in file\_save() (line 601 of /var/www/html/drupaltst/includes/file.inc).

Any help is appreciated!

```
function jobform_permission() {
  return array(
    'add jobs module' => array(
       'title' => t('Administer permission for your module'),
       'description' => t('Some description that would appear on the permission page..'),
    ),
  );
}

function jobform_menu() {
  $items = array();
  //$items['jobform/form'] = array(
  $items['jobform'] = array(
    'title' => t('Job Form Details'),
    'page callback' => 'jobform_form',
    'page arguments' => array('jobform_form'),
    'access arguments' => array('add jobs module'),
    'description' => t('My form'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function jobform_form() {
  return drupal_get_form('jobform_my_form');
}

function jobform_my_form($form, &$form_state) {
  $form['title'] = array(
    '#type' => 'textfield',
    '#title' => t('Title'),
    '#required' => TRUE,
    '#maxlength' => 100,
    '#prefix' => '<div class="titletle"><img src="/drupaltst/sites/default/files/images/title_icon.png" height="50" width="45">',
     '#suffix' => '</img></div>',
     '#attributes' => array(
       'placeholder' => t('Enter a Short Title'),
     ),
   );
   $form['descr'] = array(
     '#type' => 'textarea',
     '#title' => t('Description'),
     '#required' => TRUE,
     '#size' => 150,
     '#maxlength' => 5000,
     '#prefix' => '<div class="titledescr"><img src="/drupaltst/sites/default/files/images/descr_req_icon.png" height="50" width="45">',
     '#suffix' => '</img></div>',
     '#attributes' => array(
       'placeholder' => t('Enter some specific details about the service you provide!'),
     ),
   );
   $form['location'] = array(
     '#type' => 'textfield',
     '#title' => t('Enter Your Location'),
     '#required' => TRUE,
     '#size' => 75,
     '#prefix' => '<div class="titleloc"><img src="/drupaltst/sites/default/files/images/loc_icon.png" height="50" width="41">',
     '#suffix' => '</img></div>',
     '#attributes' => array(
      'placeholder' => t('Where Can the Work Be Completed? (i.e. Online, City, State, Zip)'),
     ),
   );

   //Image Field
   $form['image'] = array(
     '#type' => 'file',
     '#title' => t('Upload a Photo'),
     '#description' => t('Allowed extensions: gif png jpg jpeg'),
     '#prefix' => '<br><div class="titlefile"><img src="/drupaltst/sites/default/files/images/upload_image_icon.png" height="50" width="41">',
     '#suffix' => '</img></div>',
   );
   $form['submit'] = array(
     '#type' => 'submit',
     '#value' => 'Submit',
     '#prefix' => '<br><div class="titlesubmit">',
     '#suffix' => '</div>',
   );

   return $form;
 }

 function jobform_my_form_validate($form, &$form_state) {
   $file = file_save_upload('image', array(
     // Validates file is really an image.
     'file_validate_is_image' => array(),
     // Validate extensions.
     'file_validate_extensions' => array('png gif jpg jpeg'),
   ));
   // If the file passed validation:
   if ($file) {
     // Move the file into the Drupal file system.
     if ($file = file_move($file, 'public://images/')) {
       // Save the file for use in the submit handler.
       //$form_state['image'] = $file;
       $form_state['storage']['image'] = $file;
     }
     else {
       form_set_error('image', t("Failed to write the uploaded file to the site's file folder."));
     }
   }
   else {
     form_set_error('image', t('No file was uploaded.'));
     //$file = file_move($file, 'public://images/title_icon.png');
   }
 }

 function jobform_my_form_submit($form, $form_state) {
   $file = $form_state['storage']['image'];
   // We are done with the file, remove it from storage.
   //unset($form_state['image']);
   unset($form_state['storage']['image']);
   // Make the storage of the file permanent.
   $file->status = FILE_STATUS_PERMANENT;
   // Save file status.
   file_save($file);
   global $user;
   $na = 0;
   $istat = 1;
   db_insert('job_mp_catalog')
     ->fields(array(
       'user_id' => $user->uid,
       'title' => $form_state['values']['title'],
       'descr' => $form_state['values']['descr'],
       'location' => $form_state['values']['location'],
       'image' => $file->fid,))
     ->execute();
   drupal_set_message("successfully saved ");
   //Example:
   //drupal_goto("user/".$user->uid."/edit");
   drupal_goto("content/test-page");
   //drupal_set_message("successfully saved Job!");
 }

```

# Answer
> 0 votes
Just try to validate on submit function as follow

```
function my_module_image_form_submit($form, &$form_state) {
  // Upload file to upload_directory in the public files dir.
  $file = file_save_upload('image', array(
    'file_validate_is_image' => array(),
    'file_validate_image_resolution' => array('500x500', '100x100'),
  ), 'public://uploaded_images/', FILE_EXISTS_RENAME);

  // Check if image upload was success.
  if ($file) {
    drupal_set_message(t('Image successfully uploaded.'), 'status');
  }
  else {
    form_set_error('image', t('Image was not uploaded.'));
  }
}

```

For more info please see this article.

# Answer
> 0 votes
Figured out the 'image' =\> $file-\>fid, part in the db\_insert. I used visabhishek suggestion above but for the db\_insert, I did the below with removing "'image' =\> $file-\>fid," in the else section.

Thanks for the help!

```
if ($file) {
   db_insert('job_mp_catalog')
     ->fields(array(
       'user_id' => $user->uid,
       'title' => $form_state['values']['title'],
       'descr' => $form_state['values']['descr'],
       'location' => $form_state['values']['location'],
       'image' => $file->fid,))
     ->execute();

}
  else {
      db_insert('job_mp_catalog')
        ->fields(array(
       'user_id' => $user->uid,
       'title' => $form_state['values']['title'],
       'descr' => $form_state['values']['descr'],
       'location' => $form_state['values']['location'],
     ->execute();
}

```

---
Tags: hooks, files
---


# Question
Title: url() not providing links to correct language alias using i18n in D7
We have a site that features two languages, EN (primary/default) and JA. On one content page, we link to another node using it's `nid`: `url('node/123')`. In EN, this returns the alias and not the node based url. When in the JA language, this returns a url like `/ja/node/123` which then shows text in the EN variant when we expect JA. There are aliases set for both EN and JA, which both point to the same desired URL like: `/products/new-fancy-product` and their respective node id urls. In EN, `url` returns this alias correctly.

Also, if I change `/products/new-fancy-product` to `/ja/products/new-fancy-product` in the address bar, I get the correct JA version of the page as I want.

Why is `url` not returning me the correct alias instead of the node id path, which then just shows EN content?

# Answer
> 0 votes
Use l() function to generate a link.

> Formats an internal or external URL link as an HTML anchor tag.
>
> This function correctly handles aliased paths and adds an 'active' class attribute to links that point to the current page (for theming), so all internal links output by modules should be generated by this function if possible.

---
Tags: 7, i18n-l10n, path-aliases
---


# Question
Title: How to add another html tag (i.e. span) before the field value renders using hook_preprocess()?
I have a field (field\_txt) that renders properly, but now i want to add a tag around it so that i can style the background color of it. How would this be possible using the preprocess field hook?

Output

```
<div>some text value</div>

```

Desired Output:

```
<div><span class="bg-color-rd">some txt value</span></div>

```

# Answer
Not sure how it would be done with a preprocess hook, but an alternative would be to instead copy field.tpl.php into your theme, rename it according to the convention of field-name-\[field\_name\], and simply add the `<span>` and `</span>` elements at the appropriate points in the template, like so:

```
<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
    <span class="bg-color-rd">
        <?php if (!$label_hidden): ?>
        <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>: </div>
        <?php endif; ?>
        <div class="field-items"<?php print $content_attributes; ?>>
            <?php foreach ($items as $delta => $item): ?>
            <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><?php print render($item); ?></div>
            <?php endforeach; ?>
        </div>
    <span>
</div>

```
> 1 votes

---
Tags: entities, hooks, theming
---