title: Problem CKFinder with multilingual site

text:
# Question
Title: Problem CKFinder with multilingual site
I have installed the CKEditor module, the CKEditor library and the CKFinder library.
I have modified correctly the file config.php and the file settings.php, but when I want login in my site, I don't get the permission for access. If I comment the variable `cookie_domain` I can access at the site and all working properly, but I get a message error that say: "You are using a feature that requires $cookie\_domain to be set, but it is not set in your settings.php file (CKFinder is enabled in the Advanced profile)". What can I do?

# Answer
> 1 votes
set the $cookie\_domain variable in sites/default/settings.php

```
<?php
$cookie_domain = $_SERVER['SERVER_NAME'];
?>

```

Uncomment the `$base_url` variable and set the base URL of your website (without the trailing slash).

**Another option** if you have the Drupal Domain access module installed use

```
<?php
$base_domain = explode('.', $_SERVER['SERVER_NAME']);
unset($base_domain[0]);
$base_domain = '.' . implode($base_domain, '.');

$cookie_domain = $base_domain;
?>

```

Here is the reference to the answer

---
Tags: wysiwyg
---


# Question
Title: When exiting views modal I am returned json
When I am in views UI and I edit an option a modal box appears. I edit some seetings then press save and am displayed with something like:

> \[{"command":"settings","settings":{"basePath":"/","pathPrefix":"","ajaxPageState":{"theme":"bartik","theme\_token":"SUIsCUisas2D3yeSiBkGNwaXtTMtlVVXouHWgoffCYA"}},"merge":true},{"command":"viewsDismissForm"},{"command":"viewsShowButtons"},{"command":"viewsTriggerPreview"},{"command":"insert","method":"html","selector":"#views-tab-block","data":"\u003Cdiv id=\u0022edit-display-settings-details\u0022\u003E\u003Cdiv id=\u0022edit-display-settings-top\u0022 class=\u0022views-ui-display-tab-actions views-ui-display-tab-bucket clearfix\u0022\u003E\u003Cdiv class=\u0022ctools-no-js ctools-button ctools-dropbutton\u0022\u003E\u003Cdiv class=\u0022ctools-link\u0022\u003E\u003Ca href=\u0022#\u0022 class=\u0022ctools-twisty ctools-text\u0022\u003Eopen\u003C/a\u003E\u003C/div\u003E\u003Cdiv class=\u0022ctools-content\u0022\u003E\u003Cul class=\u0022horizontal right actions\u0022\u003E\u003Cli class=\u0022duplicate ...

What could be going wrong?

# Answer
Make sure you use the default jQuery version (1.5) when using The Views UI module.
> 2 votes

# Answer
It seems that also using JQuery version (1.7) can also be used with the views UI module. It works well with JQuery version (1.5) in Drupal 7. I checked with both versions of the JQuery and it works. Not working properly with JQuery 1.8.

You can follow this thread in drupal.org if you would like to have more information or suscribe http://drupal.org/node/1869988

The version of the views that I am using is 7.x-3.7
> 1 votes

# Answer
use jquery version 1.5 it best works with views\_ui.
> 0 votes

---
Tags: 7, views, iis
---


title: ZEN 5 Responsive - general questions

text:
# Question
Title: ZEN 5 Responsive - general questions
For a couple of last days I've read dozens of articles about Zen 5, its grid system and responsive design. But there are still some questions need to be answered or maybe confirmed.

**1. responsive-sidebars.scss file**

Let's say I want to have different text color of main content for different media queries. I guess the overall definition of the color should be in pages.scss file, but for specific media queries it should to be in responsive-sidebars.scss, right? A've added a color: red; syntax to the example shown in the second question. Is this correct place for this property and value?

**2. Override $zen-column-count variable**

Let's assume that I want a scenario like this. For the front page I want to have 5 column grid at @media all and (min-width: 960px). But for non-front pages I want to use 10 column grid at the same media query. I reckon, I can do it like this:

```
@media all and (min-width: 960px) {
 $zen-column-count: 5;

 .sidebar-first {
  #content {
   @include zen-grid-item(4, 2);
   color: red;
  }

  .region-sidebar-first {
   @include zen-grid-item(1, 1);
  }

 /* not-front pages */
 $zen-column-count: 10;

 .not-front .sidebar-first {
  #content {
   @include zen-grid-item(7, 3);
  }

  .region-sidebar-first {
   @include zen-grid-item(3, 1);
  }

 }
}

```

**3.Different max-width query for front and non-front pages.**

Let's say I want to have different max-width query for front and not-front pages. In the responsive-sidebars.scss file I found this notation:

```
@media all and (max-width: 1125px) {

}

```

While the only difference between front and non-front pages is a body class, how can I prevent this to use it only for front page? Is the notation of ".front" class is enough to apply this media query to front page?

# Answer
The short answer is yes; the `.front` class is more than adequate.

Using SASS nesting, your CSS would probably end up looking something like the following.

```
@media all and (min-width: 960px) {
 $zen-column-count: 5;

 .front {
   .sidebar-first {
    #content {
     @include zen-grid-item(4, 2);
     color: red;
    }

    .region-sidebar-first {
     @include zen-grid-item(1, 1);
    }
  }

 /* not-front pages */
 $zen-column-count: 10;

 .sidebar-first {
  #content {
   @include zen-grid-item(7, 3);
  }

  .region-sidebar-first {
   @include zen-grid-item(3, 1);
  }

 }
}

```

Note that I've removed the `.not-front` class from the second batch. Adding the `.front` class to the first block gives it a higher level of specificity, so it can't be overridden by what is in the second block. Basically, if you are using `.front` for the first bits, then it is redundant to use `.not-front` for the second block.

As an FYI, there is an awesome CSS specificity article here.
> 3 votes

---
Tags: theming
---


# Question
Title: how to delete modules which are alredy uninstall?
I have set of modules in my system but those modules are not properly un installed from the file system i have removed all modules but name aad path of the module still remains in system table

Any one please suggest me how to clear this garbage ?

# Answer
Unless you disable and uninstall the custom modules you should not remove that custom module . This can cause performance and other issues. Get back those modules from backup. Then disable and uninstall them. Then you can remove the module.

There is even a module in Drupal 7 which will tell you deleted but not disabled modules which I'm not able to remember.
> 2 votes

# Answer
If the modules really haven't uninstalled properly then you'll need to manually go though the install files for each, and make sure you carry out all the actions on their behalf.

Far more likely, though, is that they *have* uninstalled properly but because you've left the files there, Drupal still picks them up in the system table, as they're fair game to be re-installed (Drupal module discovery is file based, so as long as the files are there, Drupal will find them).

So just delete the relevant module folders from your Drupal install, ensuring you take a backup of both files and database before hand in case there's a problem. If that happens, you'll need to cleanup manually, steps for which will completely depend on the modules you have installed/your config/etc.
> 0 votes

---
Tags: 7
---


# Question
Title: where does the drupal6 cck field default value stored in database?
Is there a way to get the default value in a cck field (in drupal 6)?When I set the default value,the nodes created after that, are having this default value.(in database also ,table name is content\_type\_contenttypemachine).

Initially I set the default value as '1000' and later changed it to "4000" but when am trying to get the value from the content type table its retrieving the first value as "1000" and not the recent value "4000".

Is fetching the last record is the only way to get the latest default value I have set?

Thanks in advance, cheers.

# Answer
> 3 votes
No need to go directly into the database for that, you can use the `content_field_instance_read()` function:

```
module_load_include('inc', 'content', 'includes/content.crud');
$definition = content_field_instance_read(array('field_name' => 'field_foo'));

// Your mileage may vary here, inspect $definition[0]['widget'] to see what you've got available.
$default = $definition[0]['widget']['default_value'][0]['value'];

```

If you're dead set on going into the database, the info is stored as a serialised PHP string in the `widget_settings` column of the `content_node_field_instance` table.

---
Tags: 6, nodes
---


# Question
Title: Date field in FormAPI, remove Day field?
Using a 'date' field in the FormAPI, is there something I can set to hide the day field from showing?

# Answer
There isn't a setting for that, but you could do it with the `#after_build` option, as it will allow you to alter the form element after it has been processed (day, month and year fields have been created).
> 4 votes

# Answer
I think you could accomplish this using the widgets provided by the Date module, specifically the `date_text` widget:

```
$form['date'] = array(
  '#type' => 'date_text',
  '#title' => 'Date',
  '#date_format' => 'm/Y',
  '#default_value' => date('Y-m-d')
);

```

You can use the `#date_format` key to set the level of granularity you want for the element date.

Be aware the default value has to be in the `Y-m-d` format for some reason (can't dig out the link to the issue on drupal.org at the moment but I'll update the answer if I find it).
> 2 votes

# Answer
Here's a code example, close to the op request that may help other devs. Based on the answer by @Clive

```
$form['deadline'] = array(
  '#title' => 'Deadline ',
  '#type' => 'date_select',
  '#date_title' => 'Deadline',
  '#date_format' => 'm/Y',
  '#date_year_range' => '0:+1',
  '#default_value' => variable_get('deadline', date('Y-m')),
  '#description' => t('Deadline description'),
);

```

If you use this instead of the form api date type element, then the value is stored differently. The form api date element is like this:

```
array(
  'year' => 2013,
  'month' => 12,
  'day' => 31,
);

```

Whereas the date\_select form element is stored as a string:

```
"2013-12-31"

```

Although for the example above the value is formatted like this:

```
"2013-12"

```

So you'll need to adjust the areas of your site that use this data.
> 1 votes

---
Tags: 7, forms
---


# Question
Title: "This view has been automatically updated to fix missing relationships" - fields removed from a working view for no reason
I have a site built on Commerce Kickstart 1 - Views 3.7.
I have a standard cart, to which I wanted to add photos of the products. It is a view that includes a relationship to *Commerce Order: Line items* and a contextual filter by Order ID.

Now, I added a reference to the product in order to be able to access the photos. The view works OK, all the initial elements *and* the images are there, but when i try to edit it, all the relationships are gone and I receive the "This view has been automatically updated to fix missing relationships" message. Both the relationship I added and the default relationship to line items are gone.

RELATIONSHIPS
Commerce Order: Line items
(Line Item) Commerce Line item: Product

FIELDS:
(Line Item) Commerce Line item: Display path
(Product) Field: Image (Image)
(Line Item) Commerce Line Item: Title
(Line Item) Commerce Line item: Unit price
(Line Item) Commerce Line Item: Quantity text field
(Line Item) Commerce Line item: Total
(Line Item) Commerce Line Item: Delete button

To me it looks like a bug in Views? There is a discussion of a similar issue https://drupal.org/node/1860380 (the last post is actually mine). Maybe I am wrong, though, maybe it's me who's doing something wrong?

# Answer
EDIT: It turned out after all that this behaviour was related to the "Administration Language" module https://drupal.org/project/admin\_language.
Disabling it made the problem disappear for good.
It seems as its is related to access permissions. A similar problem was encountered in creating product views in drupal commerce. If you want to relate to the fields of the referenced product, you have to grant the *View* permisssion to all *products* (non-node enitities of DC). Otherwise the users without permission to view the product enitities will see an empty view (see Views results empty for unprivileged user when using Relationship: Content: Referenced Product). What makes it especially difficult to track that the problem does show up only when one uses Relationship & "Fields" display. A similar view with content / teaser etc renders the same content without problems.

Now, I wanted to add an image of the product to the cart view. I referenced the *Image* field of the product in the cart (*(Line Item) Commerce Line item: Product*), and put the image field from there.

I understand that the permissions problem prevent the view from functioning properly. It seems to be that it's a bug that
a) the view itself functions well
b) that the problem appears in the Views UI
c) that the error message is not informative.

It seems to me that this behavior is just a side effect of a number factors in how the Views work.
> 0 votes

---
Tags: commerce, i18n-l10n, views
---


title: "true" 'first' 'last' classes in menus

text:
# Question
Title: "true" 'first' 'last' classes in menus
I am building a zen subtheme in which I try to adjust my menus from:

```
<ul class="menu">
    <li class="first">
        <ul class="menu>
            <li class="first"></li>
            ...
            <li class="last"></li>
        </ul>
    </li>
    <li class="..."> </li>
    <li class="..."> </li>
    <li class="last">
        <ul class="menu>
            <li class="first"></li>
            ...
            <li class="last"></li>
        </ul>
    </li>
</ul>

```

too:

```
<ul class="menu">
    <li class="first"> <----- mark the very first
        <ul class="menu>
            <li class="..."></li>
            ...
            <li class="..."></li>
        </ul>
    </li>
    <li class="..."> </li>
    <li class="..."> </li>
    <li class="...">
        <ul class="menu>
            <li class="..."></li>
            ...
            <li class="last"></li> <----- mark the very last li element
        </ul>
    </li>
</ul>

```

another example:

```
<ul class="menu">
    <li class="first"> <----- mark the very first
        <ul class="menu>
            <li class="..."></li>
            ...
            <li class="..."></li>
        </ul>
    </li>
    <li class="..."> </li>
    <li class="..."> </li>
    <li class="last">
    </li>
</ul>

```

I know I can handle each menu item with `theme_preprocess_menu_link` but I didn't find a solution to have the very first and last item marked as I need to? Any suggestions?

# Answer
> 1 votes
Please see added sample image; is this similar to what you want?

If so, I achieved it with this CSS code:

```
li:first-child {
color: red;
}

li:first-child li {
color: black;
}

li:last-child li:first-child {
color: yellow;
}

li:last-child li {
color: black;
}

li:last-child li:last-child {
color: green;
}

```

# Answer
> 1 votes
I am not sure that i fully understood what you want; but if what you need is to give special attributes(ID, class etc.) to menu items, Menu attributes module may help. You also could use CSS3 :nth-child() selector.

---
Tags: theming
---


# Question
Title: Enable a flag automatically for specific users using Rules
1. I have a content type called testimonials, and in that I have a user reference field with multiple selection option.
2. I have a flag called 'Request to review' enabled on nodes of 'testimonials' content type.
3. I wrote a rule for sending mail to the author of the node if any user clicked on that flag.

What I need to do here is, I want to enable that flag automatically when a new node is saved only for the users who are selected in the form field user reference. And for remaining users the flag should not be enabled automatically i.e., they have to enable it manually by clicking the flag link.

Thanks

# Answer
> -1 votes
I achieved it by writing a new rule, in that i wrote a loop for getting all the selected users.

thanks

---
Tags: rules, users
---


title: Alter Acquia Search Results

text:
# Question
Title: Alter Acquia Search Results
I am using acquia search on D7 site. By default I get all the search results as Title, Teaser with search info at the bottom. I am trying to alter this results to add some of the field data.

Eg: Content type is a product and there is a Date of arrival field and Stock availability field for all the Product node.

Now how can I add these two fields as part of every result on search results page?

# Answer
You can use Apache Solr Views module. Add title, date and any other fields you want.
> 0 votes

# Answer
You can use hook\_apachesolr\_query\_alter($query) to alter your results variable, if you're using Apache solr views and this error

> Notice: Undefined property: apachesolr\_views\_query::$group\_operator in apachesolr\_views\_query-\>build() (line 80 of /var/www/html/root/sites/all/modules/apachesolr\_views/apachesolr\_views\_query.inc).

this means that you didn't use filters in your view.
> 1 votes

---
Tags: 7, search
---


# Question
Title: Remove colons from Drupal form fields/labels
How can I remove the : from appearing after every label in forms made with the Drupal Form API?

# Answer
Create your own implementation of theme\_form\_element(). The offending semicolon is in `$t('!title: !required', ...)`, and would need to be removed in both locations.

Not the easiest thing to change, but at least it's possible without hacking core!
> 13 votes

# Answer
The way I've just done it is to add a `<span class="colon"><span>` around the colon in field.tpl.php. Then I can hide it with `display:none;` if I don't want it.

It avoids putting a lot of logic into a tpl.php if you have multiple fields which either need or don't need colons.

It also allows you to change fields colon requirements on different pages. For example I often don't want them on displaying a node but would like them in editing.
> 1 votes

# Answer
copy the field.tpl.php to your current theme folder and remove colon. Clear cache and check. I think It will solve the problem.
> 0 votes

# Answer
You can try this also, works for me in drupal 7.

Drop this in the body of your version of 'page.tpl.php' in your template folder.

```
<?php
    drupal_add_js(
      'jQuery(document).ready(function () {
        var labels = jQuery(".field-label");
        jQuery.each(labels, function() {
          this.innerHTML = this.innerHTML.replace(":", "");
        });
      });',
      'inline');
  ?>

```
> -2 votes

---
Tags: 7, theming, forms
---


# Question
Title: Prefill content type form field with alter hook
I've created a **content type** with a **link** type field. When an **user** add this content type I want to prefill the **link** field with the user email. I've a create a new **module** named **prefilllink** with an alter hook :

```
function prefilllink_alter(&$form, &$form_state, $form_id) {
  dsm($form);
  switch($form_id) {
    case "job_node_form":
      $form["field_apply"]["und"][0]["value"]["#default_value"] = $user->mail;
      break;
  }
}

```

But it doesn't work... Any idea?

# Answer
> 0 votes
You need to implement either `hook_form_alter()` or `hook_form_FORM_ID_alter()` (there's no `hook_alter()` which is what your code is implementing at the moment).

The second is probably preferable as it targets the form you're interested in:

```
function prefilllink_form_job_node_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  $form["field_apply"][LANGUAGE_NONE][0]["value"]["#default_value"] = $user->mail;
}

```

---
Tags: nodes, forms
---


# Question
Title: Translation for node references not working properly
I have two content types: product feature and product. Both can be translated. If I create English product and assign many product features (by node reference inside field collection) and then create translation (ex. French) for this I have rewritted product features. Then I can select Product features translated previously to French. English product have English product features and French product (translated) have French product features (also translated).

PROBLEM: When I modify French node (change product features to French) my English node is also changed (product features are French).

Did I missed something?

# Answer
> 0 votes
The only solution I found is to remove all elements in field collection of translated node and add them once again - with properly translated elements/values.

# Answer
> 0 votes
There's a module for that: https://drupal.org/project/i18n\_node\_reference

> Provides i18n field synchronisation for a node\_reference field.
>
> The referenced nodes are translated into the correct language. If no such language exists, it is ignored. This is the same functionality as is supported by the taxonomy reference translation in i18n\_taxonomy.

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


# Question
Title: Showing content associated with node reference in a view
I have created a "Node Reference Field" in a content type named "TV Shows" . ( And it is referring to another Content Type "Episodes")

I created a view which takes the NID of "TV shows" from Contextual filters . How to display all the fields of related "Episodes" to that "TV show ."

cheers :)

# Answer
If I understand correctly, you have a single node (type TV Show) with several related nodes of type Episodes, each Episode node describing an episode of the particular TV show.

If this is correct, this is a common error. Your node reference field should be on the Episode type, and should refer to the TV Show type.

Then a simple view of Episodes with a contextual filter on Node ID will give you what you want. Just make sure the reference goes in the correct direction.
> 1 votes

---
Tags: views, nodes
---


title: Formatting output of token

text:
# Question
Title: Formatting output of token
I have Drupal Commerce, and it sends confirmation emails after product is sold. In those emails are tokens. I have token `[commerce-order:created]` and I'm interested if is there any conveniant way to change a formatting of that date.

# Answer
If `[commerce-order:created]` is a date token, then you can use `[commerce-order:created:custom:<the format you want to apply>]`, where `<the format you want to apply>` is the string format accepted by `date()`.

Otherwise, the more generic way to alter tokens implemented by other modules is implementing `hook_tokens_alter()`.

```
function mymodule_tokens_alter(&$replacements, $context) {
  $options = $context['options'];

  $sanitize = !empty($options['sanitize']);
  $langcode = !empty($options['language']->language) ? $options['language']->language : NULL;

  if ($context['type'] == 'commerce-order') {
    foreach ($context['tokens'] as $name => $original) {
      switch ($name) {
        case 'created':
          // Set a value for $sanitized and $new_value.
          $replacements[$original] = $sanitize ? $sanitized : $new_value;
      }
    }
  }
}

```

Notice that in my code:

* `$sanitized` is the sanitized value to assign to the token, used only when `$sanitize` is `TRUE`
* `$new_value` is the new value for the token, used to obtain the value of `$sanitized`
> 1 votes

# Answer
You can do this with hook\_tokens\_alter

> Alter replacement values for placeholder tokens.

Eg:

```
/**
* Implements hook_tokens_alter().
*/
function mymodule_tokens_alter(&$replacements,  $context){
  // May be you can do some more ifs to reduce the load :)
  if(isset($replacements['[commerce-order:created]'])){
    $replacements['[commerce-order:created]']  = check_plain('YOUR-CUSTOM-REPLACEMENT');
  }

}

```
> 0 votes

---
Tags: commerce, datetime, tokens
---


# Question
Title: How to set a datetime field = now() during insert?
I'm using db\_insert() to insert a record into a table. That table as a "creationDatetime" field which should be set to now() on insert. I tried setting it to REQUEST\_TIME, but that value is a unixtime value and not an sql datetime format so I get an error.

I suppose I could write a php function that will automatically format REQUEST\_TIME as an sql datetime value and call that function every time I try to insert, but does anyone else have a better solution?

# Answer
I don't think you'll find a better solution to be honest. Classes like the `SelectQuery` provide an `addExpression()` function so that arbitrary expressions can be added (like `NOW()` etc), but unfortunately the `InsertQuery` class provides no such method.

Looks like you're stuck writing the helper function, or building up the SQL string yourself and running it through `db_query()` (I can't say I'd advise the second method though, and I'm sure I've seen it specifically recommended against in the docs somewhere).
> 3 votes

# Answer
Using a slightly different syntax (drupal\_write\_record):

```
$new_record = array(
    'field' => $form_state['values']['field'],
    'timestamp' => date("Y-m-d H:i:s", time()), //<- this
);
drupal_write_record('table_name', $new_record);

```
> 7 votes

# Answer
db\_insert() returns an InsertQuery object. It allows you to set any field value you want to set. Just use the php time() function to pass in the current unix time stamp.
> 2 votes

# Answer
Let to chime in but here is a solution. Just use db\_query. Here is my code I used that worked. And yes, this is a Drupal 7 solution. Thanks.

```
$query = "INSERT INTO {company_cmi_session_time} uid,scoid,gid,datetime,initialize,terminate) VALUES (:uid,:scoid,:gid,NOW(),1,1)";
$result = db_query($query, array(':uid' => $uid, ':scoid' => $nid, ':gid' => $groupid));

```
> 0 votes

---
Tags: 7, database
---


title: Custom drush command not being loaded

text:
# Question
Title: Custom drush command not being loaded
I'm creating a custom drush command in my module but it's not being seen. Wondering if someone would know why. The module is enabled. It seems the hook\_drush\_command() is never being called for my module, but I see it being done for other modules. I've tried clearing cache.

bir.drush.inc is located in /bir/drush directory

```
function bir_drush_command() {
  $items = array();

  $items['bir-process-images'] = array(
      'description' => dt('Process images on image server.'),
      'aliases' => array('birpi'),
      'arguments' => array(
          'days' => dt('Number of day(s) in the past to begin processing.'),
          'nids' => dt('Comma separated list of node ids to process.'),
      ),
      'required-arguments' => array(1),
      'options' => array(
          'days' => dt('Number of day(s) in the past to begin processing.'),
          'nids' => dt('Comma separated list of node ids to process.'),
      ),
      'examples' => array(
          'drush bir-process-images --days=7' => dt('Process images from 7 days ago to now.'),
          'drush bir-process-images --nids="2409,2309,5896"' => dt('Process images for given node ids.'),
          'drush birpi --days=7' => dt('Process images from 7 days ago to now.'),
          'drush birpi --nids="2409,2309,5896"' => dt('Process images for given node ids.'),
      ),
  );

  return $items;
}

```

When I type $ drush help at the command line, my command is never shown. I tried printing out the $items array in the function and it never even gets there. If I print $items out in another module, for example search\_api, it prints to my screen. So, for some reason it's simply not picking up that I'm calling the hook in my file. Or, not seeing the file?

# Answer
> 1 votes
I figured it out. Even though I closed the command line window, I never cleared the drush cache. Running "$ drush cache-clear drush" fixed the issue.

---
Tags: drush
---


title: Drawing Tool in WebForm

text:
# Question
Title: Drawing Tool in WebForm
Drupal 6 website.

I need to embed a drawing tool into a webform to allow a visitor to sketch a diagram and have it sent as an attachment to the email from the WebForm.

Been looking around but have not found a solution for Drupal 6.

Any ideas?

# Answer
Image Editor will do that,

Drupal 6 version allows to edit Imagefield items and save them back either by replacing the original image or adding new Imagefield item. but I'm not sure it will integrate with webform, You need to test it.

See the Demo Here

> Bring image editing (draw, text, crop, scale, etc.) functionality into your Drupal website! Edit/create any images online in the powerful and feature-rich image editors and save resulted images back to your site!
> 1 votes

# Answer
Have you tried the painter module

> The Painter provides dynamic image creation and manipulation capabilities by allowing the definition of sequences of image IO, manipulation and drawing operations that can be applied to fields within content types and views, as well as to page elments such as the logo, navigation, titles and buttons.
> 0 votes

---
Tags: webforms
---


# Question
Title: Is there a better way to get a uid in a block than using Input Format PHP?
I need to make a direct link to page which needs the uid in the URL.

Can someone suggest a better way to do this in a block? Does Input Format PHP code open some unnecessary attack vectors? Are input filters or tokens in blocks possible?

```
<?php
global $user;
?>
.
.
.
<li>
   <a href="/user/<?php echo $user->uid ?>/fboauth?destination=stream">Facebook Deauthorize</a>
</li>

```

This is a legacy site running 6.28 using FBOauth.

# Answer
> 3 votes
You should be creating your own block module for blocks that require custom PHP, custom PHP inside a form field is not very good security wise because of the way the PHP is parsed.

A custom block meaning

`custom_hook_block()` with the `$block['content'] =>`

---
Tags: blocks, input-formats
---


# Question
Title: Feeds module and feed that includes external files as nodes
I have a feed that includes item content in external xml files. For example, I have a manifest.xml file that has "sections" and each section links to another xml file.. such as:

```
<rss version="2.0">
<script/>
<channel>
<title>Example</title>
<link>manifest.xml</link>
<pubDate>Fri, 27 Jul 2012 00:00:00 GMT</pubDate>
<lastBuildDate>Wed, 05 Dec 2012 17:04:05 GMT</lastBuildDate>
<item>
<title>Page One</title>
<link>Page_One_Section.xml</link>
<pubDate>Fri, 27 Jul 2012 00:00:00 GMT</pubDate>
</item>
...
</channel>
</rss>

```

Then in that (section) external file contains lists of nodes whos content is stored in yet another external xml file...such as

```
<rss version="2.0">
<script/>
<channel>
<title>Page One</title>
<link>Page_One_Section.xml</link>
<pubDate>Fri, 27 Jul 2012 00:00:00 GMT</pubDate>
<lastBuildDate>Wed, 05 Dec 2012 17:04:05 GMT</lastBuildDate>
<item>
<title>Example Story</title>
<link>story.xml</link>
<pubDate>Fri, 27 Jul 2012 00:00:00 GMT</pubDate>
</item>
...
</channel>
</rss>

```

Now my question is, in this multi-file structure, will the feeds module parse this out-of-the-box, or will I need to get some other add on or create a custom parser??

What other solutions are out there for parsing something like this?

# Answer
Feeds module can be setup to do this with XPath Parser and Feed Tamper. Give feeds tamper a try - https://drupal.org/project/feeds\_tamper
> 0 votes

---
Tags: feeds
---


title: Line Items module?

text:
# Question
Title: Line Items module?
What options do I have in implementing line items, other than using an extra content type for each type of line item?

Line items, can be more purchase order order items, addresses, etc.

Seems to me, it would be a common requirement to have something which is query-able by VIEWS but not it's own content-type, but configurable through an UI?!?

I thought entities were designed to address this issue but I don't see any easy UI to allow creation/updating/associating sub-entities (for lack of better term)

When I google for a module like this I only seem to find Commerce modules -- not exactly what I was hoping for.

Any ideas???

Regards, Alex

# Answer
> 0 votes
Entity Construction Kit provides a decent UI for managing entities, and integrates with Views nicely.

---
Tags: entities
---


# Question
Title: Customized User Registration form with Profile fields
I'm missing something core to how user registration forms are customized and the data is added to the database and I'm hoping to get a workflow.

I have created about a dozen Profile fields, textareas, radio buttons, select lists, etc.

I have written a module to do a `form_alter`, and in that module I have laid out fieldsets and containers so that everything is neat and orderly. For example, for *Home Information* I have this:

```
$form['hi'] = array(
    '#type' => 'fieldset',
    '#prefix' => '<div id="hi_cont">',
    '#suffix' => '</div>',
    '#title' => t('Home Information'),
    );

    $form['hi']['hic'] = array(
    '#type' => 'container',
    '#prefix' => '<div id="hic">',
    '#suffix' => '</div>',

    );

    $form['hi']['hic']['left'] = array(
    '#type' => 'container',
    '#prefix' => '<div id="hic_left">',
    '#suffix' => '</div>',

    );

    $form['hi']['hic']['right'] = array(
    '#prefix' => '<div id="hic_right">',
    '#suffix' => '</div>',
    '#type' => 'container',

    );

```

and then I have this to display Profile fields that are relevent to Home Information:

```
$form['hi']['hic']['right']['profile_memberlist']['field_home_phone'] = $form['profile_memberlist']['field_home_phone'];
$form['hi']['hic']['right']['profile_memberlist']['field_home_phone']['#maxlength'] = 16;
$form['hi']['hic']['right']['profile_memberlist']['field_home_phone']['#size'] = 13;
$form['hi']['hic']['right']['profile_memberlist']['field_home_phone']['#title'] = t('Phone');
$form['hi']['hic']['right']['profile_memberlist']['field_home_phone']['#description'] = t('Enter your phone number');
$form['hi']['hic']['left']['profile_memberlist']['field_first_name'] = $form['profile_memberlist']['field_first_name'];
$form['hi']['hic']['left']['profile_memberlist']['field_first_name']['#maxlength'] = 16;
$form['hi']['hic']['left']['profile_memberlist']['field_first_name']['#size'] = 13;
$form['hi']['hic']['left']['profile_memberlist']['field_first_name']['#title'] = t('First Name YO');
$form['hi']['hic']['left']['profile_memberlist']['field_first_name']['#description'] = 'HEY THERE';

```

Now when I view the registration form, I see first all my generic Profile fields, PLUS the elements created from the above. I thought that unsetting the profile\_memberlist was the way to go, but it turns out that while the user is created the Profile fields do not get saved this way.

My Submit is something like this:

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

```

the actual function:

```
function all_data_form_submit($form, &$form_state) {
drupal_set_message('<pre>' . print_r($form_state['values'],TRUE) . '</pre>');

$new_user = array(
'name' => $form_state['values']['name'],
'pass' => user_password(),
'mail' => $form_state['values']['mail'],
'init' => $form_state['values']['mail'],
'status' => 0,
'access' => REQUEST_TIME,
  'field_first_name' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['field_first_name']))),
  'field_last_name' =>  array(LANGUAGE_NONE => array(array('value' => $form_state['values']['field_last_name']))),

);

$form_state['redirect'] = array(
'node/31890',

array(
  'query' => array(
    'foo' => 'bar',
  ),
  'fragment' => 'baz',
 ),
);

$account = user_save(null,$new_user);

}

```

But that ends with a DATA INTEGRITY error on submit, because apparently user\_save is being called twice? I remove the user\_save and the user is created, but none of the Profile fields get added to the database.

What has worked for me is when both the unstyled and the styled form elements are shown, and I don't use a custom submit handler, the Profile data is saved.

**My question**: how do I display the styled and neatly organized form elements only, and have the data entered through them get saved to the database?

# Answer
> 0 votes
I believe you're looking for hook\_user\_presave().

This hook is called directly before the user is saved and the $edit arg will contain all of your form values.

As an alernative, you may look at the Profile2 module

---
Tags: 7, forms
---


# Question
Title: How do I wrap classes around taxonomy terms?
I need to add CSS to individual terms for a taxonomy field. Where is the best place to do that?

# Answer
You're looking for taxonomy-term.tpl.php.

This will allow you to customize the output of your term page.
> 1 votes

---
Tags: 7, taxonomy-terms
---


# Question
Title: Dynamically fill field when adding a new node
I have been trying to search for an answer to this but I am not entirely sure what to ask. I am using drupal 7. What I am trying to accomplish is being able to create a campaign, and then allowing users to order a product within that campaign.

So currently I have a content type of campaign and a content type of order. I create a new campagin and then un-authenticated users should be able to create new Order nodes, but what I am not sure how to do, is link the orders to the campaign. So http://www.domain.com/campaign/name would have a form on it that generates a new order node.

It seems like I need to have entity reference in the order content type, but how to I populate that field because I don't want the user to select which campaign, it should be automatic. Hopefully that makes sense, the only way I have thought to accomplish this would be to parse the uri and try to get the campaign name then lookup the campaign nid. Seems kind of hackish though. Thanks!

# Answer
> 1 votes
I don't know a clever way to link, so I would probably use the NID from campaign as a reference.

I'd create a integer field in order which would store the NID from the campaign on creation. i.e. The custom form would create a node of type order and automatically fill the value.

Then both objects have the same number which will function as a connection. You can use `EntityFieldQuery` to find the related objects whenever you have the campaign nid.

This is pretty crude though, hopefully there is a smarter way.

Here is some sample code (untested, probably will need a little debugging, paths are from memory).

```
function my_create_a_node_form() {
  //form stuff goes here.

}

function my_create_a_node_form_submit() {
  //menu_get_object retrieves the current objects that loaded. We're storing it
  // we're storing it in a variable.

  $currentcampaign = menu_get_object();

  //we collect the nid from the campaign.
  $currentnid = $currentcampaign->nid['value'];
  global $user;

  $values = array(
    'type' => 'order',
    'uid' => $user->uid,
    'status' => 1,
    'comment' => 1,
    'promote' => 0,
  );
  $entity = entity_create('node', $values);

  $ewrapper = entity_metadata_wrapper('node', $entity);
  $ewrapper->title->set('YOUR TITLE');

  //here we store the nid in our pre set-up order field.
  $ewrapper->field_my_order_ref->set('$currentnid');

  //the rest of this is just standard create a node stuff.
  $my_body_content = 'A bunch of text about things that interest me';
  $ewrapper->body->set(array('value' => $my_body_content));
  $ewrapper->body->summary->set('Things that interest me');

  $my_date = new DateTime('January 1, 2013');
  $entity->field_my_date[LANGUAGE_NONE][0] = array(
     'value' => date_format($my_date, 'Y-m-d'),
     'timezone' => 'UTC',
     'timezone_db' => 'UTC',
   );

  $ewrapper->save(true);
  entity_save('node', $entity);

}

```

---
Tags: nodes
---


# Question
Title: Setting values for custom display fields in Views
thanks in advance for your help with this.

Firstly, the Basic Page type of my drupal build has a Title (as per usual) and a Subtitle custom field. The Title and Subtitle are then displayed in a header when viewing the node.

I then have a View which is producing a page displaying a list of Employees from the Employee content type. The Employee content type does not have the subtitle field. When the view is displayed it uses the standard page.tpl.php which will display the subtitle field if it exists.

Since the View is displaying a page, it is not bound to any specific Basic Page node so there is no subtitle to pull in to the View.

Is it possible to add the subtitle variable into this View so I can fill it with a custom piece of text and have it display on the View page.

Thanks again.

EDIT: Updated text to clear up confusion

# Answer
> 2 votes
There are a couple of ways to go about this, if I understand your goals correctly:
1) If your view is set up to use Fields, you can customize the Subtitle field to include additional content along with what is coming from the Node's field.
To do this, Edit the view, Select the field, Expand "Rewrite results", and then you can use a Replacement Pattern token along with your additional text:

```
The subtitle is [field_subtitle], yes it is!

```

2) If your view is set up to display as a Node, you would create a Node template override, named like node-contenttype\_with\_subtitle.tpl.php, and you can format your layout specifically for your need here:

```
echo 'The subtitle is '.$node->content['subtitle']['#value'].', yes it is!';

```

Note that the 2nd approach would affect the appearance of that content type everywhere, not just in the view. So, if you want this special treatment of the subtitle only in your view, then the 1st approach may be preferable.

A third option would be a field-level override template, where you would create a file named something like views-view-field--subtitle--page.tpl.php and control your output there. Here is an in-depth look at that approach: https://drupal.org/node/352970

(Please let me know if I misunderstood your question, and I'll be glad to take another stab at answering.)

---
Tags: views, nodes
---


# Question
Title: When should I use hook_field_attach_presave(), and when hook_entity_presave()?
I was looking for a way to act on entity fields before they are saved, and I have noticed the following about hook\_field\_attach\_presave(), and hook\_entity\_presave():

* They take the same parameters, but in a different order.
* They are both called when an entity is saved. For example, taxonomy\_term\_save() contains the following code.

```
// Invoke hook_field_attach_presave().
field_attach_presave('taxonomy_term', $term);

module_invoke_all('taxonomy_term_presave', $term);
module_invoke_all('entity_presave', $term, 'taxonomy_term');

```

Similar code is present in comment\_save().

```
field_attach_presave('comment', $comment);

// Allow modules to alter the comment before saving.
module_invoke_all('comment_presave', $comment);
module_invoke_all('entity_presave', $comment, 'comment');

```

As they get the same parameters, the code I should write to access the entity's fields is the same for both the hooks. This means that, apparently, there isn't any reason to choose one instead of the other hook.

When should I then implement one hook instead of the other? Are there cases where I would implement `hook_field_attach_presave()`?

# Answer
> 9 votes
It depends on what type of data you are trying to modify. Some entities are not fieldable. Those entities would never call hook\_field\_attach\_presave() where as they would call hook\_entity\_presave().

If you are modifying an entity's base properties such as 'title', you should use hook\_entity\_presave(). If you are modifying the fields attached to an entity, you should use hook\_field\_attach\_presave().

Keep in mind that other modules might be using these hooks as well. They would expect you to be making your modifications to the type of data in its respective hooks.

# Answer
> 4 votes
Personally, I would recommend to use the entity hooks. The reason is simple: The field attach hooks no longer existing in Drupal 8.

That both exist has mostly historical reasons. The field system and the field attach functions and hooks have been added to Drupal 7 before the entity concept even existed. Then the entity system has been gradually introduced but it was no longer possible to unify those hooks.

Drupal 8 no longer has a separate field storage API, this has been completely unified.

---
Tags: 7, entities
---


# Question
Title: "Undefined index: und" Error fetching array in node form
I am facing this error in node form when I going to be print title of the body field.
Error:

> Notice: Undefined index: und in include() (line 4 of C:\wamp\www\drupalapi\themes\bartik\article-node-form.tpl.php).

I need to print the title of the body field, and my code looks like:

```
print $form['und']['#title'];

```

And shortly, the array is:

```
Array
(
[#type] => container
[#attributes] => Array
    (
        [class] => Array
            (
                [0] => field-type-text-with-summary
                [1] => field-name-body
                [2] => field-widget-text-textarea-with-summary
            )

    )

[#weight] => -4
[#tree] => 1
[#language] => und
[und] => Array
    (
        [#theme] => field_multiple_value_form
        [#field_name] => body
        [#cardinality] => 1
        [#title] => Body
        [#required] => 0
        [#description] =>
        [#prefix] =>
[#suffix] =>

        [#max_delta] => 0
        [#after_build] => Array
            (
                [0] => field_form_element_after_build
            )

        [#language] => und
        [#field_parents] => Array
            (
            )

```

What i am missing in my code to print the title of the body field. Thanks

# Answer
Greatly explained by user20301.
If you still not sure how to print the title then do something like this in your tpl.php file:

```
print $form['body']['und']['0']['#title'];

```

This will print the title of body field "Body" in node form.
> 0 votes

# Answer
To get usable markup of the field in template you need to render it before print.

```
print drupal_render_children($form['title']);

```

As explained here Theming Node Forms in Drupal 7

Additionally make sure you also render the hidden parts of the form to keep track of form identity related to system. If you wish to exlude some parts of the form, do something like this.

```
hide($form['field_body']);
print drupal_render_children($form);

```

This way drupal "render api?" can be aware of what has allready been rendered, what needs to be hidden and finally push out all required parts to make form functional.
> 3 votes

---
Tags: nodes, theming
---


title: Validation at node_presave in drupal 6

text:
# Question
Title: Validation at node_presave in drupal 6
I received a somewhat complicated Drupal 6 application to maintain and unfortunately I am quite a newbie with Drupal.

The task is to verify certain system variable is set before saving the node. Is the node\_presave ok place to do this? And how can I abort the saving process?

It should fail silently with a log message.

# Answer
> 3 votes
No, `hook_nodeapi op=presave` is the wrong place for that.

You should instead use `hook_nodeapi op=validate`

> "validate": The user has just finished editing the node and is trying to preview or submit it. This hook can be used to check the node data. Errors should be set with form\_set\_error().

https://api.drupal.org/api/drupal/developer%21hooks%21core.php/function/hook\_nodeapi/6

However, it won't fail silently, instead showing an error on the node form.

---
Tags: 6, hooks, nodes, forms
---


title: Facebook integration

text:
# Question
Title: Facebook integration
I am currently developing a real estate website, and the client wants to push a notification to his Facebook page when he edits or adds a real estate.

How can I achieve this, with a module or hard-coded?

# Answer
> 1 votes
Post It Everywhere just one click and your content will be posted to:

* Facebook
* Twitter
* LinkedIn
* FriendFeed

The most common way to make your site popular is by posting your content to different social networks. Here is a new and simple way for publishing content to different social networks.

> Features:
>
> * The link "Post it Everywhere!" will be displayed with every node type(the admins select). This link will be used to post on all the networks
> * Authenticate Once, Use Forever: The users don’t have to authenticate every time when they login to the site or want to post content. Each user will authenticate himself only once and these saved settings will be used to post in the future.
> * The users will not be moved to other sites to post the content (as it happens in various modules that users are redirected to that social network on which they want to post).
> * The user names and passwords of users are not saved for this purpose so no risk for security and spoofing.
> * Facebook Connect API is used to send posts to Facebook and OAuth is used to connect to LinkedIn, Twitter and FriendFeed. OAuth API can be downloaded from this link.
> * End users can update their settings at anytime.

---
Tags: social-network
---


# Question
Title: Not able to save the selected custom populated option list
I have a cck select list where the options are populated by my custom code. There is no issue for populating the list but after that the selected options are not able to save. Is there any way to fix this. Here is my code snippets:

```
function pelikan_common_form_alter(&$form, $form_state, $form_id) {
if ($form_id =='monitoring_node_form'){
    $nid = arg(3);
    $node = node_load($nid);
    $index=0;
      foreach ($node->field_test_monitoring['und'] as $key) {
       $show = node_load($key['nid']);
       $form['field_indicator']['und']['#options'][$index++]= $show->title;

     }
   }

```

# Answer
List fields are tied to their allowed values and they make sure all the values in the database align with what is in the allowed values.

To programatically populate list fields, there is a lesser known feature, which is that you can set the 'allowed\_values\_function' setting of your field instance.

If you are programatically creating your field you just add it in the settings. If not you could do one of these things:

* Form alter the field settings form to make the allowed\_values\_function field a visible text field you can enter a function name into.
* Implement hook\_enable() in your custom module to load the fields in question and set the allowed\_values\_function and then save the fields. Then use hook\_disable() to reverse the cahnge when you disable the module.
* Go in the database directly and set the value in the field settings.

Your allowed value function should be of the form:

```
function function_name($field, $instance, $entity_type, $entity, $cacheable) {
  // return an array of values.
  $values = array(
    'val1' => t('Value 1'),
    'val2' => t('Value 2'),
    'val3' => t('Value 3'),
  );

  return $values;
}

```

There is another module though that makes things a little nicer: List field predefined options

It allows you to implement it's hook to define allowed value functions, which you can then select from in the field UI.

For example:

```
/**
 * Provide information about available predefined list options.
 *
 * @return
 *   An associative array whose keys define the machine name for each
 *   predefined list options and whose values contain the list options
 *   descriptions. Each list options description is itself an associative
 *   array, with the following key-value pairs:
 *   - 'label': (required) The human-readable name of the list options.
 *   - 'callback': (required) The name of the function that will return the
 *     list options.
 *
 * @see hook_list_option_info_alter()
 */
function MYMODULE_list_option_info() {
  $info['FIELD_NAME'] = array(
    'label' => t('Name that describes the values this callback will return'),
    'callback' => 'mymodule_function_that_returns_allowed_values',
  );

  $info['ANOTHER_FIELD_NAME'] = array(
    'label' => t('Name that describes the values this callback will return'),
    'callback' => 'mymodule_another_function_that_returns_allowed_values',
  );

  return $info;
}

```

Then you can implement the functions you defined in the above hook to return the allowed values and in the field UI you can select to use the function by its label. Much more user friendly.
> 0 votes

# Answer
Finally, I solve this problem. I came to know that indexing the options is not required so finally I change this line:

```
$form['field_indicator']['und']['#options'][$index++]= $show->title;

```

to this

```
$form['field_monitoring']['und']['#options'][$show->nid]= $show->title;

```

and got rid of the $index variable and now I can populate the node reference field in the select list and also can save.
> 0 votes

---
Tags: nodes
---


title: Modify apache solr search sort options?

text:
# Question
Title: Modify apache solr search sort options?
Is there the ability through contrib module or hooks to modify how the apache solr sort block sorts queries?

Currently, it seems it supports these queries out of the box:

* Relevancy
* Title
* Author
* Date

What i would like to have is to remove Author, Add a field to sort title from a-z and z-a. Is that possible?

# Answer
> 5 votes
You can find all info with examples here: http://drupal.org/node/715276

```
<?php
function MYMODULE_apachesolr_query_prepare(DrupalSolrQueryInterface &$query, &$caller) {
  $query->addParam('fl', 'some_field_image');
  $query->addParam('fl', 'some_field_date');
  //Remove sorts
  $query->remove_available_sort('sort_label');
  $query->remove_available_sort('bundle');
  $query->remove_available_sort('sort_name');
  //Rename sorts
  $query->remove_available_sort('score');
  $query->set_available_sort('score', array('title' => t('Relevance'), 'default' => 'desc'));
  $query->remove_available_sort('ds_created');
  $query->set_available_sort('ds_created', array('title' => t('Latest'), 'default' => 'desc'));
 }
?>

```

# Answer
> 1 votes
There is a module Apachesolr Sort that provides an UI to configure apachesolr sort block. From module page:

* Removal of a sort by field
* Weights for the sort by fields
* Neat integration with the apachesolr modules.
* Adds a block that gives you a select block to sort your results on.

---
Tags: 7, search
---


# Question
Title: Get single field valure from node object
I have loaded a node object in my module, I want to get the single value entered for a specific field (a text field).

I can access it directly with `$node->field_position['und'][0]['safe_value']`.

Is there a better way to do this? I have looked at field\_get\_items and field\_view\_value but I dont want a renderable array or an array at all. Isn't there a way to just return the string value? Having

```
$items = field_get_items('node', $node, 'field_position');
$position = $items[0][safe_value];

```

just seems like additional code that doesnt make it any simpler

# Answer
Entity API

Documentation says: The Entity API provides wrapper classes you may use to make dealing with the values of an entities properties and fields easier. Wrappers make it easier to get and set the values of fields and properties as well as to programmatically retrieve additional information about these elements and iterate over lists of values in a consistent manner. https://drupal.org/node/1021556

```
    // Create wrapper around the node.
    $wrapper = entity_metadata_wrapper('node', $node);

    // We can do it also using only $nid.
    $wrapper = entity_metadata_wrapper('node', $nid);

    // Get the value of field_name of the node.
    $wrapper->field_name->value();

    // Get the value of field_name of the nodes author's profile.
    $wrapper->author->profile->field_name->value();
    $wrapper->author->profile->field_name->set('New name');

```
> 7 votes

---
Tags: entities, nodes
---


title: hook_form_alter execution order

text:
# Question
Title: hook_form_alter execution order
Is there a way to change the order of execution of hook\_form\_alter in Drupal 7 without changing a module's weight or hacking Drupal Core?

I am trying to alter the element added in translation\_form\_node\_form\_alter from the translation module. When debugging the form I can't find the element so I assume my hook is being executed before the one in the translation module is.

# Answer
> 1 votes
I don't think so. `translation_form_node_form_alter()` implements `hook_form_BASE_FORM_ID_alter()` which I believe is called *after* `hook_form_alter()`, so even changing the module weight wouldn't be enough. I think your two options are to use a `hook_form_BASE_FORM_ID_alter()` and ensure you have a high enough module weight, or use `hook_form_FORM_ID_alter()` (if possible).

# Answer
> 18 votes
Also worth mentioning, there is a new drupal 7 API called hook\_module\_implements\_alter() which lets you alter the execution order for a given hook WIHOUT altering the module weights table.

Sample code from the API docs showing how easy this is to do:

```
<?php
function hook_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'rdf_mapping') {
    // Move my_module_rdf_mapping() to the end of the list. module_implements()
    // iterates through $implementations with a foreach loop which PHP iterates
    // in the order that the items were added, so to move an item to the end of
    // the array, we remove it and then add it.
    $group = $implementations['my_module'];
    unset($implementations['my_module']);
    $implementations['my_module'] = $group;
  }
}
?>

```

# Answer
> 5 votes
Here is how to make sure your hook\_form\_alter is called after another modules hook\_form\_alter:

```
/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, &$form_state, $form_id) {
  // do your stuff
}

/**
 * Implements hook_module_implements_alter().
 *
 * Make sure that our form alter is called AFTER the same hook provided in xxx
 */
function my_module_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'form_alter') {
    // Move my_module_rdf_mapping() to the end of the list. module_implements()
    // iterates through $implementations with a foreach loop which PHP iterates
    // in the order that the items were added, so to move an item to the end of
    // the array, we remove it and then add it.
    $group = $implementations['my_module'];
    unset($implementations['my_module']);
    $implementations['my_module'] = $group;
  }
}

```

This also works when the other module has provided a form\_alter hook in the variation: hook\_form\_FORM\_ID\_alter. (they explain that in the documentation: hook\_module\_implements\_alter).

I know that this post is quite similar to wiifm's post, but thought it useful with an example with hook\_form\_alter

---
Tags: 7, forms, hooks
---


# Question
Title: ctools_ajax_command_redirect is no longer working to redirect ajax form on successful submit
My ajax callback function which is changing a form did redirect properly in the past, but now with no change to this code it does not work anymore.

```
function node_create_callback($form, &$form_state){
    module_load_include('inc', 'node', 'node.pages');
    node_form_validate($form, $form_state);
    if (!form_get_errors()){

      //on success submit form and redirect
      node_form_submit($form,$form_state);
      ctools_include('ajax');
      ctools_add_js('ajax-responder');
      $commands =  array(ctools_ajax_command_redirect("node/"));
      return array('#type' => 'ajax', '#commands' => $commands);
    }
    else
    {
      //on error display errors on form without refreshing page
      $commands = array('#type' => 'ajax', '#error' => FALSE, '#commands' => array());
      $output = drupal_render($form);
      $commands['#commands'][] = ajax_command_insert(NULL, $output);
      // Prepend status messages to the node form.
      $commands['#commands'][] = ajax_command_prepend(NULL, theme('status_messages'));
      return $commands;
    }
}

```

# Answer
instead of

> return array('#type' =\> 'ajax', '#commands' =\> $commands);

try this

> print ajax\_render($commands);
>
> drupal\_exit();

I had a similar problem, and this code worked for me.

courtesy: Ajax redirect on successful submission is not working properly

Hope that helps!
> 1 votes

---
Tags: 7, forms, ajax, redirection
---


# Question
Title: Views - Filtering view results by current user profile field
I have been trying to do this last couple of days but no luck.

Every user have a custom field (favorite\_car) which is taxonomy and there is different terms ('Audi','Bmw' etc).

I have also content type 'Cars' which had also a custom field (favorite\_car).

I need to display only the results, that user have selected. If user have a custom field selected to 'Bmw', view need to return only nodes which have a favorite\_car field set to 'Bmw'.

I think that there is a way to do this in drupal 7. Every kind of help is welcome.

# Answer
You can filter contents on their term\_reference\_field by the field\_value of a term\_reference\_field of the current\_user:

So we go:

* Create a content\_view
* Create a relationship with "favorite\_car"
* Create a relationship with "term from favorite\_car"
* Create contextual filter user:uid with provide default\_value: user\_id from logged in user and the relationship favorite\_car

This works for me!
> 5 votes

# Answer
Look at the answer to Add Taxonomy Term automatically based on term from user's account

Replace the references to "state of residence" with "favorite car" and references to "forum postings view" with "car listings view".
> 0 votes

---
Tags: views
---


title: if statement with content of a form

text:
# Question
Title: if statement with content of a form
I searched a lot without success, i hope i can find the right answer for me.

I want to make a simple bet system, without any real money. At the time of the registration the user get x fakecredits. I decide to use the comment system to check how much the user wants to bet, so i added a field called bet to comment form.

What i want to do now is very simple as logic:

```
if (Bet < User Money){
 submit content;
}else{
 don't submit;
}

```

i already made a view that shows user money. i only need the if statement. I also created a module with module\_form\_alter, but i don't know what to put then.

Thanks in advance

Drupal version 7.x

# Answer
I use another method. I coudnl't find the way to print the input of the user, until i find this:

```
$form_state['input']['field_bet']['und'][0]['value']

```

And checked if it was greater or lesser then $user-\>fakemoney
> 0 votes

# Answer
Sounds like something to put in the field or form validation.

```
$form['#validate'][] = 'form_validate';

```

or

```
$form['your_field']['#element_validate'] => array('_field_callback_validate'),

```
> 0 votes

---
Tags: forms, comments
---


# Question
Title: How to add the input text field in node view page
How can i add the field(input filed) for particular content type in submitted node view page.Using this field i can add some text to the particular node. Please suggest me is there any module for this or custom code.....

I think I've made it clear, please answer

# Answer
You can use editablefields module.

> This module allows CCK fields to be edited on a node's display (e.g. at node/123), not just on the node edit pages (e.g. node/123/edit). It also works within views etc. Anywhere a 'formatter' can be selected, you can select editable (or click to edit).

You can follow the below step for setting up editablefields for your content type.

* Go to Administration -\> Structure -\> Content type
* Edit your content type and then click on "Manage Display"
* Change the Format to editablefields for your field.
* Once you set the formatter, you can click on the gear icon to further change the settings - the settings vary per field type
> 1 votes

---
Tags: views, 7, entities, nodes
---


# Question
Title: Hiding empty section of a custom content type if field is left empty
I am relatively new to Drupal so I need someone to school me here.

I have created a custom theme and using theme key to attach it to a new content type (HTML Email). It roughly has about 12 sections consisting of a header graphic and a text area.

I’ve created a view and added all the fields to it displaying as a block in my custom theme using the views-view-fields—\[name\].tpl.php.

It displays perfectly but my issue is not all the section of the content type will be used so If the text area in a section is left blank I want that section not to show up in the block.

Below doesn't seem to work

```
<? if ($fields['field_text']->content): ?>
     <table border="0" cellpadding="5" cellspacing="0" width="100%">
        <tr>
           <td><?php print $fields['field_header']->content; ?></td>
       </tr>
       <tr>
         <td valign="top" style="padding:5px 20px"><?php print $fields['field_text']->content; ?></td>
  </tr>
</table>
<? endif; ?>

```

# Answer
See also the Empty Field module:

https://drupal.org/project/empty\_fields

This module can replace the markup of an empty field with some other output, which might be helpful in this case.
> 0 votes

# Answer
If I'm understanding your question correctly, you're testing for a string in $fields\['field\_text'\]-\>content and finding that even when it seems to be blank, it still prints the table.
You might try outputting the contents, like

```
var_dump($fields['field_text']->content);

```

Perhaps there is some "invisible" content, like

```
<p></p>

```

If that's the case, then you could strip that out before testing for the existence of a string in the variable.

```
$tmp_content = strip_tags($fields['field_text']->content,'<p>');
if($tmp_content):
// print table, etc.

```
> 0 votes

# Answer
If you will check your html code for that field, then you will find that `<span class="field-content"></span>` code for your field. So, there is content in your field and your condition will not be validate.

You can hide the empty fields from your views by setting in admin of views as below.

* Go to Administration -\> Structure -\> Views.
* Edit your views.
* Click on specific field in your views under Field section.
* Checked `Hide if empty` check-box under NO RESULTS BEHAVIOR fieldset and save the views.

Or you can use `strips_tags` in your code to remove html tag from the content of the field.
> 0 votes

---
Tags: entities
---


# Question
Title: Apply a product discount if orders are picked up
I have a Drupal Commerce site where customers get to choose whether to ship the order, or if they want to come and pick it up. Picking up is free, obviously. This part works already, and I don't need help with.

There is an additional discount that should apply to one specific product only when the customer comes to pick up his order. There could be other products in the order besides the one specific product, and those products would not be discounted. This discount would be applied if "picking up" is specified during the check out process. I'm having a bit of trouble getting the event/conditions right: it seems to me that no shipping method has been picked when the sell price is calculated.

Menno

# Answer
Aren't the shipping methods themselves using rules? I would try to edit the rule for the Pickup shipping method and see if I could add the discount from the Actions of that Rule.

If you know how to use Rules Components, you could further encapsulate this so all the discount-related stuff was in a separate Rule Component.
> 0 votes

---
Tags: commerce, rules
---


# Question
Title: Some of the user profile fields on registration page not showing in user edit page
I have customized user profile edit page as page-user-edit.tpl.php in drupal 6 and created custom fields in user profiles like COMPANY SIZE with radio buttons, NO OF EMPLOYEES etc.

It is configured to display these field during registration based on role. It works well. My problem is these fields are not being displayed on user edit page (user/\*/edit). Is there any way i can display the fields on user edit page to update values.

Here is my code on page-user-edit.tpl.php

```
<div id="container">
<div id="wrapper">
<div id="page_tp">

<?php if(arg(0) == 'user' && arg(3) == 'profile' && arg(1) != '0' && trim($user->roles[3]) == 'Corporate Profile'  ){ ?>

<?php print $help; ?> <?php print_r($content); ?>

<?php } ?>

</div>
</div>
</div>

```

# Answer
> 0 votes
I think the custom fields comes under a new tab. The tab name would be the value you given in the category field . please check

---
Tags: users
---


# Question
Title: Lock Workbench content until moderation state change
I'm managing content workflow using the Workbench module. Content is moved through various states until it's made live by the publisher.

I've managed to lock content whilst it's being edited, using the Content locking module, which seems to do the job well. **However**, I now have another requirement to lock the content to the user until the user is finished editing it, which is to be indicated by changing the state to the next level, such as 'Ready for review'.

Can anybody suggest a method of doing this?

# Answer
> 2 votes
There is a really cool module called Rules Forms that could help here. https://drupal.org/project/rules\_forms

1. You have to set it up so that it works with your particular content type. See admin/config/workflow/rules/forms
2. Create a Rule and set two Events "XX node form is being built", and "XX node form is being validated", where XX is your content type
3. Set an Action called "Set an error on the form" and then choose "Title" for lack of something else, and then enter a message about this node being locked.
4. Set up the conditions as needed - probably need to check the user id and the state of that node - this is the part where I can't help without seeing your particular site.

If you don't set any conditions, nobody will be able to create or edit nodes of this type until you do.

---
Tags: rules, workflows, workbench
---


# Question
Title: Automatically add users to the same group as their group admin
I am using the Organic group module. I created 2 groups on my site. To each group I assigned 1 user as group admin. Group admins have the permission to create users.

My question is how to automatically assign the users which got created by a group admin to the group admin's group?

# Answer
> 0 votes
In Drupal 7, you can achieve it using **hook\_user\_insert** and OG function **og\_group**.

* **hook\_user\_insert** : Called when a user account is created
* **og\_group** : Set an association (e.g. subscribe) an entity to a group

```
 /**
     * Implemention hook_user_insert
     * @global type $user
     * @param type $edit
     * @param type $account
     * @param type $category
     */
    function HOOK_user_insert(&$edit, $account, $category) {
        global $user;
        $usr_grps = og_get_entity_groups(); //get all user groups
        if (count($usr_grps) > 0) {//if any groups
            $grp_mgr_grps = array();
            foreach ($usr_grps['node'] as $key => $gid) {
                $group_type = 'node';
                $group = entity_load_single($group_type, $gid);
                if (is_object($group)) {
                    if (!empty($group->uid) && ($group->uid == $user->uid)) {//subscribe only the groups where the user is group manager
                        $grp_mgr_grps[] = $gid;
                    }
                }
            }
            if (count($grp_mgr_grps) > 0 && is_object($account)) {
                HOOK_subscribe_grpmgr_groups($grp_mgr_grps, $account); //subscribe the group
            }
        }
    }

    /**
     *
     * @param type $grp_mgr_grps : array of group ids
     * @param type $account : Object of the user we want to add to the group
     */
    function HOOK_subscribe_grpmgr_groups($grp_mgr_grps, $account) {
        foreach ($grp_mgr_grps as $key => $gid) {
            $group_type = 'node'; //All groups are of type node
            $values = array(
                    'entity_type' => 'user',
                    'entity' => $account->uid,
                    'field_name' => FALSE,
                    'state' => 1,
            );
            og_group($group_type, $gid, $values);
        }
    }
```

---
Tags: organic-groups
---


# Question
Title: Display Google Map after entering address?
Trying to find an easy way to do the following:

1) Visitor enters their address in a form field 2) Google map display's their address on the page

Does not seem to be an easy way to accomplish this in Drupal 7?

# Answer
> 2 votes
I think you are looking for geofield gmap module, it have the option same like your requirement. See the below screenshot and also easy to configure.

Geofield Gmap allow to use a google map v3 map to **input a location**.

A **quick text input + geocode** allow you to specify an address.

You can also drag and drop the marker to narrow the position.

Geofield Gmap require geofield.

Geofield is a module for storing geographic data in Drupal 7. It supports all geo-types (points, lines, polygons, multitypes etc.)

---
Tags: google-maps
---


# Question
Title: How to get "empty line items" in Commerce, similar to Ubercart?
In Ubercart, there is a little feature for adding "empty line items" to an admin created order. This allowed an admin to manually enter a custom title for the line item and a custom amount. Essentially allowing you to add line items without going through the process of creating a product first, then attaching it to the order. Very helpful for creating invoices for custom services. Is there any way I can get this feature in Drupal Commerce?

This is how it looks and works in Ubercart:

# Answer
> 3 votes
I've just created and submitted a module that might suit your needs. It is currently in sandbox. Let me know!

# Answer
> 5 votes
In Drupal Commerce, we made the decision to add line item type dependent callbacks to the line item API. A product line item will function differently from a shipping line item will function ... etc. As a side effect, this means there is no such thing as a "generic" line item, just like there is no such thing as a typeless node.

What needs to happen, if it doesn't already exist, is a small contrib module could be made that adds a basic line item type whose "line item add form" in the order edit page lets you specify all the information needed to manage and display that line item. Where it's gonna break down are things like pricing rules - should these line items have taxes? Should other discounts apply? Or display rules - should these show up on customer order pages?

There is no such feature in core (as you can see, it'd be a small contrib, but it wouldn't be trivial to make), but if it were tested and proved as a concept in contrib, I don't see why we couldn't consider it for inclusion in Commerce 2.x.

# Answer
> 0 votes
Maybe a workaround could be to create a generic product and use Commerce Customizable Products. Here is an excerpt about it from the module's project page:

> Drupal Commerce allows you to sell customizable products that require customer input when added to the cart. Use cases for this functionality include:
>
> * Business cards that require contact information and a logo upload.
> * Event registrations that require attendee information.
> * Donations the allow the customer to specify a donation amount.

What do you think about?

---
Tags: commerce, ubercart
---


title: How to style a view in Omega

text:
# Question
Title: How to style a view in Omega
I want my view to use Omega's grid system, but could not find a way to do it.

There is this thread http://drupal.org/node/1491678 that suggests using "Views Column Class" module. Is that the best way to do it or I am missing something?

# Answer
> 3 votes
Yes, Views Column Class is the best way to do it in my experience.

All you need to do is set the row class to an alpha grid class, and the number of columns for the display mode you're using, e.g.

and the module will take care of adding the alpha/omega classes to the appropriate elements on your page, giving you properly responsive views for very little work.

It's worth remembering that a 'row' in the context of a floated list is each individual item, not a row of x number of elements. So when you apply `grid-4` etc, it's applied to each individual element, not the whole row. It can be confusing at first.

# Answer
> 1 votes
In D7, I was able to use **views responsive grid** with the default omega subtheme from commerce kickstart (omega kickstart) to create a 4-column responsive grid layout...

**Step:**

1. Install the views responsive grid module.
2. Create your page view.
3. Change the format to *Responsive grid*.
4. Under settings, set the number of columns to 4.
5. Under Column Classes, add ***grid-6*** to every column, ***alpha*** to the first column, and ***omega*** to the last column.
6. Under Row Classes, add ***grid-24 alpha omega*** to every row.

Adjust the ***grid-n*** classes mentioned above to suite the number of columns required for your use case. There may be a better way to do this, but this worked perfectly for me.

**As noted on the views responsive grid project page:**

> *This module will not be ported for Drupal 8. Views grids in core have been replaced with DIVs: #1903746: \[Change notice\] Replace the views grid table template with one using divs!*

# Answer
> 0 votes
This depends entirely on the the layout and design that you are trying achieve. Views column class (VCC) is great for some tasks. Other tasks can be solved without it and instead you'd just add the required 960gs class to the row in Views. Depending on the the use case (and required browser support) this could be further styled with just CSS (nth-child, odd/even classes - depends on your design).

VCC was designed to get around the lack of nth-child support in old browsers such as IE8 and below and provide an alternative to Views' dubious table based grid display option.

Is it a grid layout that you're going for? How do you want the view to respond on viewport resize?

# Answer
> 0 votes
Views Column Class didn't really work for me. Instead, I implemented what you can find in this article http://goo.gl/yfCy8. By playing with width and margin left, you can decide how many columns you want for your different screen sizes. So you can repeat the same code with different values in the different stylesheets (wide, normal, narrow...) and make something that looks sharp no matter the screen size.

---
Tags: views, theming
---


title: drupal CDN module not altering URLs

text:
# Question
Title: drupal CDN module not altering URLs
I'm using Drupal 7 on an Ubuntu VPS, I'm trying to setup CDN module with Rackspace cloud files. I'm using file conveyor and the whole setup going well. the only problem I have that Drupal CDN module not altering the files url to use the cdn urls. it still use local files. \- the files already synced to rackspace. \- file conveyor working fine. \- Drupal CDN configured correctly and it show me that it sees file conveyor working and it's sees the sync file database.

* more details about the issue: I'm using multisite setup and I'm using file conveyor with the public files folder.

Any Advice? Thanks

# Answer
I suspect you have a setting or two wrong. On admin/config/development/cdn make sure you are enabled, and not in testing mode:

Then goto admin/config/development/cdn/other, expand all of the sections and make sure you aren't excluding actual pages.
> 2 votes

---
Tags: cdn
---


title: Civicrm Membership Type in webforms

text:
# Question
Title: Civicrm Membership Type in webforms
I am using the webform\_civicrm module. It is not having the option to link the membership type to webforms. How can I link membership type to webforms?

# Answer
Support for memberships was just added in version 4 of Webform-CiviCRM integration. If you upgrade to that version then membership types will become available.
> 6 votes

---
Tags: webforms, civicrm
---


# Question
Title: Are node title & body instances update-able through the field API?
I'm guessing it's not possible, since what works on other instances won't for the title & body. (Trying to adjust widget weight.)

```
  $core_instances = array(
    // array(
    //   'field_name' => 'title',
    //   'entity_type' => 'node',
    //   'bundle' => 'article',
    //   'weight' => 1,
    // ),
    // array(
    //   'field_name' => 'body',
    //   'entity_type' => 'node',
    //   'bundle' => 'article',
    //   'weight' => 4,
    // ),
    array(
      'field_name' => 'field_tags',
      'entity_type' => 'node',
      'bundle' => 'article',
      'weight' => 7,
    ),
    array(
      'field_name' => 'field_image',
      'entity_type' => 'node',
      'bundle' => 'article',
      'weight' => 6,
    ),
  );

  foreach ($core_instances as $instance) {
  $instance_info = field_info_instance($instance['entity_type'], $instance['field_name'], $instance['bundle']);
  $instance_info['widget']['weight'] = $instance['weight'];
  field_update_instance($instance_info);
  }

```

If I uncomment the title & body instances, I get the following error:

> FieldException: Attempt to update an instance of a nonexistent field . in \[error\] field\_update\_instance()

# Answer
The Title is not a field unless you're using the Title module. That's why your first call doesn't work.

Body should work, unless you've deleted the field (can you see it on admin/structure/types/manage/article/fields?)
> 4 votes

---
Tags: entities
---


# Question
Title: Make a view content only appear when user is logged in
In Drupal 7, I need to create a view of member-only nodes. They're all of a certain type. This type—and I've already set that up with role-based access control—can only be seen by logged in users.

Now, I can create a view called *Member Area* that shows these nodes, and make it accessible only to logged in users (through the View access control), but when I create a menu entry for that view, the link obviously disappears when the user isn't logged in.

What I need is a link that points to a "please log in" text (could be on a static page, whatever) when the user isn't logged in. If the user then logs in, I want to display the view which shows only the restricted content.

Giving a specific example, I currently have this. The block is conditionally shown in the sidebar only on the page called *Member Area*. The page displays the static *You are not logged in…* text.

Once the user logs in, I want to show them the view of restricted content:

The horrible kludge that I use now is that I link the user to another view in the user menu, but that's really bad UX.

Can I set this up somehow?

# Answer
What I did was quite simple:

* Create the view normally, without access restrictions and link it to the menu.
* Make sure the nodes themselves can only be seen by logged in users.
* Create a *No results behavior* text that tells users to log in.
* Show the login block only on the view's page.
> 2 votes

# Answer
I believe you're looking for https://drupal.org/project/r4032login

In addition to that, this module: https://drupal.org/project/menu\_item\_visibility will allow you to set the menu item to be visible to anonymous users as well even though they can't access its content. when they click on it they're redirected to login.
> 1 votes

---
Tags: 7, views, routes, users
---


# Question
Title: Adding CSS around taxonomy terms in node field
In my node, I have a taxonomy field that displays one or more taxonomy terms (as plain text using DS). I want to wrap a CSS class around the term, depending on the term value.

Where is the best place to do this?

# Answer
I did this in preprocess\_taxonomy\_term(), and just added to classes\_array.
> 1 votes

---
Tags: 7, entities, taxonomy-terms
---


# Question
Title: How to insert an RTMP url from an adobe streaming server (rtmp://example.com/myvideo.flv) in drupal 7?
I need to create a video gallery and would like some advice on how to view flash videos on drupal 7.

The url I have to insert are rtmp (rtmp://example.com/myvideo.flv).

Any ideas on what modules to install and the steps to follow?

I read on the previous questions about flowplayer but it's only supported on Drupal 6.

Many thanks for your help.

# Answer
You can use JWPLAYER , and here is an example for how you setup the streaming

1- in the page header you include the jwplayer js library 2- follow the embedding guide "http://www.longtailvideo.com/support/jw-player/28839/embedding-the-player" 3- use the RTMP changes as it's documented here http://www.longtailvideo.com/support/jw-player/28854/using-rtmp-streaming/

So your simple code will look like this;

```

 jwplayer("myVideo").setup({
     file: "rtmp://example.com/application/mp4:myVideo.mp4",
     image: "/assets/myVideo.jpg",
     height: 360,
     width: 640
    });
```
> 1 votes

---
Tags: 7, files, media
---


# Question
Title: All taxonomy term paths default to the www.example.com root directory
After creating a new vocabulary and adding terms to it, clicking on the view tab of the term edit form sends me back to my root directory. And, of course, typing the term path in the url results in a page not found error message. What is going on? Strangely enough, not too long ago, I created a vocabulary and it still works well (clicking on the view tab takes me to the term page view.) However, older vocabularies no longer work when hey used to. Does anyone know what is going on? Any help on this one would be greatly appreciated. Thanks. :)

# Answer
> 1 votes
If you have pathauto module installed, you might want to check the taxonomies aliases go to "/admin/config/search/path/patterns" and look for the old Vocabularies and see how the path is setup. moreover you might want to delete all aliases and do a bulk update for theme "/admin/config/search/path/delete\_bulk" then "/admin/config/search/path/update\_bulk".

---
Tags: taxonomy-terms, uri
---


# Question
Title: How do you reorder the shipping services for drupal commerce?
There doesn't seem to be a weight option. How would one reorder the shipping services for drupal commerce?

# Answer
> 4 votes
You can use a custom hook to reorder services:

```
<?php
/**
 * Implements hook_commerce_shipping_service_info_alter().
 */
function mymodule_commerce_shipping_service_info_alter(&$shipping_services) {
  if (isset($shipping_services['my_flat_rate'])) {
    $shipping_services['my_flat_rate']['weight'] = -10;
  }
}
?>

```

See discussion here: https://drupal.org/node/1537394#comment-7003814

Steps would be create a custom module or add this hook to existing module for your site, set the weight as code above ranging from -10 to 10 and you should be all set till there is a patch or update to overall Shipping module.

---
Tags: 7, commerce
---


# Question
Title: Security Review - Untrusted users are allowed to input dangerous HTML tags
I am getting the following error in my security review: Untrusted users are allowed to input dangerous HTML tags.

Is this because in my text formats I've got the following: Plain text All roles may use this format

Should I disable anonymous users from being able to access plain text?

Also, it is saying: It is recommended you remove the following tags from roles accessible by untrusted users.

```
img

```

Should I remove the img tag from authenticated users???? Does this mean that authenticated users will not be able to uploaded images to their site at all?

# Answer
Plain text is just that, no html tags, so this shouldn't be a security issue.

Perhaps the img tag is considered dangerous because it is possible to use a specially crafted png or jpg to launch an attack against a users browser.
> 0 votes

# Answer
img tags are vulnerable to XSS attacks

Since my site required roles higher than authenticated to submit content, I simply unchecked "authenticated user" from admin/config/content/formats/filtered\_html and that solved my audit report.
> -1 votes

---
Tags: security
---


# Question
Title: How do I use another field inside view as the base table?
I would like to know how I may use a database field from a custom module to build queries on.

By default, using content view starts off querying from the "node" table. I would love to have the Views module to query from my own custom table.

I have tried using `hook_views_data()` and set a base table, but it all came to nought so far.

# Answer
Give this module a shot - Views Expose Tables

> Exposes Drupal DB tables to Views
>
> This is a simple module which does one thing: provides an admin page for site-builders to choose which tables in a site's Drupal DB to expose to Views.
>
> The module then loads all the fields for each chosen table and detects the data type of the field and sets appropriate views field, sort, filter, and argument filters (for example numeric, string, date, or "default").
>
> It also looks for a primary key of the table and if one is found it sets it as the base field for a views base table and makes the table accessible to views.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Painless way to import content from old custom CMS
I am building a Drupal site (first ever) for a company that wants to move off of an outdated custom built CMS.

They have alot of content and we are pretty much keeping the content layout (fields) the same. And of course they want to have there content in the new Drupal site.

The Drupal database structure is pretty complex and I doubt a few simple insert queries will do the trick. I have written Python scripts to do stuff like this is in the past but not with a DB as complex as what Drupal sets up.

What options do I have for importing the old content into Drupal?

# Answer
"Painless" data migration? You're kidding, right? :)

There are numerous answers suggesting the Migrate module. It is certainliy an option, but one I've never liked. I've done dozens of projects with migrations of content from external systems into Drupal (sometimes from multiple external sources simulteneously), including projects with millions of pieces of content, and I'll argue 'til my death that a Batch API implementation in a custom module is the way to go.

No two migrations are the same. Each individual migration will involve 'proprietary' cleanup, data sanitization/changes, etc. The only way to have total control is with an entirely custom script. Don't settle for an easy "80% of the way there" via a generic tool and then struggle for weeks as you bash yourself against that 20% that the tool doesn't handle.

Do it custom, use Entity Metadata Wrappers, and track legacy \<--\> new content ids in a separate db table.

It may also be an option to simply 'dump' the existing content, markup and all, into a 'legacy' content type and call it a day without moving things into fields and complicating your life. You should sit down with the client and figure out exactly what they want/need, and what they're willing to settle for. Sometimes a simple solution that is just "okay" is a heck of a lot better than the multi-month project that's "awesome."
> 5 votes

# Answer
You should use Migrate module.

> The migrate module provides a flexible framework for migrating content into Drupal from other sources (e.g., when converting a web site from another CMS to Drupal). Out-of-the-box, support for creating core Drupal objects such as nodes, users, files, terms, and comments are included - it can easily be extended for migrating other kinds of content. Content is imported and rolled back using a bundled web interface (Migrate UI module) or included Drush commands
> 3 votes

# Answer
Just wanted to add for simple migration cases:

Migrate module is the most flexible, although for simple CMS data you can use the feeds module to import data, XML or CSV etc, after first exporting from the originating CMS via whatever method. see: https://drupal.org/project/feeds tutorials: https://drupal.org/node/622698 and http://developmentseed.org/blog/2009/dec/15/importing-and-aggregating-stuff-feeds/ of course the content types and fields will need to all exist in the new Drupal 7 install.

However, if the CMS data is fairly complex, go with Migrate. https://drupal.org/project/migrate and the https://drupal.org/project/migrate\_extras can also be helpful for more flexibility.
> 3 votes

# Answer
If you can export your content to an xml,feeds is pretty easy to use.
> 1 votes

# Answer
The Migrate Module is what you want. The learning curve is a little steep but it'd handled whatever I could throw at it and I was able to get all my data into Profile2 fields as needed.
> 0 votes

---
Tags: database, nodes, importing-exporting
---


# Question
Title: Which is the equivalent of php drupal format_interval for javascript?
I want to use with JavaScript and `Drupal.t()` the equivalent of `format_interval()`.

With PHP I would use the following code.

```
print t("!date ago", array("!date" => format_interval(time() - $lastActivity, 1)));

```

What would the equivalent in JavaScript be?

# Answer
> 4 votes
Drupal doesn't implement a JS version of `format_interval()`; this is a rough (minimally tested) port:

```
Drupal.formatInterval = function(interval, granularity, langcode) {
  granularity = typeof granularity !== 'undefined' ? granularity : 2;
  langcode = typeof langcode !== 'undefined' ? langcode : null;

  var units = {
    '1 year|@count years': 31536000,
    '1 month|@count months': 2592000,
    '1 week|@count weeks': 604800,
    '1 day|@count days': 86400,
    '1 hour|@count hours': 3600,
    '1 min|@count min': 60,
    '1 sec|@count sec': 1
  },
  output = '';

  for (var key in units) {
    var keys = key.split('|');
    var value = units[key];
    if (interval >= value) {
      output += (output.length ? ' ' : '') + Drupal.formatPlural(Math.floor(interval / value), keys[0], keys[1], {}, { langcode: langcode });
      interval %= value;
      granularity--;
    }

    if (granularity == 0) {
      break;
    }
  }

  return output.length ? output : Drupal.t('0 sec', {}, { langcode: langcode });
}

```

Some random results using the above (they seem to match up to the PHP function as expected):

* 3643 =\> *1 hour 43 sec*
* 92900 =\> *1 day 1 hour*
* 2592000 =\> *1 month*
* 9331200 =\> *3 months 2 weeks*
* 297605232 =\> *9 years 5 months*

# Answer
> 2 votes
Clives implementation is doing well. However, Drupals javascript aggregator needs to parse all javascript files for translatable strings. As Clive uses dynamic values for Drupal.formatPlural this won't work here.

So here's another implementation with working translation:

```
Drupal.formatInterval = function(interval, granularity) {
  granularity = typeof granularity !== 'undefined' ? granularity : 2;
  output = '';

  while (granularity > 0) {
    var value = 0;
    if (interval >= 31536000) {
      value = 31536000;
      output += (output.length ? ' ' : '') + Drupal.formatPlural(Math.floor(interval / value), '1 year', '@count years');
    }
    else if (interval >= 2592000) {
      value = 2592000;
      output += (output.length ? ' ' : '') + Drupal.formatPlural(Math.floor(interval / value), '1 month', '@count months');
    }
    else if (interval >= 604800) {
      value = 604800;
      output += (output.length ? ' ' : '') + Drupal.formatPlural(Math.floor(interval / value), '1 week', '@count weeks');
    }
    else if (interval >= 86400) {
      value = 86400;
      output += (output.length ? ' ' : '') + Drupal.formatPlural(Math.floor(interval / value), '1 day', '@count days');
    }
    else if (interval >= 3600) {
      value = 3600;
      output += (output.length ? ' ' : '') + Drupal.formatPlural(Math.floor(interval / value), '1 hour', '@count hours');
    }
    else if (interval >= 60) {
      value = 60;
      output += (output.length ? ' ' : '') + Drupal.formatPlural(Math.floor(interval / value), '1 min', '@count min');
    }
    else if (interval >= 1) {
      value = 1;
      output += (output.length ? ' ' : '') + Drupal.formatPlural(Math.floor(interval / value), '1 sec', '@count sec');
    }

    interval %= value;
    granularity--;
  }

  return output.length ? output : Drupal.t('0 sec');
}

```

---
Tags: javascript
---


# Question
Title: Modelling one-to-many relationships with content types
So I'm trying to build a web app, and I've got it set up so far to have two content types, "Client" and "Client Contact".

Now the schema I've put together makes a one-to-many relationship between client and client contact, i.e clients can have one or more client contacts, and each client contact can be associated with only one client.

I'm trying to model this relationship through Drupal 7's content types, but I can't seem to find a way to do it. I thought it could be done through the 'existing fields' section of the 'manage fields' tab on the 'content types' page, but it doesn't seem to work.

Is there any way this can be done or do I need to download a separate module to get it to work?

# Answer
From my understanding of your question,I think you need to use Entity Reference
> 5 votes

---
Tags: nodes
---


# Question
Title: removing the 'title' field from custom content types
I've created a content type to manage people, but in addition to the 'first name' and 'last name' fields that I've created, there's a 'title' field that seems to be present because its a Node module element.

Is there any way to, say, auto-fill it with something and hide it so that users who add content don't have to worry about it? It seems so redundant to have them fill out 'title' in addition to first name and last name.

# Answer
> 2 votes
You are looking for Exclude Node Title module

> This module handles a very simple functionality, decide whatever to ***exclude a node title*** from full node page or node teasers. It provides a ***checkbox*** on node-edit pages for easier exclusion, or you can use the admin page to manually enter a list of node id's to exclude title.

Also provides the option to hide all titles of a certain Content type.

# Answer
> 2 votes
Looks like you need this automatic nodetitle. Please give a search in google before posting here.To prevent empty content title fields one can configure it to generate the title by a given pattern.

---
Tags: nodes
---


title: How to render HTML of entity?

text:
# Question
Title: How to render HTML of entity?
I have created my custom entities using Entity Construction Kit module.

Is it possible to render an HTML output of entity programatically? So I could display an entity for example in block?

I have found function entity\_view, but it returns only array, not whole HTML output.

For now, I am using Views to achieve this. I create a view that displays one instance, and I am using function view\_embed\_view to display HTML.

But is there any direct function, so I don't need to create a view?

# Answer
> 3 votes
If you've got it working with `entity_view`, you probably just need to use:

```
print render($entity);

```

where `$entity` is the render array returned from `entity_view`.

---
Tags: 7, entities, theming
---