# Question
Title: Forcing inline errors on checkout_form with Stripe Payments
First, thanks in advance for any insight.

I have successfully set up cartthrob to process payments with Stripe and I have one final UX hurdle to cross over: the checkout\_form doesn't seem to honor the **error\_handling="inline"** parameter.

For example: if I try to submit the form with an incomplete credit card number, instead of triggering the inline error, I get a JavaScript dialog, "The page at...says, Your card number is incorrect." As a test, I switched to another gateway in the Payment Gateway configuration panel, submitted the form again with an incomplete credit card number and, expectedly, CartThrob properly triggered the inline error.

Has anyone come across, or better yet, circumvented this behavior? I know that Stripe requires relies on JavaScript to process its credit cards, so I suspect this is tied to those requirements, but it seems as though one should still be able to handle the errors inline. The inability to is a major bummer for UX.

Cheers,

Chris

# Answer
You can override the default behavior by setting a custom error handler. Make sure this code comes after your `checkout_form`.

```
<script>
CartthrobTokenizer.setErrorHandler(function(errorMessage){
  //do what you want with the errorMessage. the default behavior is to alert() it
  //something like $("#alert-box").html(errorMessage).show();
});
</script>

```
> 2 votes

# Answer
It is indeed due to Stripe's JS. I don't currently have a workaround, but I'll be looking into it shortly as CartThrob.com & Mightybigrobot.com will both be switching to Stripe soon.
> 0 votes

---
Tags: cartthrob, error, stripe
---


# Question
Title: Solspace User (edit) allow member to change their own group?
I'm using Solspace User and `{exp:user:edit}`.

I notice there is a form field `<input type="text" name="group_id" value="{group_id}" />` but docs say its only visible to SA's.

Is there any way to make this visible to the logged in user so they have permission to change their own member group?

In `{exp:user:register}` new users have the option of picking their member group from your list of "allowed groups" yet they don't have the ability to edit that group later if they pick the wrong group.

This becomes more important when you also implement **Solspace Facebook Connect**, which allows passive registrations but all passive registrations must go to the same member group. Since passive registrations don't get the choice of choosing their member group on sign up, I need a way for them to edit the member group later.

Is this possible?

# Answer
> 0 votes
I can confirm that this does work if you include all possible allowed groups in the `allowed_groups` parameter and then use a form field with name `group_id` and value as the chosen group ID. Solspace please update your docs to eliminate where it says the group\_id form field is available to Super Admins only.

---
Tags: solspace, solspace-user, member-management, solspace-facebookconnect
---


# Question
Title: Update failure: "Webmaster name or email missing from Email Configuration settings."
In the process of updating a site from from EE v2.6.1 to EE 2.7.3, the update stops partway through with this error:

> Webmaster name or email missing from Email Configuration settings.

Has anyone else encountered this error? Does anyone have any advice on how to work around it?

# Answer
EllisLab Support helped me figure this one out, but just in case anyone else ever runs into this problem, here was the solution:

It was presumably a third-party add-on that was responsible for the error, and the add-on update process is the next-to-last step the update wizard runs before updating the EE version number in the config.php file.

I just needed to check that the EE 2.7.3 changes were reflected in the database, which meant checking that the following database fields were updated to a length of 75 characters.

* exp\_members.email field
* exp\_email\_cache.from\_email
* exp\_email\_console\_cache.recipient

These had, in fact, been updated correctly, so all I needed to do was update the version in the config file to "273," remove the "installer" directory from the server, and log into the control panel to update the add-ons.

Now everything works just fine. Many thanks to Robin Sowell at EllisLab Support for helping me sort this out!
> 0 votes

---
Tags: updating
---


# Question
Title: Is there a way to control entry sort order?
I am very familiar with the standard methods for sorting channel entries. However, I have a client that wants more control than the standard alpha ascending / descending or the by entry date.

Is there a way that users can drag entries to appear in a specific order or some other way to control the order in which they appear?

Thanks.

# Answer
> 7 votes
Low Reorder was created for this exact purpose.

# Answer
> 3 votes
If you are okay without the dragging, you can create a dropdown order field with numbers set up like 01,02,03 etc...

Then you can order the entries by that field.

```
{exp:channel:entries channel="news" limit="10" orderby="{name_of_field_HERE}"}

```

Not as elegant as dragging but another way to set things up if you are on a budget.

# Answer
> 0 votes
There's also Selected Items: http://brandnewbox.co.uk/products/details/selected\_items. Perhaps not as slick as Reorder, but free.

# Answer
> 0 votes
Can also be achieved with Playa.

EDIT/UPDATE: yes, my initial answer wasn't too detailed. Hadn't had any coffee then. So, here we go:

I have used Playa inside a Matrix fieldtpye on a CartThrob driven ecommerce site to give admins the power to sort products with Playa. On the homepage I set it up like this:

```
{/your_matrix_field}
     <div class="products">
          <h2>{cell_1}</h2>
          <ul class="noGrid">
              {cell_2}
              {stash:embed name="snippets:productdiv" process="start"}
              {/cell_2}
          </ul>
     </div>
     <div class="clear"></div>
{/your_matrix_field}

```

{cell\_2} is the Playa field. The superadmin can then pretty conveniently choose which products (or better which product categories) will be available in the Matrix/Playa fieldtype.

Admins will then be able to search for products, add them to the Matrix row, sort them in the added products column and as a added bonus they will be able to add multiple Matrix Rows with different heading, for example "Sale", "New" or whatever.

This is all working very nice and is really flexible. The site is online, if somebody is interested in seeing it live or needs more informations, feel free to express this wish. I just don't want to paste urls here as I don't know on how this would be recieved here and I think looking at the frontend of some site doesn't really helps that much neither.

Cheers, Marc

---
Tags: channel-entries
---


title: ExpressionEngine edit_date formatting

text:
# Question
Title: ExpressionEngine edit_date formatting
Is there a reason the edit\_date in exp\_channel\_titles isn't in Unix time format?

I need to display the last edit date of a section of a website so I'm doing a simple query

```
{exp:query sql="SELECT title, edit_date FROM exp_channel_titles
                 INNER JOIN exp_structure using(entry_id)
                 WHERE (exp_structure.channel_id ='4' OR parent_id ='13')
                 ORDER BY edit_date DESC LIMIT 1"}
       {edit_date format="%d%S %F %Y"}
{/exp:query}

```

However the edit date seems to be formatted in a non unix timestamp. Is there a specific reason for this?

/system/expressionengine/libraries/api/Api\_channel\_entries.php is set to

```
'edit_date' => $this->EE->localize->decode_date('%Y%m%d%H%i%s', $this->EE->localize->now, FALSE),

```

Should this be

```
'edit_date' => $this->EE->localize->decode_date('%U', $this->EE->localize->now, FALSE),

```

?

Using EE 2.5.5

**EDIT - reason for asking**

I ask because my outputs do not format correctly:

Eg; edit\_Date of 20130111181835

```
Last Updated - {edit_date format="%F %d, %Y"}

```

outputs -

> Last Updated - October 30, 639867

I've since tried priting the edit date of a normal post and it still it not formatted correctly. I will go check my settings...

# Answer
> 3 votes
ExpressionEngine gives `edit_date` special treatment inside the Channel Entries loop to account for the way it's saved, but inside a query it's just another 14-digit number. To get it to format properly in a query loop, the SELECT statement can be modified to offset the value from GMT and convert it to a Unix timestamp. Luckily, EE's `current_time` variable parses early enough to use it as the offset value.

```
SELECT UNIX_TIMESTAMP(CONVERT_TZ(edit_date,'+00:00','{current_time format="%P"}')) AS edit_date

```

# Answer
> 3 votes
I'm not certain if your question is answerable as is, at least from non-Ellis Lab developers. It inquires about a reason, rather than asking for guidance or a solution.

What I can say is the `edit_date` format has been in non-Unix time format from before ExpressionEngine 2.5.5. I checked three sites: one using 2.5.5, one using 2.5.3, and one using 1.7.2 all have the edit date stored the same way.

I can also say, this doesn't change the expected behavior of the `edit_date` variable as indicated by the ExpressionEngine User Guide

I tested with

```
{edit_date format="%F %d, %Y"}

```

and it returns

> November 29, 2012

So while I can't state the reason why they would store it in non-unix format, it does look like it was planned, since their date variables work appropriately for it.

---
Tags: edit-date, date-format
---


# Question
Title: User registration failing Snaptcha security test every time
I’m using EE 2.7.2 and Snaptcha 1.7

I’ve applied Snaptcha to my Solspace User registration form, however it is causing all form submissions to fail the security test.

My only thought is that maybe Snaptcha somehow doesn’t work if the form is loaded into a modal box via ajax? I have all my login and registration forms in modal boxes via ajax.

*** Edit - see comment below. I've tested without ajax or modal box and it still fails every time ***

Any thoughts on why is would continuously fail?

Here’s a sample of my generated source code after the registration form is pulled in:

```
 <article style="display: block; opacity: 1; visibility: visible; top: 70px;" class="reveal-modal ajax-container open" id="sign-up-2"><h3>Create an Account</h3><form class="edit invert validate-edit require-terms">

<div class="hiddenFields">
<input name="ACT" value="86" type="hidden">
<input name="RET" value="http://dev.weddingwise.co.nz/account/new" type="hidden">
<input name="params_id" value="JgBTwOKNvKPcwHZPUEnbWhKlP" type="hidden">
<input name="site_id" value="1" type="hidden">
</div>

  <fieldset>
   <ul class="form-row">
    <li>
     <label>Email Address</label>
     <input name="username" class="required email" title="Valid email required" type="text">
     <p class="expl">This will be your login username</p>
    </li>
    <li>
     <label>Your Name</label>
     <input name="screen_name" class="required" title="Required" type="text">
     <p class="expl">Displayed on your public profile</p>
    </li>
    <li>
     <label>Password</label>
     <input name="password" class="required" title="Required" type="password">
     <p class="expl"></p>
    </li>
    <li>
     <label>Repeat Password</label>
     <input name="password_confirm" class="required" title="Required" type="password">
     <p class="expl"></p>
    </li>
  </ul></fieldset>
  <footer>
   <p class="terms">By submitting this form I agree to the <a href="/terms" target="_blank">Terms & Privacy</a></p>
   <a class="btn submit" href="#">Sign Up</a>
   <a class="btn secondary close-reveal-modal" href="#">Cancel</a>
  </footer>
  <div class="snap" style="position: absolute !important; top: -10000px !important;"><input id="snap_AEHBdrbOW" name="snap_AEHBdrbOW" value="GDYgTIvztsTqb" type="text"></div>

 </form></article>

```

Here's source of registration page when displayed inline on its own page with no ajax or modal box:

```
<!doctype html>
<!--[if lt IE 9]> <html class="ie" lang="en"> <![endif]-->
<!--[if gte IE 9]><!--> <html lang="en"> <!--<![endif]-->
<head>
    <title>Sign Up: step 2</title>
    <meta name="description" content="">
    <!-- meta -->
<meta charset="utf-8">
<meta http-equiv="cleartype" content="on">
<!-- css -->
<link rel="shortcut icon" href="/favicon.ico">
<link rel="stylesheet" href="/css/style.css">
<!-- js -->
<script src="/js/modernizr-2.6.2.min.js"></script>
<script src="/js/detectizr.min.js"></script>
<!-- iOS -->
<meta name="viewport" content="width=device-width" />
<link rel="apple-touch-icon-precomposed" href="/app-icon.png"/>
</head>
<body>

    <article class="modal" id="sign-up-2">
    <h3>Create an Account</h3>
    <form class="edit invert validate-edit require-terms">
    <form name="register" class="edit invert validate-edit" id="member_form" method="post" action="http://dev.weddingwise.co.nz/"  >
<div class='hiddenFields'>
<input type="hidden" name="ACT" value="86" />
<input type="hidden" name="RET" value="http://dev.weddingwise.co.nz/account/new" />
<input type="hidden" name="params_id" value="hDwJbIxhVaWjeacFTvDriXRXE" />
<input type="hidden" name="site_id" value="1" />
</div>

        <fieldset>
            <ul class="form-row">
                <li>
                    <label>Email Address</label>
                    <input type="text" name="username" class="required email" title="Valid email required" />
                    <p class="expl">This will be your login username</p>
                </li>
                <li>
                    <label>Your Name</label>
                    <input type="text" name="screen_name" class="required" title="Required" />
                    <p class="expl">Displayed on your public profile</p>
                </li>
                <li>
                    <label>Password</label>
                    <input type="password" name="password" class="required" title="Required" />
                    <p class="expl"></p>
                </li>
                <li>
                    <label>Repeat Password</label>
                    <input type="password" name="password_confirm" class="required" title="Required" />
                    <p class="expl"></p>
                </li>
        </fieldset>
        <footer>
            <p class="terms">By submitting this form I agree to the <a href="/terms" target="_blank">Terms & Privacy</a></p>
            <a class="btn submit" href="#">Sign Up</a>
            <a class="btn secondary close-reveal-modal" href="#">Cancel</a>
        </footer>
        <div class="snap" style="position: absolute !important; top: -10000px !important;"><input type="text" id="snap_eSHSeRWPh" name="snap_eSHSeRWPh" value="UkdZCBwrGTtQq" /></div>
<script type="text/javascript">document.getElementById("snap_eSHSeRWPh").value = "iRewkBhZSaFgs";</script>

    </form>
    </article>

<!-- js -->
<script src="/js/jquery-1.10.2.min.js"></script>
<script src="/js/jquery.easing.1.3.js"></script>
<script src="/js/jquery.autosize.min.js"></script>
<script src="/js/jquery.maxlength.min.js"></script>
<script src="/js/jquery.equalheightcolumns.js"></script>
<script src="/js/jquery.scrollTo-1.4.3.1-min.js"></script>
<script src="/js/jquery.localscroll-1.2.7-min.js"></script>
<script src="/js/jquery.serialScroll-1.2.2-min.js"></script>
<script src="/js/ui/jquery.ui.core.js"></script>
<script src="/js/ui/jquery.ui.widget.js"></script>
<script src="/js/ui/jquery.ui.mouse.js"></script>
<script src="/js/ui/jquery.ui.sortable.js"></script>
<script src="/js/ui/jquery.ui.datepicker.js"></script>
<script src="/js/jquery.selectBoxIt.js"></script>
<script src="/js/jquery.icheck.min.js"></script>
<script src="/js/jquery.isotope.min.js"></script>
<script src="/js/jquery.stickem.js"></script>
<script src="/js/jquery.validate.min.js"></script>
<script src="/js/spin.min.js"></script>
<script src="/js/jquery.spin.js"></script>
<script src="/js/foundation.js"></script>
<script src="/js/foundation.reveal.js"></script>
<script src="/js/jquery.fitvids.js"></script>
<script src="/js/jquery.infinitescroll.js"></script>
<script src="/js/imagesloaded.min.js"></script>
<script src="/js/init.js"></script>
<script src="/js/lookbook.js"></script>
</body>
</html>

```

Here's actual template code for registration page:

```
<!doctype html>
{embed-ie}
<head>
    <title>Sign Up: step 2</title>
    <meta name="description" content="">
    {embed-head}
</head>
<body>

    <article class="modal" id="sign-up-2">
    <h3>Create an Account</h3>
    <form class="edit invert validate-edit require-terms">
    {exp:user:register
            form:class="edit invert validate-edit"
            form:name="register"
            return="/profile/new"
            admin_register="yes"
            group_id="{segment_3}"
            allowed_groups="5|8"
            required="screen_name"
        }
        <fieldset>
            <ul class="form-row">
                <li>
                    <label>Email Address</label>
                    <input type="text" name="username" class="required email" title="Valid email required" />
                    <p class="expl">This will be your login username</p>
                </li>
                <li>
                    <label>Your Name</label>
                    <input type="text" name="screen_name" class="required" title="Required" />
                    <p class="expl">Displayed on your public profile</p>
                </li>
                <li>
                    <label>Password</label>
                    <input type="password" name="password" class="required" title="Required" />
                    <p class="expl"></p>
                </li>
                <li>
                    <label>Repeat Password</label>
                    <input type="password" name="password_confirm" class="required" title="Required" />
                    <p class="expl"></p>
                </li>
        </fieldset>
        <footer>
            <p class="terms">By submitting this form I agree to the <a href="/terms" target="_blank">Terms & Privacy</a></p>
            <a class="btn submit" href="#">Sign Up</a>
            <a class="btn secondary close-reveal-modal" href="#">Cancel</a>
        </footer>
        {exp:snaptcha:field}
    {/exp:user:register}
    </article>

    {embed-foot}

</body>
</html>

```

# Answer
> 1 votes
in your template code you have an opening form tag before your user tag:

```
<form class="edit invert validate-edit require-terms">
{exp:user:register

```

and therefore your output looks like this:

```
<form class="edit invert validate-edit require-terms">
<form name="register" class="edit invert validate-edit" id="member_form" method="post" action="http://dev.weddingwise.co.nz/"  >

```

which is obviously not what you want. remove the first form tag (the hard-coded one) and this should fix the Snaptcha issue.

Snatcha can work with ajax however your modal registration form seems to be missing the JavaScript code that Snaptcha automatically adds so the input field is not being modified with the correct value.

---
Tags: solspace, solspace-user, captcha
---


# Question
Title: how to handle responsive content loading?
I have a few questions regarding loading different content depending on the screen size and or device...

a site I'm working on has one column with 5 entries, when the screen size gets reduced a bit I want to change that to 2 columns with 6 entries so I don't have an empty space in the last row. Now I can always easily just load 6 entries and hide the last one with css on widescreen but I would rather try to do it beforehand

I've downloaded the ress plugin to have some type of variable I can use but it seems kinda silly to me to wrap 2 channel entries tags inside if statements when the only difference between them is the limit="5" and limit="6" parameter.

I'm also in the EU so I'm a bit worried about having to use a cookie for this, and also it's a pain to test this because I have to delete it every time to check how the site looks on a different screen size

I have a similar issue with loading images, I'm using the foundation framework and while it does have a nice solution with data-attributes to load different images for different sizes I am wondering if it's a better idea to use something like ress and just place all my images inside if statements. Not sure which is better performance wise?

# Answer
> 0 votes
In this particular case if you used 2 channel entry calls within if statements you will have lower performance than just calling all 6 entries and hiding one with css.

'if' statements have all their contents parsed and then the unnecessary ones are removed after. One way around this would be to use an early parsed conditional like the ifelse plugin or switchee. If you already have a solution in place for images I wouldn't bother using ee to handle it. That seems redundant.

# Answer
> 0 votes
The reds plugin wouldn't be dependent on javascript, to it certainly has that going for it. And if your conditional is early passed with an add-on like switchee or ifelse, then I would suspect it would offer some pretty great performance.

With regard to your first question about the entries - you're right - you're probably best to load with a limit of 6 and then simply use a ress conditional to remove the last entry for large screens. And to minimize the markup required to handle it, you could take a look at using the block-grid rather than the regular grid so you cane have large-block-grid-5 small-block-grid-2 as your ul class (and then remove the last-child li with a ress conditional aimed as large screens). Worth a try anyway.

---
Tags: performance
---


# Question
Title: GWcode Categories pulling only 2 categories within 12
Based on one of GWCode Categories examples I have created code below

```
<li class="submenu-parent">
<a href="#">Product Type</a>
<div class="submenu cf" id="submenu-1">
    {exp:gwcode_categories channel="products" style="linear"}
        {if depth1_start}<h3>{cat_name}</h3>{/if}
    {/exp:gwcode_categories}
</div>
</li>

```

but it pulls only 2 first parent (root) categories from 12 categories assigned to the products channel.

Any clue?

# Answer
Not quite sure from the comments above if all your 'parents' are on 1 level or not but perhaps this will help

```
<li class="submenu-parent">
<a href="#">Product Type</a>
<div class="submenu cf" id="submenu-1">
    {exp:gwcode_categories channel="products" style="linear" depth="1"}
        <h3>{cat_name}</h3>
    {/exp:gwcode_categories}
</div>
</li>

```

This will list all categories from the top level only. It seems like your just trying to make a bunch of h3's with the parent categories in them. If this is not what you are trying to do maybe try listing out your categories on here like

category 1
category 1.1
category 1.2
category 2
category 2.1
category 2.2
category 2.2.1
category 2.2.2

and then explain more specifically what it is you would like to do while referencing the category numbers.
> 1 votes

---
Tags: extension, categories, gwcode-categories
---


# Question
Title: EE Language files, best practice for maintaining changes?
I'd like to make some of EE's built-in error messages more helpful to one site's users. And I know I can change these messages in EE system language files like `system/expressionengine/language/english/myaccount_lang.php`.

But since these files are part of the EE system (*not* 3rd party), what's the best way to maintain these changes so that they don't get overridden on EE updates, etc.?

---

For some context, these particular users are having some trouble understanding how to respond to error messages like `The email you chose is not available` (an error that appears on registration). And, we're looking at a lot of things on the site other than EE system messages to prevent confusion / help site users.

But, as one small part of the overall strategy, we'd like to change some of these EE error messages.

Have you done this on any of your sites? How did you maintain these changes over time?

Or, if you have an alternative approach in EE (template-based? add-on-based?) that allows you bypass or override the EE system language files, I'd be interested in hearing about that too.

# Answer
There's always the Custom System Messages addon - http://devot-ee.com/add-ons/custom-system-messages \- which allows you to run things like error messages through regular templates. That way EE upgrades don't affect the message text.
> 1 votes

---
Tags: bestpractice, language, error-pages
---


title: Matrix < > Playa check for empty cells

text:
# Question
Title: Matrix < > Playa check for empty cells
I am having a Matrix fieldtype with two cells: text and Playa. The text field serves as the title for different rows. It's setup like this in my code:

```
{my_matrix_field}
    <div class="products">

        <h2>{cell_1}</h2>

        <ul class="noGrid">
            {cell_2}{stash:embed name="snippets:productdiv" process="start"}{/cell_2}
        </ul>

    </div>
{/my_matrix_field}

```

I would now conditionally show or hide {cell\_1} based on the results of cell\_2. If for example all entries are set to closed I want the cell\_1 to not display anymore.

I have tried the syntax from this post, but without any luck.

# Answer
Well, it's not super-simple. At least the solution that I came up with. It also might end up costing performance a bit.

So, first thing first: We need to see if some entries are selected, that are not closed. To do that, we could use {cell\_2 var\_prefix="playa" status="not closed"}{playa:entry\_id}{/cell\_2}. Now, you can try using that in an if statement such as:

{if '{cell\_2 var\_prefix="playa" status="not closed"}{playa:entry\_id}{/cell\_2}'} {cell\_1} {/if}
> 1 votes

# Answer
You could try

```
{if cell_2}<h1>{cell_1}</h1>{/if}

```

This simple conditional checks for the presence of info in cell\_2 and outputs the h1 if populated otherwise it will output nothing.
> 1 votes

---
Tags: matrix, playa
---


# Question
Title: If I move an entry to a different channel, will my associated Solspace Ratings move with it?
If I move an entry from one channel to another, will there be any problems with the Solspace Ratings attached to that entry moving along with it?

# Answer
I don't believe so, no. Rating stores its data in its own database table, indexed to each entry via `entry_id` only, so the channel that entry lives in should not matter.
> 3 votes

---
Tags: solspace, solspace-rating
---


# Question
Title: gwcode_catmenu - {cat_image} and image sizes/manipulations
We've got some categories being output using gwcode catmenu (http://gwcode.com/add-ons/gwcode-catmenu/documentation) but can't seem to find a way of outputting a certain image size (based on image manipulations setup in the file upload preferences),

The code is as follows:

```
 {exp:gwcode_catmenu cat_url_title="{segment_2}" active_branch_only="yes" depth="1" style="linear"}
    <li>
      <span class="product-text"><h2>{cat_name}</h2></span>
      <span class="product-image"><img src="{cat_image}" alt="{cat_name}" /></span>
    </li>
 {/exp:gwcode_catmenu}

```

This works, but outputs the original image size, we want to do something like:

```
 {exp:gwcode_catmenu cat_url_title="{segment_2}" active_branch_only="yes" depth="1" style="linear"}
    <li>
      <span class="product-text"><h2>{cat_name}</h2></span>
      <span class="product-image"><img src="{cat_image:small}" alt="{cat_name}" /></span>
    </li>
 {/exp:gwcode_catmenu}

```

To output the small version of the image, any ideas?

# Answer
> 1 votes
It doesn't look like GWcode CatMenu currently supports calling alternate versions of category images, but you could do this in a really quick plugin pretty easily. Your key function would look something like this:

```
function get_size()
{
    $image = ee()->TMPL->fetch_param('image');
    $size = ee()->TMPL->fetch_param('size');
    $pos = strrpos($image, '/');
    if($pos !== false)
    {
        $image = substr_replace($image, '/_'.$size.'/', $pos, 1);
    }
    return $image;
}

```

So your plugin in the template might look like:

```
{exp:my_plugin:get_size image="{cat_image}" size="{small}"}

```

---
Tags: categories, gwcode-categories
---


title: Session ID of user not logged in

text:
# Question
Title: Session ID of user not logged in
I need to record some data in the database for a user in the session (a custom add-on) and I'd been using the value returned from PHP's session\_id() method, which works well enough.

When the user logs in, I then need to update the data with the logged in member's ID.

However I'm finding that when the user logs in, that session\_id() is empty so I lose the link to what was in session for that user prior to login.

I had originally tried using $EE-\>session-\>userdata('session\_id') but that was zero, which is why I ended up using the native session\_id() method.

Does anybody have any suggestions for the best way of achieving this?

Thanks.

# Answer
I ended up doing this in my module's constructor method:

```
if (! isset($_SESSION))
{
    session_start();
}

$this->EE->input->set_cookie(array(
    'name'   => 'exp_tp_session_id',
    'value'  => session_id(),
    'expire' => 60*60*24 // 24 hrs
));

```

And then when a user logs in, I retrieve that cookie value and then use EE's session.

Seems odd that I'd have to do this but it works. Perhaps I'm misunderstanding something...
> 0 votes

# Answer
What about setting a cookie with a random string as the identifier? Will be much more reliable I think.

Just create the string once, then set the cookie and insert your visitor into your database at the same time.

```
if( ! $cookie = ee()->input->cookie('guest_id') )
{
    ee()->load->helper('string');
    $id = random_string('unique');
    ee()->functions->set_cookie('guest_id', $id);
    // Do your database stuff here.
}

```
> 1 votes

---
Tags: login, sessions
---


# Question
Title: How can a member edit an entry via a Channel Form but save as a copy?
I'm searching for a solution how a member can edit an entry on frontend, but it should not change the entry on submit, but instead it should create a new entry in the database?

# Answer
> 1 votes
One option is to set up your channel form tags as if you're creating a new entry. Then use an embedded template to output the fields for your form using channel entries tags for whichever entry you're using as the form starting point.

So it works like you're creating a new entry, but have pre-filled the form from an existing entry. Like:

```
{exp:channel:form .... }

    {embed="some_template_group/some_template" use_entry_id="{segment_4}"

    <button id="form_submit" type="submit">Submit</button>
{/exp:channel:form}

```

and then on the embedded template:

```
{exp:channel:entries
    entry_id="{embed:use_entry_id}"
.... }

    <input type="text" name="title" id="title" value="{title}">
    etc....
{/exp:channel:entries}

```

---
Tags: ee2, channel-form
---


title: Zoo Visitor and Cartthrob

text:
# Question
Title: Zoo Visitor and Cartthrob
I'm building a member/ecommerce site with CartThrob and Zoo Visitor.

I have a multi-page checkout.
From looking around for solutions on how to do this, people have said to use the Zoo Visitor update profile tags on the shipping/billing pages, and use hidden ZV fields inside the Cartthrob checkout tag on the payment page.

This works fine except for a few cases:

* If you want guests to checkout, this approach won't work.
* Calculating tax and/or shipping won't work until submitting the final checkout form.

I've solved the first issue by conditionally showing a CT save\_member\_info form if they are logged out and a ZV profile form if they are logged in.

I can probably save the address to session by posting to CT's save\_member\_info using AJAX when submitting a ZV form, but that feels clunky.

Cartthrob usually calculates tax/shipping by the member data in the session. It doesn't get saved to session when using ZV forms.

Is it possible to map the ZV fields to the CT session data when saving the ZV profile form? I'm sure you need to use an extension but that's beyond me. Does anything like this already exist?

Thanks

# Answer
Justin Kimbrell of Objective HTML helped with an extension that would sync the ZV member data to the session whenever the profile was updated.

Perfect.
> 1 votes

# Answer
Dealing with a similar situation here where I'm forced to use ZV and finding it difficult to integrate with CT. Is that ZV sync extension available somewhere?
> 0 votes

---
Tags: cartthrob, extension, zoo-visitor
---


title: Template group urls

text:
# Question
Title: Template group urls
I have a template group called 'site. These are my top level generic templates, I would like to exclude the site part of the url so,

```
http://mysite/site/aboutus

```

I would like to remove the 'site' part of the url for this group only.

Any 3rd part or core EE way to achieve this.

Thanks,

# Answer
Pretty sure if you set the group to default / homepage in the cp it won't require the URL - the index page within that group will be your sites homepage.
> 1 votes

# Answer
You can achieve this for all templates located within your site's *default* template group by disabling Strict URLs. But this will only work with your default template group, no others.

Note that you should put some logic in each of these templates instructing EE to display a 404 page when accessed *with* the template group - otherwise you could run into duplicate content issues, as your content will be accessible via both `/site/about` *and* `/about`.

e.g.,

```
{if segment_1 == 'site'}{redirect="404"}{/if}

```
> 1 votes

# Answer
Unless there are other reasons for putting these templates into the /site/ group I'd recommend just creating an /aboutus/ template group and putting the code into the index template.

You'd get the URLs you want without hassle/logic and just have a few more template groups in the system.
> 1 votes

---
Tags: templates, url, groups
---


# Question
Title: Cartthrob clear_cart input not working on update_cart_form
As the title says - cart just reloads:

```
{exp:cartthrob:update_cart_form
    class="validate"
    id="form-basket"
    return="shop/basket"
    secure_action="yes"
    }

    basket code here

    <button type="submit" name="clear_cart">Empty Basket</button>

{/exp:cartthrob:update_cart_form}

```

Any idea why this might be the case?

EE is 2.7.2, CT is Pro 2.4.

Thanks

# Answer
try using an input instead of a button

```
<input type="submit" name="clear_cart" value="Empty Basket">

```
> 0 votes

---
Tags: cartthrob
---


title: Need help removing Pages URI

text:
# Question
Title: Need help removing Pages URI
I'm using the Pages module. In one entry, I created a Pages URI just to test something. Now I want to remove the URI for that entry, but I can't. It seems to be forcing me to populate the Pages URI field, but I want it blank, like it was when I initially created the entry.

Any ideas?

# Answer
> 1 votes
That sounds odd - but you can remove the page via **Add-on → Modules → Pages**.

---
Tags: pages, page-uri
---


# Question
Title: SagePay Direct: Error: Sorry, there was an unexpected error communicating with the payment gateway
We're getting a communication error response when submitting card details using the SagePay Direct payment method:

> Error: Sorry, there was an unexpected error communicating with the payment gateway.

Nothing has changed in respects to the server / EE code and transactions have been working fine since upgrading to 2.10 recently. Logging into SagePay shows that since today transactions aren't even being logged as failed at sagepay; ie they're failing before they even reach sagepay.

I took the measure of upgrading to Store: 2.20 and the error persists.

Any pointers?

After uncommenting the exception, the error displayed is:

> Fatal error: Uncaught exception 'Guzzle\Http\Exception\CurlException' with message '\[curl\] 6: Couldn't resolve host 'live.sagepay.com' \[url\] https://live.sagepay.com/gateway/service/vspdirect-register.vsp' in /var/www/vhosts/domain.com/httpdocs/system/expressionengine/third\_party/store/vendor/guzzle/http/Guzzle/Http/Curl/CurlMulti.php:338 Stack trace: #0 /var/www/vhosts/domain.com/httpdocs/system/expressionengine/third\_party/store/vendor/guzzle/http/Guzzle/Http/Curl/CurlMulti.php(279): Guzzle\Http\Curl\CurlMulti-\>isCurlException(Object(Guzzle\Http\Message\EntityEnclosingRequest), Object(Guzzle\Http\Curl\CurlHandle), Array) #1 /var/www/vhosts/domain.com/httpdocs/system/expressionengine/third\_party/store/vendor/guzzle/http/Guzzle/Http/Curl/CurlMulti.php(244): Guzzle\Http\Curl\CurlMulti-\>processResponse(Object(Guzzle\Http\Message\EntityEnclosingRequest), Object(Guzzle\Http\Curl\CurlHandle), Array) #2 /var/www/vhosts/domain.com/httpdocs/system/exp in /var/www/vhosts/domain.com/httpdocs/system/expressionengine/third\_party/store/vendor/guzzle/http/Guzzle/Http/Curl/CurlMulti.php on line 338

So looks like the server can't communicated with sagepay... so, I've done a quick test and it seems cURL is up the swanny on the server. Thanks for your help as always!

# Answer
> 2 votes
> Sorry, there was an unexpected error communicating with the payment gateway.

This generally means that there was a communication problem talking to the gateway (i.e. your server is blocking the request, or the authentication details are incorrect). We're working on better logging for these errors, but in the meantime the full error isn't displayed because it could pose a security risk to your site (or reveal your gateway authentication details).

To diagnose it, open `third_party/store/src/Store/Service/PaymentsService.php` and around line 328, you will see this code

```
} catch (\Exception $e) {
    $transaction->status = Transaction::FAILED;
    $transaction->message = lang('store.payment.communication_error');
    $transaction->save();
}

```

If you comment out those 4 lines, you should see the underlying exception displayed, which may make it clear what is going wrong. Can you either update your original question with the exception details, or send us an email so we can add a check for this in future?

---
Tags: expresso-store, sagepay
---


# Question
Title: Free Shipping with the Australia Post Shipping Extension
I'm using Expresso Store with the "Australia Post Shipping" extension.

Currently I'm attempting to order a single item with "Free Shipping" set, but it seems the Australia post extension is applying a shipping cost of $9.95 to the order.

I was wondering if the calculator ignores "Free shipping" items when calculating a shipping total, or if I'm doing something wrong?

If the extension ignores the "Free shipping" attribute, is it possible to check if the order consists of free shipping items, and render a different set of {shipping\_options} in the checkout tag?

# Answer
> 0 votes
This is a known issue, and we have a fix for it coming out very soon.

In the meantime, if you would like to test the update please email support@exp-resso.com and we will get you a copy.

UPDATE: This has been fixed in version 1.0.2 of the Australia Post extension.

https://exp-resso.com/docs/shipping\_aus\_post.html

---
Tags: expresso-store, shipping
---


title: Freeform Pro and Session Variables

text:
# Question
Title: Freeform Pro and Session Variables
My client has a "resource" blog with articles and PDFs that are available for download.

They would like for their users to enter in an email address before being allowed to download the PDFs (I know). The form would save the entry into the database and email an admin the information for a possible follow-up (I know..). They would also like for the user's data to be saved for that session so they don't have to fill out the form over-and-over if they choose to download other articles. They do not want the user to have to login or register.

I have this working outside of ExpressionEngine2 and Freeform, using $\_SESSION variables to check if the form was submitted and saving the $\_POST data into the $\_SESSION array for auto-populating the form fields on subsequent article pages. The user just has to hit Submit again on the form, which is fine.

However, when implementing in EE 2.7.3 using FreeForm Pro 4.1.3, using the default form action, the POST and SESSION arrays are empty after submission. If I substitute the Freeform form:action it works as expected, but of course the form results aren't stored in the database or emailed to the admin.

They love the Freeform interface and ability to see and export previous entries. Also, I need to do the form submission check server-side, so a user can't just view the source and download the PDF without filling out the form.

Is there another way to accomplish this? I am a hook novice. Any help or insight is most appreciated.

Here's my current code on the blog listing template:

```
<?php session_start(); ?>
<!DOCTYPE html>
<head>
...
<body>
...
{exp:channel:entries channel="blog"}
        <h1>{title}</h1>

        <?php // SET VAR FOR FORM SUBMIT
            $submit = ee()->input->get_post('submit', TRUE); ?>

        <?php // IF FORM NOT FILLED OUT
            if ( empty($submit) ) { ?>

            <a class="download-prompt" title="Download Attachment" href="#"><strong>Download Attachment:</strong> {exp:channel:entries channel="blog"}{title}{/exp:channel:entries}</a>

            <!-- Hidden Contact Form - Shown on '.download-prompt' Click -->
            <div class="contact-form">
                {exp:freeform:form
                    form_id="16"
                    required="email"
                }
                <div class="line">
                    <label>Email <span class="required_item">*</span></label>
                    <input type="text" name="email" id="freeform_email" placeholder="Email" value="<?php if (!empty($_SESSION['email'])) { echo $_SESSION['email']; } ?>">
                </div>
                <div class="line">
                    <input type="submit" name="submit" value="Submit">
                </div>
                {/exp:freeform:form}
            </div><!-- /.contact-form -->

        <?php // ELSE IF FORM IS FILLED OUT
        } else if ( !empty($submit) ) { ?>

            <?php // Save each POST value in SESSION
            foreach ( $_POST as $key => $value ) {
                ${$key} = $value;
                $_SESSION[$key] = $value;
            }
            ?>

            <p>Thank you message.</p>

            <!-- Hidden iFrame to Auto Download Attachment -->
            <script type="text/javascript">
            $(document).ready(function() {
                $('<iframe src="/resources/download.php?file_source={blog_attachment}"></iframe>').appendTo('body').hide();
            });
            </script>

        <?php // ELSE SOMETHING BROKE
        } else { ?>
            <h3>Something went wrong. Please try again.</h3>
            <p><a href="{page_url}">Try again.</a></p>
        <?php } ?>

        {/exp:channel:entries}

```

# Answer
> 0 votes
Based on the direction from @stuartmcd69 here's what I came up with...

First, I had to split this out into two templates and add the Stash module (which is awesome) and the Freebie module (because I'm also using Structure for page management).

The Stash variables take place of the $\_SESSION variables from my first attempt. Freebie allows me to ignore anything after '/download' in the URL so Freeform can use the %%entry\_id%% and channel:entries can grab the correct attachment based on {url\_title}.

*If you have difficulty retrieving the Freeform Entries, make sure you check the status... that took me a bit to figure out from the docs (e.g. status="pending|open").*

**Blog Listing Template:**

```
{exp:freeform:form
    form_id="16"
    required="first_name|email"
    return="/{segment_1}/download/{segment_2}/%%entry_id%%"
}
<div class="line">
    <label>First Name <span class="required_item">*</span></label>
    <input type="text" name="first_name" id="freeform_first_name" placeholder="First Name" value="{exp:stash:get name='first_name'}">
</div>
<div class="line">
    <label>Email <span class="required_item">*</span></label>
    <input type="text" name="email" id="freeform_email" value="{exp:stash:get name='email'}">
</div>
<div class="line">
    <input type="submit" name="submit" value="Submit">
</div>
{/exp:freeform:form}

```

**Download Template:**

```
<!-- Save Entry to Stash Vars -->
{exp:freeform:entries
    form_id="16"
    dynamic="no"
    status="pending|open"
    entry_id="{freebie_4}" limit="1"
}
    {exp:stash:set
        type="variable"
        dynamic="yes"
        save="yes"
        match="#^[a-zA-Z0-9\@\.,\s\-]+$#"
        scope="user"
    }
        {stash:first_name}{freeform:field:first_name}{/stash:first_name}
        {stash:email}{freeform:field:email}{/stash:email}
    {/exp:stash:set}

    {if freeform:no_results}
        <p>There was an error. Please try again.</p>
    {/if}
{/exp:freeform:entries}

<!-- Hidden iFrame to Auto Download Attachment -->
{exp:channel:entries channel="blog" dynamic="no" url_title="{freebie_3}" limit="1"}
<script type="text/javascript">
    $(document).ready(function() {
        $('<iframe src="/resources/download.php?file_source={blog_attachment}"></iframe>').appendTo('body').hide();
    });
</script>
{/exp:channel:entries}

```

# Answer
> 1 votes
I seem to recall freeform processes the form before returning you to the return page, loosing post data. You can specify %%entry\_id%% in the return param and use that to do a look up of the entry and set a cookie or some such.

I've done something similar but used stash to store session vars. Its not perfect but achieves a similar outcome.

# Answer
> 0 votes
Have you considered Protected Links? (I haven't tried it myself so can't speak to its quality, but it appears to do what you're aiming for).

---
Tags: solspace-freeform, sessions
---


# Question
Title: Newby question: caching, is Page module enough, and can Stash cach template without setting up htaccess file?
I am working on a site that has potential to attract a lot of traffic, says my client. I am reading here and there how to build efficient, for speed. One of the things I am looking at is the use of Stash for caching pages with static content. (I did use Stash for something else in another project)

My questions. 1) Is the pages module enough for this? 2) Is a htaccess file needed for page caching with Stash? The documentation makes me a bit unsure.

Thanks.

# Answer
> 0 votes
Mod\_rewrite rules for caching are only needed if you're using the static cache method.

Static caching works by writing the HTML output of an EE template to a static file; when the browser requests a URL, mod\_rewrite in .htaccess will check to see if that static file exists, if it does, it will serve the HTML from the static file, and, EE won't even be aware the request took place.

If the static HTML file doesn't exist, EE will handle the request as usual (with the Pages module), and, if static caching is enabled for the page, write the output of the page load to the static cache, so the next user who requests that page will get content from the file, instead of from EE, if that makes sense.

---
Tags: stash, pages, speed
---


title: Migration from File Manager to Assets

text:
# Question
Title: Migration from File Manager to Assets
I am working on a fully-developed site that is currently live, with hundreds, perhaps thousands of images and files in preset folders using File Manager in EE.

As a pre-purchase question, I guess... I would like to migrate the files & images to Assets, and was wondering if it was as easy as changing the channel fields from a File field to an Asset field?

Any help would be appreciated, thank you.

# Answer
I was doing just this last week on a few thousand entries. Assets works really well at converting.

First make sure Assets is synchronised with your upload paths. Assets creates a reference to all the files in `exp_assets_files`.

EE File fieldtype stores it's data in the format `{filedir_x}your-file.ext`, where x is the reference to upload paths config.

When changing an existing fieldtype from File to Assets, Assets matches the file name against it's stored reference in `exp_assets_files` and create the appropriate rows in `exp_assets_selections`.

I did have some issues with files starting with underscore. I've yet to work out if this is a real issue or specific to my install.
> 1 votes

# Answer
Yes, it is that easy, I've done this many times. In some earlier versions of Assets I had some issues doing this on a couple of sites, but later versions smoothed out the bumps.

As always, do this on a dev copy of the site first - or at the veery least, take a full DB backup first.
> 2 votes

---
Tags: assets, file-manager, files, migration
---


title: Query optimization and database indexes

text:
# Question
Title: Query optimization and database indexes
I noticed that there a handful of queries that ExpressionEngine runs that don't use any database indexes. An example is the query `SELECT DISTINCT ee.* FROM exp_extensions ee WHERE enabled = 'y' ORDER BY hook, priority ASC, class` which gets run on every page. Doing a MySQL `EXPLAIN` on this shows that it could benefit from a database index. However, since the number of extensions installed is usually fairly small, adding an index for this query might not be a huge win.

I realize that the official stance is to not add indexes because it could conflict with future updates. On the other hand, from a practical standpoint, I have to balance resource usage and page rendering speed against the official stance; also, I'm willing and able to removing indexes before upgrading to a newer version of ExpressionEngine.

Is there a set of queries that are prime candidates for database indexes that would reduce load on the MySQL server? Is there any best practice on this?

# Answer
I'm not aware of any established best practices for adding indexes to DB tables. I'd say the official EllisLab stance is you shouldn't have to add any because they've done this work for you where needed.

But every project has different needs and developers have to evaluate this on a case by case basis depending on the project. In my years with EE, I've only needed to add one index to a large database that was struggling with a specific query. I'm not well versed in this area so perhaps I've needed it more and just didn't know. If you're going to add indexes to any table it will probably be the exp\_channel\_data table.

My advice is unless you are having specific resource issues with your DB server or can identify a specific query that is struggling, there shouldn't be reason to add an index. EE runs fine with its default DB settings for more projects.

A quick solution if you are having specific issues is to implement the **CE Cache addon**. The speed increase when using the Static Driver is incredible... night and day difference in page load times... and it will immediately reduce any resource strain on the DB.
> 3 votes

# Answer
I haven't heard of any best practices around this. I think it depends on the user, you. If you're looking for some best practices to improve speed, you may want to start with:

Generally speaking, I've heard of developers adding indexing for queries that are frequently used, that can benefit from them. I'm not certain if they drop the indexing before upgrades.
> 8 votes

# Answer
Most of required indexes are already there.

What I usually do, is if I use custom sorting order with `exp:channel:entries` I add key on field that I sort by.

I.e. if I have `{exp:channel:entries orderby="title"}` I add index on `title` in `exp_channel_titles` table.

If I have `{exp:channel:entries orderby="my_custom_field"}` and `my_custom_field` is a custom field with ID `7` I add index on `field_id_7` in `exp_channel_data` table.
> 5 votes

# Answer
For custom field columns that will be used in join statements I find its best to set the column type to an `int` or a `varchar(#)` and then index it as suggested.

You can also optimise the way EE gets its data from the database.

When EE queries the database for a set of channel entries it brings back a lot of data that is often not needed.

This includes joining all columns from `exp_channel_data`, `exp_members`, `exp_member_data` and `exp_channels` for the related data.

Changing the way that EE generates its queries for the Channels module will yield some impressive results.

I had fun changing the channel entries query by adding a new extension hook to the `build_sql_query` method and adjusting the returned columns and table joins using tag parameters.

While working on a big site pulling lots of database content in from many `{exp:channel:entries}` tags I found it necessary to create an add-on to better manage the size of returned database results and keep the memory footprint smaller. Adding SQL comments via a tag parameter is a small bonus to make SQL debugging much easier when searching the MySQL logs.

If you're interested feel free to take a look: http://ee-garage.com/nsm-turbo-channels.

Please note that this version is rather experimental, hasn't been updated in a while and was never officially released.

Hopefully it will give you some ideas on how you can make EE's database functions run faster for you.
> 3 votes

# Answer
EE has a lot of indexes already, so it's fairly rare to run into a situation where you'd need another. However, I see no reason to avoid doing it if you see measurable performance gains in a custom query or something. You can always drop it later if something changes.

I got a very modest performance boost on my site by adding an index to the `file_name` column of `exp_files`. The file field tag pair can get a bit slow without that index if you have a huge number of files.

As far as your `exp_extensions` example goes, it's probably a bad candidate because there are only two options for `enabled` (y/n). It *might* be beneficial if you had thousands of rows and only a few were marked 'y', but as a general rule of thumb it's best to use indexes on columns with lots of unique values.
> 0 votes

---
Tags: database, query, optimization
---


# Question
Title: Using Stash to share data between templates
Is it possible to Stash some content in one template and then grab it from another template?

Basically, I want to store a bunch of Entry IDs in one template and then i'm AJAX loading another template where I would like to retrieve those Entry IDs and use them to plot markers on a map.

I've tried using scope, but it doesn't appear to be working.

```
{exp:stash:set name="show_nearby" parse_tags="yes" parse_depth="2" parse="inward" trim="yes" scope="user" refresh="10"}
    {exp:channel:entries dynamic="no" url_title="{segment_4}"}
        {exp:trails_nearby entry_id="{entry_id}" lat="{thingtodo_latitude}" lng="{thingtodo_longitude}"}
    {/exp:channel:entries}
{/exp:stash:set}

```

The following code gets the values above when used in the same template (so I know the values are being set;

```
{exp:stash:get name="show_nearby" backspace="1"}

```

However, when I use in another template it just returns everything from the channel because the entry\_id isn't being set;

```
{exp:channel:entries channel="things-to-do" entry_id="{exp:stash:get name='show_nearby' backspace='1' scope='user'}" parse="inward" status="open" dynamic="no"}
{title}
{/exp:channel:entries}

```

I would appreciate any advice.

Thank you.

# Answer
> 0 votes
Thanks Romans-8---31-39. That did the trick using scope site.

---
Tags: stash
---


title: Stash static caching URL issue

text:
# Question
Title: Stash static caching URL issue
I am using Stash static caching (and it is AWESOME). I'm using Stash 2.4.5, Mustash 1.0.9, and EE 2.7.2.

On my Mustash 'Static cache rewrite rules' page, in the example .htaccess code, it has the following lines:

```
# Check if cached index.html exists
RewriteCond /path/to/my/static_cache/1/$2/index.html (.*\.(.*))$
RewriteCond %1 -f

# Rewrite to the cached page
RewriteRule ^(index.php/*)*(.*)(/*) http://www.domain.com/static_cache/1/$2/index.%2 [L]

```

If I use that entire `.htaccess` file as is, I get weird URLs as I navigate throughout my site. The first time I visit a page (no static cache file exists yet), the URL is fine (like `http://www.domain.com/about`)... but the next time I visit it, I get a weird URL, like `http://www.domain.com/static_cache/1/about/index.html`.

Another weird thing, when I visit the home page `http://www.domain.com/`, if it's been cached, the url is `http://www.domain.com/static_cache/1//index.html`. (notice the //).

. . . HOWEVER, I found that if I remove the domain part from

```
RewriteRule ^(index.php/*)*(.*)(/*) http://www.domain.com/static_cache/1/$2/index.%2 [L]

```

to make it

```
RewriteRule ^(index.php/*)*(.*)(/*) /static_cache/1/$2/index.%2 [L]

```

then caching works and my URL's are fine...

Everything seems to be working (with the exception of the issue I noted in this question (Stash static caching not ignoring POSTs like I think it should).

But it does seem like it's indicative of some underlying issue in the way I've set things up. I assume things should work normally with the example .htaccess file provided from that Mustash page. Any ideas what I've done wrong?

# Answer
> 1 votes
The domain output in the rules generated by Mustash is defined by the `stash_static_url` config value. As you have discovered for many systems a webroot relative url should be used instead of an absolute one: https://github.com/croxton/Stash/wiki/Installing-%26-upgrading

The problem with POST requests is something I have also noticed with Low Search, which submits forms to the index page of the site. Please try the solution @Jay F posted.

---
Tags: stash, .htaccess
---


# Question
Title: CartThrob: Setting no tax on on-the-fly products
I understand the add to cart form can take a parameter to disable tax on a product like so.. (although the docs seem to indicate it should be 'tax\_exempt'?)

```
{exp:cartthrob:add_to_cart_form on_the_fly="y" no_tax="yes"}

```

I am using this to create phone orders but sometimes a product may not have tax so I was hoping to add a checkbox, something like this:

```
<input type="checkbox" name="no_tax" value="yes" />

```

Unfortunately this does not appear to work for me, just wondering if there are any undocumented features that will do what I want?

# Answer
> 0 votes
The `tax_exempt` parameter is renamed to `NTX` and then its value is encrypted by the CartThrob form tag before being added as a hidden input, so it's not quite so simple.

But a little bit of PHP can do this for you (or a you could write a simple plugin if you're averse to PHP in templates).

```
<input type="checkbox" name="NTX" value="<?php echo ee()->encrypt->encode('yes'); ?>" />

```

You may or may not need to load the Encryption library first:

```
ee()->load->library('encrypt');

```

---
Tags: cartthrob
---


# Question
Title: URL title field is blank on some entries! Help
I have a channel for users to add their own entry via a Safecracker form, it is a live site and there is now 800 odd entries – about 300 of these have slipped by without URL titles, which you can imagine is causing trouble...

**Blank URL title:**

In some instance, it seems that my URL titles have not came through – they are blank. Would this signal a lack on Javascript in the users browser? URL title field is hidden. It all works fine when I test it with Javascript enabled, could only recreate the problem with JS disabled, no URL title comes into the fields value.

My question on this is – how do I prevent this from happening within Safecracker? These users would not understand url title field, so want to keep it hidden – which means can't user validate it.

**Rebuilding the URLS using title**

I have seen a few solutions on here – but none work. SQL solution leaves in special characters. PHP solution throws up an error.

If I need to rebuild all the URL titles in a Channel, how do I go about it? (I am not good with PHP or MySQL – is there an existing solution I am missing)

I am stuck with about 300 blank URLs, which would be tedious to do manually.

Thanks in advance for your help!

# Answer
> 1 votes
You'll have to test this, but MX Title Control allows you to update all entries with a pattern. You could set the URL Title Pattern to `{title}` and try updating that way. As always, backup first before giving it a shot

---
Tags: safecracker, channel-form, url-title
---


# Question
Title: Order channel categories on the navigation
I am a novice with ExpressionEngine and still learning.

How can one order channel categories in an ascending or descending order ?

For example :

```
<!-- ABOUT US -->

<li><a href="/corporate">About Us</a>
    <!-- DROPDOWN NAV -->
    {exp:channel:categories channel="corporate" category_group="8" dynamic="no" style="nested" status="{published-status}" show_empty="no" id="nav_categories" class="dropdown"}
    {if category_id != "82"}
        {if category_id != "116"}
    <a href="{path='corporate/topic'}">{cap_category_name_catgrpid-8}</a>
    {/if}
    {/if}
    {if count == "{total_results}"}
        <a href="/get-involved/item/parachutes-sponsors">Our sponsors</a>
    {/if}
{/exp:channel:categories}
</li>

```

Any suggestion will be helpful

# Answer
> 2 votes
The native `exp:channel:categories` tag doesn't offer any type of sorting parameters. I suggest using GW Code Categories as it has a ton of useful options.

```
{exp:gwcode_categories
    channel="corporate"
    group_id="8"
    excl_cat_id="82|116"
    orderby="cat_name"
    sort="asc"
    style="nested"
    status="Open"
    show_empty="no"
    id="nav_categories"
    class="dropdown"
}
    ...
{/exp:gwcode_categories}

```

You can also disregard the category conditionals as I excluded them with the `excl_cat_id` parameter.

---
Tags: categories
---


# Question
Title: Stash static caching not ignoring POSTs like I think it should
I am using Stash static caching (and it is AWESOME). I'm using Stash 2.4.5 and EE 2.7.2. I am also using Low Search 3.0.4.

So I have the `{exp:stash:static}` tag on my homepage, which is great. But if it's there (or, I should say, if my static\_cache folder has a cached file for my homepage), my Low Search form doesn't work. When I submit a keyword search, it just loads the homepage.

The search works fine when I am logged in, presumably because I have Stash disabled for logged in users.

So, based on my .htaccess, I'd expect it to NOT load the homepage from the cache file because it's a POST.

Any idea what I'm doing wrong, or how to get this to work? I'd really like to keep my homepage static caching working.

In my .htaccess, I have

```
#################################################################################
# START MUSTASH STATIC CACHE RULES

# -------------------------------------------------------------------------------
# default_site
# -------------------------------------------------------------------------------

# Exclude image files
RewriteCond $1 !\.(gif|jpe?g|png|ico)$ [NC]

# We only want GET requests
RewriteCond %{REQUEST_METHOD} GET

# Exclude CSS/ACT EE URLs and 'preview'
RewriteCond %{QUERY_STRING} !^(css|ACT|URL|preview)

# Uncomment this if you want to disable static caching for logged-in users
RewriteCond %{HTTP_COOKIE} !exp_sessionid [NC]

# Remove index.php from conditions
RewriteCond $1 ^(index.php/)*(.*)(/*)$

# Check if cached index.html exists
RewriteCond /path/to/my/public_html/static_cache/1/$2/index.html (.*\.(.*))$
RewriteCond %1 -f

# Rewrite to the cached page
RewriteRule ^(index.php/*)*(.*)(/*) /static_cache/1/$2/index.%2 [L]

# END MUSTASH STATIC CACHE RULES
#################################################################################

```

# Answer
I finally got this working (Low Search working with Stash static cached homepage)!!!

I added the following rule to my .htaccess, to get it to really really ignore POST requests. I'm not sure why this works (maybe it's my server environment? I'm on a Nexcess EE-Optimized plan).

So I added the following RewriteCond

```
RewriteCond %{THE_REQUEST} ^(GET)

```

And now, my Low Search form works and I can keep my homepage static-cached!
> 3 votes

# Answer
Your htaccess looks OK to me--I think it should be doing what you want. But you could try changing the Request Method match from this:

```
RewriteCond %{REQUEST_METHOD} GET

```

to this more strict match:

```
RewriteCond %{REQUEST_METHOD} ^GET$

```

Another rewrite technique I've used, that I know works, is to enclose the rules in a `Limit` block, like:

```
<Limit GET>
   # your caching rewrite rules here
</Limit>

```
> 1 votes

---
Tags: stash, low-search, htaccess, caching
---


# Question
Title: Freeform Contact form disallowed key characters
first time using the Solspace freeform add on. When i test out the contact form i get a "disallowed key characters"

here is my code..

```
    {exp:freeform:form form_name="contact" required="first_name|user_message" return="contact|contact_us" admin_notify="pete@pbwebdeisngs.co.uk"}
    <div class="grid_8 prefix_2 suffix_2">
        <div class="block_green">
            <h4 class="white title1 space3">Email me here!</h4>
            <label for="{first_name}">Name</label>
            <input type="text" id="name" name="{first_name}"/>
            <br />
            <br />

            <label for="{email}">Email</label>
            <input type="text" id="email" name="{email}"/>
            <br /><br />

            <label for="{user_message}">Message</label>
            <textarea name="{user_message}"></textarea>
            <br /><br />

            <input id="submit" type="submit" value="Comment" name="submit"/>
        </div>
    </div>

{/exp:freeform:form}

```

probably something stupid as usual but help would be appreciated

Thanks Peterp205

# Answer
> 3 votes
```
<input type="text" id="email" name="{email}"/>

```

This is why - you're posting an item whose *key* is an email address. EE treats this as malicious data (as it contains the `@` character).

What you meant to write was:

```
<input type="text" id="email" name="email" value="{email}" />

```

Same goes for all your other inputs - you have `name` confused with `value`, and your `value`s are all missing.

# Answer
> 2 votes
In addition to Derek's answer, try changing `return="contact|contact_us"` to `return="contact/contact_us"`, or some other URL (by the way, return="" should hold a URL, absolute or relative).

---
Tags: solspace-freeform, solspace, channel-form
---


# Question
Title: {count} of shown/rendered channel entries passed through conditionals
When I display a couple of entries using the channel tag, and use the {count} var inside the entries template, I simply get 1,2,3,4 etc.

When I use a conditional to filter entries like so:

```
{exp:channel:entries channel='artworks'}
    {if "{specifications}{type}{/specifications}" == "Painting"}
        {count}
    {/if}
{/exp:channel:entries}

```

Now I successfully filter my entries to only display those entries that match my criteria, however, my count var renders as (eg) 4,8.

I would like to have a variable that renders as 1,2,3 etc. So the count var should only count the rendered entries.

Ho to get this to work?

# Answer
> 0 votes
You're not really *filtering* your entries - you're simply showing some content conditionally. Filtering would happen at the query level - if `specifications` were a Grid field, then you could do:

```
{exp:channel:entries channel='artworks' search:specifications="Painting"}

```

Then `{count}` would work as you expected.

But if `specifications` is a Relationship field, this won't work. You'll need to resort to some PHP (which will need to be enabled for this specific template).

```
<?php $count = 1; ?>
{exp:channel:entries channel='artworks'}
    {if "{specifications}{type}{/specifications}" == "Painting"}
        <?php echo $count; $count++; ?>
    {/if}
{/exp:channel:entries}

```

---
Tags: channel-entries, conditionals
---


title: Stash cacheing with embeds

text:
# Question
Title: Stash cacheing with embeds
It was my understanding that Stash embeds are cached by default. I'm working on an ecommerce site where all template groups have EE templates similar to:

```
{stash:embed
    name="file"
    context="@URI"
    file_name="views:file"
    process="static"
}

```

(I've got `process=static` in there but I've also got static cacheing turned off in my config for now. Will be looking at that part of things later.)

Each view file then contains code that looks like:

```
{stash:embed name="layouts:global"}
{exp:stash:set name="st_content"}Page content goes here{/exp:stash:set}

```

So I thought that I would need to escape the add to cart part of my product detail page with `{stash:nocache}`. But when I add that tag to my page, my form disappears and instead I get `[_Stash_1]`.

If I remove the `{stash:nocache}` tags, the page appears as intended and then if I add products to the cart (which is also set up the same way and currently doesn't have any nocache tags in it), items get added to the cart successfully.

So my question is, am I misunderstanding how cacheing works with Stash or am I doing something else wrong and will I get tripped up somewhere if I didn't correct the cacheing set-up now?

# Answer
> 3 votes
You embed IS being "cached" - saved to the Stash database table as a variable - but it's not being *parsed* before being cached. That is because, out of the box, a Stash embed works just like an EE embed: the content of the embed file is included into the host template and then *parsed at runtime*.

The parsing stage of an embed is controlled by the `parse_stage` parameter.

---

## parse\_stage="set"

Parse the template the first time it is read from the file, and cache the rendered result. Subsequent retrievals will return the cached template from the database and not the original template file (unless you have set `replace="yes"` parameter or have set `stash_file_sync = TRUE` in your config).

## parse\_stage="get"

Read the template file and cache it to the database. When output to the template on the first and subsequent retrievals the template will be parsed. This is similar to how EE templates work.

## parse\_stage="both"

Parse the template before caching AND after it is retrieved. This can be very useful when enclosing regions of your template with `{stash:nocache}{/stash:nocache}`. On SET the template code inside {stash:nocache} will not be parsed, but everything else will. On GET it will be parsed. This provides a way to partially cache some of your template code while leaving other areas dynamic.

---

So to be clear: if you plan to cache a partially-rendered template with regions escaped with `{stash:nocache}{/stash:nocache}` tag pairs, then you will need to use `parse_stage="both"` on your main Stash embed.

Also please note that partial caching is incompatible with static caching, as a static-cached page does not pass through EE or even PHP at all - it's just served as plain old HTML. However, you can of course use javascript/ajax to update dynamic elements within a static-cached page.

---
Tags: stash, caching
---


# Question
Title: Remove segment and segment parts out of url
Alright I seem to hit rock bottom, and can't figure this out.

I've googled and read several solutions here, and can't seem to implement them in my situation.

This is probably an .htaccess solution, which is another reason why I'm asking the question because I don't know how to come up with a solution myself.

So I'd like to take a segment/parts of segment out of my url.

`domain.com/one-day/one-day-denver` and like it to be - `domain.com/denver`

I'm using structure to give me my url structure. I could recreate the page and make it name how I want it, but it would defeat my relationships that I have with playa.

Whats a quick and dirty way that I could write in my `.htaccess`?

I currently have these rules on there.

```
<IfModule mod_rewrite.c>
  RewriteCond %{HTTPS} !=on
  RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  RewriteRule ^ http://%1%{REQUEST_URI} [R=301]
</IfModule>

```

and

```
RewriteCond $1 !^(notes|api|cms|fw|themes|uploads|favicon\.ico|robots\.txt|index\.php|speakers\.json|ads|email) [NC]
RewriteRule ^(.*)$ index.php?$1 [L]

```

How do I write it to remove what I asked about and still and have the inner workings still poiting to `/one-day/one-day-denver`

I appreciate any help.

Thanks!

# Answer
> 1 votes
It depends on why you're doing this I think. It seems like you're adding extra info in to the entry so the client can distinguish between entries inside a Playa field, is that correct? But you want your URLs to be different. If that's the reason just change the URL to denver and keep the title One Day Denver. Playa will display the titles.

Alternatively add 301 redirects in your htaccess, so domain.com/denver maps to domain.com/one-day/one-day-denver. This will show the 3 segment URL to everyone though but you can keep your URLs short.

---
Tags: url, structure, htaccess, segments
---


# Question
Title: Solspace Freeform Pro Notification Hook Bug?
I am using the freeform\_module\_admin\_notification hook and the documentation indicates that the field contents should be available:

```
$this->fields (array) - output data of fields by fieldname

```

But the fields array contains the 'Field Label' of the field keyed by the Field Name.Not the value entered in the form by the user.

For example I have defined a text field in the admin panel for the module, it is called 'name' and the Field Label is 'Name' I have included it on a form:

```
<input type="text" id="name" name="name" class="input-1" />

```

But the value I get within the extension is 'Name' not the value entered in the field.

$fields\['name'\] has a value of Name

Anyone any idea if this is a bug or I am just doing something wrong?

Thanks

Andrew

# Answer
> 0 votes
I believe you want to look at `$variables`, not `$fields` \- specifically, `$variables['field_inputs']` and/or `$variables['field_outputs']`

---
Tags: solspace-freeform, solspace
---


title: Stash Regex Match

text:
# Question
Title: Stash Regex Match
In my stash:get\_list how would I ignore case sensitivity. I know its something to do with '/i' but don't know a thing about regex.

```
{exp:stash:get_list name="filter_list" match="#{stash:keyword}#" against="e_title"}

```

cheers!

# Answer
> 2 votes
Try a case insensitive modifier (?i) :

```
match="#(?i){stash:keyword}#"

```

(untested)

# Answer
> 1 votes
Without digging to deep I would look to transform your stash:set to lowercase to bypass testing. Something like streeng could remove cases and set to all lowercase for example.

http://devot-ee.com/add-ons/streeng

---
Tags: stash, regex
---


title: Generate many promo codes

text:
# Question
Title: Generate many promo codes
because we're not able to setup promo codes to different products with Expresso 1.6.5 like you can with 2.x with discounts. We thought to use 200 promo codes with a limited use of 1.

The questions is, is it a problem to enter 200 codes to expresso? Can this be generated, via our database or with a different tool, which i don't know right now? Do we have to delete this promo codes after use by ourself, or get they deleted when they get used, via expresso store?

Would be great to know, how you would handle this with the 1.6. version

Thanks

Peter

# Answer
> 2 votes
You can do this in Store 1.x by simply adding rows to the `exp_store_promo_codes` table. You can look at existing rows in the table to see the format.

Basically you just need to enter a `promo_code`, set `enabled` to `y`, and set the `use_limit` to `1`.

In Store 2, this table is named `exp_store_discounts`.

You can use a tool such as phpMyAdmin to access the database, or do it programatically from an EE extension.

---
Tags: expresso-store, expresso
---


# Question
Title: Store: Changing Order Statuses from SAEF?
Is there a way to change the status of Expresso Store orders via a SAEF?

For people working in the picking/packing department of a webshop, I would like to create a simple page with a few buttons: "Start picking" "Packed" "Shipped" or "Delayed due to ..." so they can easily use a simple touch screen device and quickly update the status of an order.

Anyone ever tried this? Don't know if it is even possible.

# Answer
It's not possible using Store's built in tags. You could do this by writing your own plugin though, if you're comfortable getting your hands dirty with a bit of PHP.

To programatically change an order status in Store 2, you can find an order by ID like so:

```
$order = Store\Model\Order::find($entry_id);

```

You can then find and change the status like this:

```
$status = Store\Model\Status::where('name', $status_name)->first();
$order->updateStatus($status, $current_member_id, $custom_message);

```
> 3 votes

# Answer
Received a mail back from the developers.

It isn't possible at this moment but they are willing to put it on their list of potential things to do. No commitment towards if/when.
> 1 votes

# Answer
Um, yep the EE Docs even give you an example. You could turn that into radio group or some such to achieve the function you seek.
> -1 votes

---
Tags: expresso-store, expresso, saef
---


# Question
Title: Intermitent failure of Call-backs from World Pay
Using EE 2.5.3 and exp-resso 1.6.3

Basically we keep getting call-back failures. I'd guess around 5% of orders or maybe slightly less all encounter the exact same error:

```
Our systems have detected that your callback has failed.

This callback failure means we were unable to pass information
to your server about the following transaction:

   Transaction ID:
   Cart ID: xxxx
   Installation ID: xxxxxx

Error reported: Callback to http://www.mysite.co.uk/index.php?
ACT=66&H=381d0eea799cbf1ebbddbacca7718ee5: NOT OK, recevied HTTP status: 302
Server Reference: ukdc1-pz-pay03:callbackFailureEmail-1182:MerchReq-126-73

```

Note, it rarely contains a transaction ID which is very strange in and of itself.

World-Pay have insisted that everything is correct at their end and in the World-Pay settings. The only thing they weren't sure about was the call-back URL, which is set by the shopping cart module itself via it's call to WP.

Now, we know the server is working fine, we've had instances of successful payments very close either side of failed payments (as well as ones on their own) and Paypal is working fine with no callbacks ever.

If the server wasn't responding, it also would display a 5xx error, not the 302 redirect, which I believe is how the cart responds normally. We have a script that tests the server's response times from queries to the site and all have them are responding in the below 5 second range at worst.

So we pretty much can't think of anything else left to check.

Hope you can help!

Thanks

Steven Lockey

# Answer
> 0 votes
You probably need to email support@exp-resso.com about this one, so we can follow up and do some tests on your actual server.

That said, looking through the code I'm pretty sure that would only be happening for orders which are declined or cancelled (Store is trying to redirect your customers back to the checkout, but Worldpay isn't having a bar of it). I would try putting through some test orders in Worldpay that are declined or cancelled and see whether you can trigger the error message yourself.

---
Tags: expresso-store, ee2
---


title: VZ Buyers for Expresso Store 2.0?

text:
# Question
Title: VZ Buyers for Expresso Store 2.0?
The VZ Buyers plug in does not work for Store 2.0 and above and I was wondering if anyone had tinkered with it to get it to work? Please let me know!

# Answer
The update to Store 2.x changed some of the extension hooks that VZ Buyers used, the add-on will need to be modified to work with Store 2.0. Your best bet would be to ask the developer directly by going to the Official Support Forum to see if there are plans to update it support Store 2.x.
> 1 votes

---
Tags: expresso-store, vz-buyers
---


# Question
Title: Grid - Column output wrapped in <p> tags
I have a Grid field with four columns

1. Relationship
2. Select Dropdown, Output Formatting = None
3. Select Dropdown, Output Formatting = None
4. Text Input, Output Formatting = None

The problem I am having is that when I output the value of column #3, it is always get wrapped in a `<p>` tag.

I have checked my templates to see if there is any post processing being done(there wasn't)

```
{foo orderby="some|columns|here" sort="asc"}
    ...
    {foo:bar}
    ...
{/foo}

```

This is very, very odd to me since if there is a problem with output formatting, it should be reflected in column #2 since they are setup the same.

Any idea why this is the case?

**NOTES:**

* I am on EE 2.7.2
* I read this forum thread and double checked if my output formatting option is set right
* I read this and tried to apply the solution but it did not work. To be fair, the poster was talking about a native select dropdown, not a grid column select dropdown

# Answer
> 3 votes
After a new channel and new field group and channel fields, I suddenly had the same problem for an existing channel(+fieldgroup)'s entries. It certainly wasn't a template issue.

I'm pretty sure I fixed it now: try renaming the grid field's Field Name (and Publish Label to match) to something else. It should work then (though mind that the template tags would need to be updated to reflect this change), and you can rename it back again to what you have it named now.

Maybe clearing the cache (Tools \> Data \> Clear Cached Data) would have done the trick, you might try that first.

---
Tags: grid
---


# Question
Title: Using Grid with File Fields to get thumbnail
I'm using the new Grid system in EE 2.7.3 and trying to create an image gallery with it. Typically I'd use the normal file upload format as a normal file:

```
{image}
    <img src="{path}_thumbs/{filename}.{extension}" alt="{title}">
{/image}

```

But with the grid system I have to use

```
{gallery_images}
     <img src="{gallery_images:community_image}" alt="{gallery_images:title}">
{/gallery_images}

```

How can I get that to go to the path for the thumbnails?

# Answer
> 4 votes
You can use your original code if you prefix variables with the Grid field's short name. The purpose of the prefix is to avoid conflicts with the outer Channel Entries loop; it doesn't affect functionality.

```
{gallery_images}
     {gallery_images:community_image}
          <img src="{path}_thumbs/{filename}.{extension}" alt="{title}">
     {/gallery_images:community_image}
{/gallery_images}

```

---
Tags: ee2, file-uploads, grid
---


# Question
Title: Search Multiple Channel Fields From One Low Search Field
Is it possible to have a single Low Search form doing something like:

> Low Search Form field called `name` which checks for values in channel fields called `company_name`, `first_name`, `last_name` Low Search Form field called `keywords` which works just like the regular keywords field on Low Search

I know we could have three fields on the form to handle company name, first name, last name but we are trying to simplify it for users and just have one field called name.

# Answer
If you want to search multiple fields with one input field, you'll need to use the Keywords filter. The Field Search filter will always target a single field. Therefore, if you want to search for name only across 3 different fields, you'd need to create a collection where you give weight to the `company_name`, `first_name` and `last_name` fields only. You could use a `<select>` or radio buttons to let the user select the collection to use. For example:

```
Search for <input type="search" name="keywords">
in <select name="collection">
    <option value="">the whole site</option>
    <option value="names">names</option>
</select>
<button type="submit">Go</button>

```

...where `names` is the collection for the name only. By leaving the `collection` parameter empty, you're telling Low Search to search *all* collections.
> 1 votes

---
Tags: low-search
---


title: Global Cache Fragment with Stash

text:
# Question
Title: Global Cache Fragment with Stash
So we have our navigation cached within stash to help rendering time. And as you can imagine, the navigation is present on every page.

The problem is, for some reason this is creating a cache for every page... For example, there's an `[index]:navigation`, as well as an `about-us:navigation` and a `contact-us:navigation`. There's also a `partials:navigation` that gets created, but I think this is just stash saving the template to the database.

As our navigation takes a good amount of time to render, this become a problem when we need to apply the cache breaking rules as now every single page load needs to re-render the navigation and cache it to it's own specific cache.

The tag I'm using for the cache on the navigation is `{exp:stash:cache name="navigation"}`. I have the default scope set to `site` in my configuration file, and when I look in Mustash it says the scope is `site`. For the Label in Mustash though, it says `@URI:navigation` and I'm not really sure why that is happening? I believe that's the problem here.

How do I get my navigation cache fragment to be a global one, and not one generated for every single page?

# Answer
`{exp:stash:cache}` creates a cached variable with the URI as the context. That means each URI at which the host template is viewed will generate a unique instance of the variable. This tag is therefore generally used for full page caching, or for URI-specific fragments of template code.

You should use `{exp:stash:set}` with the `site` scope to create a single global fragment.

Examples here: https://github.com/croxton/Stash/wiki/Caching
> 2 votes

---
Tags: stash, cache
---


# Question
Title: Compare contents of two grid inputs, possibly with variables?
I have two grid inputs and I need to have a conditional statement that says: if all fields of both grids are equal to 0, output some text. The way I'm trying to do this is by changing a variable value based on an EE if.

```
<?php $var = 0; ?>
{ex_product_dimensions_g}
  {if ex_product_dimensions_g:height != "0" || ex_product_dimensions_g:width != "0" || ex_product_dimensions_g:depth != "0"}
    {ex_product_dimensions_g:height}(h) x {ex_product_dimensions_g:width}(w) x {ex_product_dimensions_g:depth}(d)<br>
  {if:else}
    <?php $var++; ?>
  {/if}
{/ex_product_dimensions_g}

{product_dimensions_case_g}
  {if product_dimensions_case_g:height != "0" || product_dimensions_case_g:width != "0" || product_dimensions_case_g:depth != "0"}
    {product_dimensions_case_g:height}(h) x {product_dimensions_case_g:width}(w) x {product_dimensions_case_g:depth}(d) (inc. Flightcase)<br>
  {if:else}
    <?php $var++; ?>
  {/if}
{/product_dimensions_case_g}

<?php
if ($var >= 2):
  echo 'Not specified';
endif;
?>

```

For some reason though $var seems to always increment regardless of the content in the grid input. Can the EE if statements be used for what I am trying to achieve, or is there a better way to do this?

# Answer
> 1 votes
You're going to run in to parse order issues here I think. Unfortunately the code is not executing in the order you've written it, so certain evaluations won't happen when you're expecting them to.

There's a certain point when adding PHP in an EE template that it's best to roll out a custom plugin instead. My general rule when doing something like you're doing is to keep EEs template code as separate from PHP code as possible.

Assuming you have PHP set to run after the template, retrieve all your values first in to PHP vars then add PHP logic at the end of the template.

In this case see if increment $var as you have it but do the logic in PHP later. So instead of

```
{if ex_product_dimensions_g:height != "0" || ex_product_dimensions_g:width != "0" || ex_product_dimensions_g:depth != "0"}
  {ex_product_dimensions_g:height}(h) x {ex_product_dimensions_g:width}(w) x {ex_product_dimensions_g:depth}(d)<br>
{if:else}
  <?php $var++; ?>
{/if}

```

use:

```
<?php $var_h = $var_h + '{ex_product_dimensions_g:height}';
      $var_w = $var_w + '{ex_product_dimensions_g:width}';?>

```

at the end of the template:

```
<?php if($var_h > 0 || $var_w > 0) echo 'A dimension is zero.'; ?>

```

Alternatively it might be easier to go over to using P&T's Matrix as that has some built in logic/maths: http://docs.pixelandtonic.com/matrix/templating/field.html#average-lowest-highest-and-sum

---
Tags: php, grid, ifelse, comparison
---


# Question
Title: Collapsing div toggle using dynamic channel entries
Just a quick issue someone can hopefully help me out with

I have a webpage that displays listed event entries (using `exp:low_events` module). They are displayed as blocks that once clicked trigger a collapsible div to open, standard bootstrap plugin really.

OK, so my problem is that I would like to display a symbol that displays an up/down arrow dependent on whether the collapsible div is open or closed. Normally that wouldn't be an issue but because the entries are dynamic, they each need to be unique.

So right now if you open one entry, the toggle symbol changes on both. I have tried integrating expression engine variables into my script snippet but unfortunately this only has an effect on the first entry, and no effect on any subsequent entries.

```
{exp:low_events:entries
channel="events"
status="not closed"
dynamic="off"
show_passed="yes"
show_upcoming="yes"}

<div class="row-fluid">
    <div class="span12">

        <a id="switch" class="{entry_id}" data-target="#details-{entry_id}" data-toggle="collapse">

        <div class="collapse-block">

        <h4>Title of Event <span class="closed pull-right {entry_id}"></span></h4>

        </div><!--collapse-block-->

```

```
        <div class="collapse in" id="details-{entry_id}">

          Collapsible content

        </div><!--collapse-->

    </div><!--span12-->
</div><!--row-->

{/exp:low_events:entries}

{exp:low_events:entries
channel="events"
status="not closed"
dynamic="off"
show_passed="yes"
show_upcoming="yes"}

<script>

    $('#switch.{entry_id}').on('click', function(e) {
$('.closed.{entry_id}').toggleClass("expanded");
    });

</script>

{/exp:low_events:entries}

```

I'm not entirely sure about using EE variables in my script as its not something I've ever really done, but I'm struggling to see another option...although an obvious solution could be staring me right in the face

The idea of the above code is that when the `<a id="switch" class="{entry_id}"` is clicked it toggles a class of `expanded` the the `<span class="closed">`

Both the `.closed` and `.expanded` classes have background-images set to up and down arrows which will change when the collapsible opens and closes. Though as I mentioned earlier, this markup only seems to have an effect on the first entry and then no effect on the rest.

I'd really appreciate any advice on this

# Answer
In the end this isn't really an ExpressionEngine question at all (you don't need to use *any* EE variables here). A few things:

1. You cannot have two elements with the same ID on each page (so, using `<a id="switch">` within a loop is a no-no).
2. CSS class names cannot be purely numeric (e.g., `class="{entry_id}`).
3. You don't have an `href` value or closing tag for your anchor - this can cause issue in some browsers.
4. Your jQuery script should be abstracted to apply to *all* of your looped markup blocks.

I assume you have another script at play here as well, which is handling the collapsing via the the `data` attributes in your markup - if it's expecting an element with an `id` of `toogle`, you may have to adjust it so that it uses a class name instead.

Here's a revised version of your code which should work for you:

```
{exp:low_events:entries channel="events" status="not closed" dynamic="off" show_passed="yes" show_upcoming="yes"}
<div class="row-fluid">
    <div class="span12">

        <a class="switch" data-target="#details-{entry_id}" data-toggle="collapse" href="#"></a>

        <div class="collapse-block">
            <h4>Title of Event <span class="closed pull-right"></span></h4>
        </div><!--collapse-block-->

        <div class="collapse in" id="details-{entry_id}">
          Collapsible content
        </div><!--collapse-->

    </div><!--span12-->
</div><!--row-->
{/exp:low_events:entries}

<script>
    $('.switch').on('click', function(e){
        $(this).parent('div').find('.closed').toggleClass('expanded');
        return false;
    });
</script>

```
> 1 votes

# Answer
Low Events supports all `channel:entries` parameters and variables.

So I'd ignore the entry id and use count instead:

```
<div class="row-fluid">
    <div class="span12">

        <a id="switch" id="event{count}" data-target="#details-{entry_id}" data-toggle="collapse">

```

Now we're in HTML/JQuery territory! Personally I wouldn't use a class to identify each unique link, an ID is more appropriate.

Then in your JQuery:

```
$('a[id^="event"]').on('click', function(e) {
  $(this).find('.collapse-block').toggleClass("expanded");
});

```

Again personally I I'd say you're not using JQuerys 'on' handler correctly. This will add N events to the DOM depending on how many events you have displayed. This can be handled with 1 event to the container element.

```
$('.row-fluid').on('click', 'a[id^="event"]' function(e) {
  $(this).find('.collapse-block').toggleClass("expanded");
});

```
> 0 votes

---
Tags: channel-entries, dynamic, bootstrap
---


# Question
Title: Thumbnail could not be created for the image
I'm using EE 2.6.0, has anyone run into an issue where they get the following error when trying to upload a image: Thumbnail could not be created for the image. Please make sure the thumbnail directory is writable.

I've checked the usual suspects, the path is correct, permissions on the folders are ok. I've tried changing the image library from GD2 to imagemagik. I can upload other file types to the folder (pdfs etc..) just not images.

Strange thing is, it was working ok, the client left the site for a few months, I've just returned to it to finish it off. I was able to upload ok 6 months ok, nothing's changed in the meantime.

Thanks,

# Answer
Checked the permissions of the upload destination folder, make sure that PHP has permission to create files and folders. If the 'thumbs' folder exists in this destination make sure nothing odd has happen to that, and it's permissions are set correctly. EE should have created it but in the past I've deleted whole directories and uploaded local folders with a thumbs folder inside. This can sometimes result in the FTP user (you) as the owner and PHP can't alter it.

Another place to look is the tmp folder for the server. I've had this issues as well. The PHP img library (GD2/imagemagik) needs a temp folder to save the image while manipulating it. Make sure your Apache vhosts conf file allows the site to access the system tmp folder and it's permissions are correct.

You, too, should make sure the path to ImageMagick is right, in case you're using it.

I'm assuming it's an Apache server. Also depends on how you're administering it. I've had Plesk completely screw up a vhost file in this way before.
> 1 votes

---
Tags: image, uploads
---


# Question
Title: Sorting and filtering items in Cartthrob
I've been trying to find a proper way to do this but no luck so far. How does one go filtering products in Cartthrob. For example if the user wants to change the number of products displayed by clicking the relevant link (show items: 16, 64) (limit=16, limit=64 and so on). I've tried using Mo'variables and pass a limit variable on the url (i.e. /books?limit=16) however this messes up pagination and category filtering. Is there a guide or something on how to achieve this without loosing your hair? :)

# Answer
> 0 votes
You're on the right track. This advice applies to EE 2.7.2+, so if you're on an earlier version of EE, sorry. First, you don't need to use Mo' Variables. All you need to do is set the `dynamic_parameters="limit"`. Now when `limit=X` is in your url query string, the channel:entries loop will automatically use that limit. To get it to work with pagination, you need to do this (add the query string to the pagination links):

```
{paginate}
  {pagination_links}
    <ul>
      {page}
        <li><a href="{pagination_url}{if current_query_string}?{current_query_string}{/if}">{pagination_page_number}</a></li>
      {/page}
    </ul>
  {/pagination_links}
{/paginate}

```

Docs on dynamic parameters: http://ellislab.com/expressionengine/user-guide/modules/channel/dynamic\_parameters.html

Docs on current\_query\_string global variable: http://ellislab.com/expressionengine/user-guide/templates/globals/single\_variables.html#current-query-string

---
Tags: cartthrob, url, sort, orderby
---


title: Addons - Snippets as files

text:
# Question
Title: Addons - Snippets as files
Is there a well-supported, 2.7.x+ compatible add-on to save Snippets as files like what we can do to templates in Expression Engine?

I think there are a lot of options out there but I just want something that is well supported and stable.

# Answer
My choose is Bjorn SnippetsSync \- simple and stable
> 6 votes

# Answer
I personally prefer Low Variables as it does so much more than just let you edit as files. You can control the parse order allowing you to create global variables or snippets. Plus it works with a whole bunch of field types making it extremely useful for content that clients need to edit but don't deserve a channel. And yes you can hide variables/snippets from clients so your client only sees what they need to.
> 3 votes

---
Tags: snippets
---


title: Member Badges/Achievement?

text:
# Question
Title: Member Badges/Achievement?
Had anyone come across developing **Member badges** in Expressionengine?

I am developing a site, when a member do such activities such as

* Creating Entry
* Leaving Ratings
* Leaving Comments
* Making 10x comments
* etc

and they get awarded a badge.

**Plugins I am using**

* User (Solspace)
* Credits (Dev Demon)

I need some guidance. If no such plugins available, is there any other alternative I could develop with.

Many thanks D

# Answer
Never done that but there are a few Member custom profile options available, see http://ellislab.com/expressionengine/user-guide/modules/member/index.html#id6

That would cover, for each member, getting

* Total entries
* Total comments
* Total forums posts
* Total forum topics

You could grab those values and do somthing like:

```
{exp:member:custom_profile_data}
    {if total_entries < 10}Newbie user{/if}
    {if total_entries >= 10 AND total_entries < 50}Advanced user{/if}
    {if total_entries >= 50}Super user{/if}
{/exp:member:custom_profile_data}

```
> 0 votes

---
Tags: members, solspace, plugin, solspace-user
---