texts: Category slug variable is not available when category url's are disabled

texts:
Just like the title states, the slug variable is not available when a category's url are disabled:

<select name="field-styles" id="field-styles" class="select">
    <option value="">Style</option>
    {% for style in craft.categories.group('productStyles').order('title') %}
    <option value="{{ style.slug }}">{{ style.title }}</option>
    {% endfor %}
</select>

The snippet of code above works when the URL's are enabled for this category group. When disabled, the input value is blank.


texts: How to save a Matrix with Super Table in it

texts:
I have an entry with a Matrix field, inside this field I have a Super Table as block type.  My fields data looks like below:

"title" => "test1"
"matrixHandle" => array:2 [
  0 => array:2 [
    "type" => "sponsorshipRow"
    "fields" => array:2 [
      "sectionTitle" => "blablabla"
      "superTableHandle" => array:5 [
        0 => array:3 [
          "fields" => array:10 [
            "relatedArticle" => 325051
            ...
          ]
        ]
        1 => [...]
  1 => [...]

Then I loop these fields

foreach ($fields as $key => $value) {
    $entry->setFieldValue($key, $value);
}

And last, I save the entry:

Craft::$app->elements->saveElement($entry);

But every data is saved except for the super table block. The super table block is not even created. Any idea please?


texts:
is it possible to grab all the entries in a section that arent related to a category?

So something like

craft.entries.section('news').relatedTo('not',category)

Doesnt seem to work but is there some other syntax?


texts: Swapping currency when swapping languages

texts:
Folks:
I have a multilingual and multicurrency site. All works fine when switching currencies or languages independent of one another. But is there a way to have the currency switch when the language is switched? For example, if the user selects German, the currency is switched to Euros.
To complicate matters, I am using GeoMate to detect the IP and redirect to the appropriate language. Can I switch to the correct currency when they are automatically redirected to their language?


texts: What variables are available to what template types?

texts:
complete newbie question here. Craft is so well designed, I could probably work it out, but it seems like this simple info might help others as well.

So here goes, a two part question:
1. Is there a simple list of the types of pages Craft outputs?
   (like single-entry, single-category, search-results, etc)
2. What are all the variables available to each of those?
   (single-entry has a variable called 'entry', plus the globals, I think)

Thank you!


texts:
I am evaluating different CMS. I need to know if Craft CMS supports these features:

Preview function for different devices, screen sizes and screen configurations(portrait/landscape)
Is it possible to publish only a subset of my website?
Is lazy loading supported? E.g. loading images on scrollto?
Does a frontend created with Craft CMS use much .js code? Can I minimize the amount of .js code (for performance reasons)?
Is mobile first approach supported?
Are URLs SEO-friendly?
Can I integrate Onsite-Banners from external Ad servers?
Does the cms contain Digital Asset Management?
Which media file types are supported?
Is there any REST API provided?
Does the CMS internal search engine support synonyms and how about the error tolerance?
Can I login to the CMS on mobile devices? Do I have good usability when doing so?
Do I upload high resolution images and later on these are generated and maybe compressed for target devices?


texts:
I'm having a hard time understanding how the payload (and namely, IDs of payloads) is defined.
When a webhook for craft\elements\Entry is triggered, I get something like (very simplified):
{
  "sender": {
    "id": 1001,
    "duplicateOf": {
      "id": 1000
    }
  }
}

On new entries, I also get like 2 hooks, and then the second payload is:
{
  "sender": {
    "id": 1002,
    "duplicateOf": {
      "id": 1001
    }
  }
}

But looking in admin, the actual ID of the entry (looking at the url pattern) would be 1001. This doesn't change, regardless if I create other revisions, re-save or otherwise.
What in this case, does the ids 1000 and 1002 refer to? These doesn't seem to be "loadable", but they have somehow been created (and deleted?).
Right now I deduplicate it on event.sender.ref because I can't deduplicate on id:s, hopefully that is unique enough. But I would really like to know exactly what is going on behind the scenes here.
The webhook configuration is as follows (I need a hook when entry is created, and re-saved):


texts: Set User's entry field from PHP in Craft 3

texts:
From this question, I tried:

$user->setAttributes(['products' => $userProductsIds]);

return Craft::$app->getElements()->saveElement($user);

Where $user is an instance of craft\elements\User; and $userProductsIds an array. It's not giving me any errors, but the user is not updated. Any idea on what am I missing?


texts: How flexible is tying content to a structure?

texts:
I'm trying to decide how to organize my content on a site with a few levels of hierarchical content. I'm toying with the idea of creating structures for all my top level navigation items, with a few levels of nested content for sub-navs and sub-sub-navs.

My main concern is that if there are 100+ sibling entries deep inside one of my structures, how coupled are the entries to the hierarchy of the structure? Would I be able to later move that section to a completely different main navigation structure?

Or would I be better decoupling the a lot of my content into singles and smaller structures or channels, and sacrifice the relationships between the pages and the neat tree-like representation that gives clients a better overview of their site structure?


texts: Issues accessing Control Panel with iPad on iOS 7

texts:
I'm having issues accessing the Control Panel using an iPad on iOS 7.0.4. When loading the Dashboard and any subsequent pages, 6 popup alerts will appear with the message:

Safari cannot open this page because the address is invalid

After dismissing this alert 6 times, it'll disappear until you visit another CP page. I can confirm that there are no issues using iOS 8.1.2. I've tested on numerous sites without any plugins installed, along with a brand new Craft Demo site, and the issue persists.

Any ideas what could be causing this?


texts: I'm trying to create manual payments within Craft Commerce so the customer doesn't have to enter their credit card but every time I use the checkout button it says that the payment information is invalid. Is there anyway to have customers checkout without credit card info?


texts: Link Popup Modal to correct script in loop

texts:
Popup Closed Screenshot

Popup Open Screenshot

I have image that has multiple markers on it that can be clicked to bring up different popups. However, I need to some help refining the code to work properly and to link to the correct id tag.

My template code:

{% set var = craft.entries.section('availablehomes').relatedTo(category).level(2) %}
{% for entry in var %}

{% set plotPopup = 'plotPopup' ~ entry.title|camel %}

....markup.......

{% endfor %}

Which outputs

...

...

...

...

And below is the current script text:

Which is printing out as:


texts:
I know Craft gives us access to Twigs getTwig template service; so when I attempt to use the addGlobal function like so:
craft()->templates->getTwig()->addGlobal('var', $var);

... nothing happens. No errors. I had hoped putting this in my plugins init() would allow me to call the variable in a twig template like so: {{ var }}. But that just returns an error.

Variable "var" does not exist

I know of other methods to define global variables. I just wondered where I was going wrong with that quick one-liner that doesn't seem to work.
Maybe Craft has ommitted it?
Thanks,
Mark


texts:
I have a field of the dropdown fieldtype, let's call it myDropdown.

myDropdown has a list of options, one of which has the "default" checkbox checked.

If I use a front-end form to submit a new entry, but the form does not contain the myDropdown field, will Craft insert the value designated as the the default into that field, or will it just leave the field empty?


texts:
I am making a plugin which has a controller to be called every hour.
My server environment is using Anacron.

So I wrote this anacron job:
1@hourly 0 cron.hourly wget http://www.mydomain.com/actions/controlername

And I got 2 questions:

How to log my cron job into a file on the server? (so I can follow when it has been triggered)
What is the best way to log and follow my controller actions in Craft CP side?


texts: How to create a relation to multiple assets in my Plugin Model/Record?

texts:
I defined an estateRecord in my Plugin. Every estate has a set of images that i want to import from a zip file directly via assetsService::insertFileByLocalPath().

In my estateRecord I defined a relation:

public function defineRelations()
{
    return array(
        'assets' => array(static::HAS_MANY, 'AssetFileRecord', 'id'),
    );
}

Is that correct?

Now i'm stuck to define a 'asset'-field in the estateModel to access the image-sets.

I just find a solution to define the Attribute for one assetId but have no idea how to define the Attribute for the related set of assetIds.
How can i do this?


texts: Using modifyElementsQuery to get plugin's custom table data

texts:
I need to join my plugin's custom table to a an ElementCriteriaModel (ECM). I am trying to use modifyElementsQuery.

In the plugin's custom table, rows can share an element/entry via a separate id.

Can I achieve this by adding to the modifyElementsQuery? What would the query be to accomplish this?

*My intention is to have an array of models for each row of my custom table, and each model will include my row data, in addition to the element's content it is related to.


texts: Duplicating Matrix fields with content from another locale

texts:
I'm working on an Element Action that will duplicate some fields from the primary locale, to whatever locale the user is currently in, if those fields are already empty.

Asset fields seem to work fine, but I can't find a way to duplicate Matrix fields with all their content, including their own relation fields.

So far I've got:

foreach ($criteria->find() as $element)
{
    $locale  = $criteria->locale;
    $content = $element->getContent();
    $gbr     = craft()->entries->getEntryById($element->id, 'en_gb');

    foreach ($element->getFieldLayout()->getFields() as $fieldLayoutField)
    {
        $field       = $fieldLayoutField->getField();
        $fieldHandle = $field->handle;

        if (in_array((string) $field->type, array('Assets', 'Entries', 'Categories', 'Tags')))
        {
            // only copy the relation's IDs if there's nothing there already
            if ($element->$fieldHandle->total() == 0)
            {
                $content->$fieldHandle = $gbr->$fieldHandle->ids();
            }
        }
        elseif ((string) $field->type == 'Matrix')
        {
            if ($element->$fieldHandle->total() == 0)
            {
                foreach($gbr->$fieldHandle->find() as $gbrBlock)
                {
                    // not sure what to do here to duplicate $gbrBlock,
                    // and save it to $locale with the same contents.
                }
            }
        }
    }
}

$element->setContent($content);

I've tried using craft()->matrix->getBlockById($gbrBlock->id, $locale) like you do when duplicating whole entries (they're both elements right?) but that always comes back null, so... I need to create a new MatrixBlockModel in that locale?


texts: Problems with Craft CMS development strategy

texts:
Clearly Craft CMS is not a thing for non-developers (like WordPress or Drupal is). Despite the option to create fields, sections, etc. in the administration panel, we still need to code templates (twig, html, CSS, etc.). So for me it's kind of a weird relationship where we define those things in administration with ease and luxury (no programming at all), and then still need to code standard way upon it in templates.

In my opinion, this relationship creates a bunch of issues:

1) Let's say we work in team and some other dev decides to remove some fields (or change handle names), because he/she does not know my part in templates. The page is screwed! And it's hard to rollback, because, well it's database.

2) Content replication problem! Thanks god there is something upcoming in this area https://craftcms.com/news/craft-3-content-migrations, but still this is fishy - read on.

3) Request to DB are made for content definitions, that mostly stay the same all the time. No need for that.

The solution I see, in my opinion, is very simple.

Let programmers to define fields, sections, globals, etc. (most of the settings contents) programmatically. If we know how to code with Twig, it shouldn't be so hard to edit some Yaml or PHP array. There is nothing to lose!

After that:

1) No request to DB for code defined stuff. Huge performance gain.

2) There is no content replication problem for programmatically defined settings. It is just delivered via version control!

3) We can create unit tests, do code reviews, etc. for those content parts. Even extend to more functionality ... and always refer to version control (revert/analyze bad changes etc.).

Am I talking bananas?
BR, J


texts: Error with uploading Asset Files: net::ERR_EMPTY_RESPONSE

texts:
In my local MAMP site I'm not able to upload any files.

Gives me this error in Chrome:

http://nobel.craft.dev:8888/index.php?p=admin/actions/assets/uploadFile net::ERR_EMPTY_RESPONSE

This error in Safari

"Failed to load a resource: The network connection was lost."

Things I did

I've checked the asset folder path
makes sure folder is writable
nothing strange in the craft.log
delete cache in admin
download new version of craft and replaced the app folder


texts: IncludeJsFile doesn't load from within the templates directory

texts: Anyone know what could be wrong? It doesn't load files residing in /craft/templates/js that I include with for example {% includeJsFile "/js/file.min.js" %}, only if the js folder is in the public folder.


texts: Forgot password URL in email returns an error

texts:
When hitting the "forgot password" link on the CP login form, an email is sent but the URL provided returns "Bad Request Param "id" doesn't exist."

Is this a bug or have I done something silly?

This is a site running on a local development environment with Craft 2.3.2636


texts: Listing All tags - and linking them to list of entries with that tag

texts:
I have a blog, and in the sidebar I have listed all tags in use. I would like to link each tag - when you click it I want to link to a page that lists all the blog entries which have that tag applied to them. Cant find this in the docs.. would someone mind helping? Here is my code so far:

    {% set entries = craft.entries.section('blog').limit(null) %}
         {% for tag in craft.tags %}

{{ tag.title }}

    {% endfor %}

MY RESULTS: This code is linking to for example mysite.com/blog-page/88 - and giving me a page not found. I have a template blog-page and the path is correct as the page loads if you remove the tag-id off the end.

Thanks


texts: How do I perform a critical update if my Craft site relies on older plugins?

texts:
I recently came across a website in this situation and am curious to here how others approach this problem.  Here's the scenario:

A client had a website built on Craft 2.4 with a lot of integration work. The site has 10 custom plugins, integrating with several different systems and services. The relationship with the original development firm did not work out and a new development firm is picking up where the old one left off.  This means, the new team initially has limited knowledge of the 10 custom plugins on the site.

The new development firm inherits this project just as Craft discovers and releases a critical update with a fix for a security vulnerability (Craft 2.6.2791). It's in the website owners interest to upgrade to the latest version of Craft.

However, as mentioned, the site has 10 custom plugins that have not yet been updated to Craft 2.5. And, for fun, let's just say Craft 3.0 is also on the horizon.

If you are the development firm that inherits this project:

What options do you present to the new client for them to move forward?
How do you explain the costs (and the value) of why 10 plugins will need to be updated to Craft 2.5 and to Craft 3?
How do you respond if the client expresses concern that this work doesn't relate to value toward their business objectives?


texts: Getting to grips with errors and flash messages

texts:
As a newbie to Craft and Craft Commerce. I wondered if someone could explain the difference between all these error codes that I have seen either in the docs, this forum or the templates and when they get set and when I should use each method in which situations? Apologies if this is a broad question...

{% if errors is defined %}

        {% for error in errors %}

{{ error }}

        {% endfor %}

{% endif %}

{% if errorMessage is defined %}

{{ errorMessage }}

{% endif %}

{% if model and model.getErrors('firstName') %}
   {{ model.getErrors('firstName')|join }}
{% endif %}


texts: 'Invalid argument supplied for foreach()' using Shopfiy Craft Plugin

texts:
I have set up the Craft Shopify plugin on a new build.

I have also created a 'Shopify Product' field in the CMS on my entry within my Products channel.

However, whenever I try to view the product in the back end I get this error:

Any help would be massively appreciated.

Thanks,
Jay


texts:
I'm using a form using Sprout Forms plugin. This form is set for submitting via AJAX. The documentation explains how to translate error message, but this is not working via AJAX submissions.

Currently, the primary language of this website is French. While the site is browsed in English or Dutch, it still shows AJAX errors in French.

How can I get Sprout Forms errors in current language using AJAX?


texts:
I have created a simple task to automatically create some entries if they don't exist and this all works fine.

The only issue I am having is that if the task is still running and I try and load a page on the site or another control panel page it simply hangs until the task is complete.

I can't seem to get the task to run in a similar way to the task that runs when updating a section's Entry URL Format (the task spinner and progress bar in the top right).

I have tried using the PowerNap example and changing the total steps to 100 (to give me enough time to see what is happening) and the same thing happens.

Do I have to create it as a specific background task?

Edit: To show sample code

<?php
namespace Craft;

/**
 * Inception task
 */
class Bounce_TotalUpdateTask extends BaseTask
{
    /**
     * Defines the settings.
     *
     * @access protected
     * @return array
     */
    protected function defineSettings()
    {
        return array();
    }

    /**
     * Returns the default description for this task.
     *
     * @return string
     */
    public function getDescription()
    {
        return 'Update Total Record';
    }

    /**
     * Gets the total number of steps for this task.
     *
     * @return int
     */
    public function getTotalSteps()
    {
        return craft()->elements->getCriteria(ElementType::User, array(
            "group" => "members",
            "limit" => null,
        ))->total();
    }

    /**
     * Runs a task step.
     *
     * @param int $step
     * @return bool
     */
    public function runStep($step)
    {
        $users = craft()->elements->getCriteria(ElementType::User, array(
            "group" => "members",
            "limit" => null,
        ))->find();

        $section = craft()->sections->getSectionByHandle("totals");

        if (isset($users[$step])) {
            $user = $users[$step];

            $record = craft()->elements->getCriteria(ElementType::Entry, array(
                    "section" => "totals",
                    "authorId" => $user->id,
                )
            )->first();

            if (!$record) {
                $entry = new EntryModel();
                $entry->sectionId  = $section->id;
                $entry->typeId     = $section->id;
                $entry->authorId   = $user->id;
                $entry->enabled    = true;

                craft()->entries->saveEntry($entry);
            }

            return true;
        } else {
            return "Result " . ($step) . " does not exist";
        }
    }
}


texts: Error with Craft Commerce & Stripe no longer supports API requests made with TLS 1.0

texts:
I am using the code from the example templates to integrate a simple stripe pay button on a commerce site:

<form method="POST">
  <input type="hidden" name="action" value="commerce/payments/pay"/>
  <input type="hidden" name="redirect" value="/orders/order?number={number}"/>
  <input type="hidden" name="cancelUrl" value="/checkout/payment"/>
  {{ getCsrfInput() }}
  {% if cart.paymentMethod.class == 'Stripe' %}
  <script
    src="https://checkout.stripe.com/checkout.js"
    class="stripe-button"
    data-label="Pay Now"
    data-key="{{ cart.paymentMethod.settings.publishableKey ?? '' }}"
    data-name="{{ siteName }}"
    data-image="/assets/img/tfa-logo-128.png"
    data-description="Membership" {# This is not used for order description in stripe - see Craft Commerce general settings #}
    data-email="{{ cart.email }}"
    data-currency="{{ cart.paymentCurrency }}"
    data-amount="{{ cart.totalPrice|commerceCurrency(cart.paymentCurrency,convert=true,format=false) * 100 }}"
    data-locale="auto">
  </script>
  {% endif %}
</form>

When the form submits I get back the following error:

  Stripe no longer supports API requests made with TLS 1.0. Please
  initiate HTTPS connections with TLS 1.2 or later. You can learn more
  about this at https://stripe.com/blog/upgrading-tls.

Is this something that needs updating in the commerce plugin? I am running my local site using HTTPS using Valet. I found this link which suggests it might be the plugin that needs updating (I am using the latest version of craft commerce).


texts: Is it achievable to route a dynamic URI with prefixed character?

texts:
The goal is to have a variable(link) merged with prefix "any special character", that will not break the URL(this was pointed to my about character in URL lately, but in this question, We use "#"). So the final output would be "site.com/#variable" (in my case it is the author of an entry and a link to author's profile.

Also, I'd have to route it to get the correct template loaded. The whole reason behind is, that the current prefix would avoid of potential conflicts with other templates in case, some username will be 'index'.


texts:
I'm stumped trying to order paginated entries for a channel. The end goal is to have listings with the most recent postDate at the top. The code below has the most recent item third instead of first. The first item should be third.

The same happens as you paginate to the next page. The third item listed should be the first item listed.

{% paginate craft.entries.section('podcastEpisodes').order('postDate desc').limit('3') as pageInfo, pageEntries %}
{% for entry in pageEntries  %}

{% set category = entry.topic.first() %}

{{ entry.postDate|date('M j, Y') }}

        {% set myEntry = entry.podcaster.first() %}
        {% if myEntry %}

{{ myEntry.title }}

        {% endif %}

{{ entry.title }}

{% endfor %}

Any idea why this is happening?


texts: nitro Error: stat no such file or directory

texts:
I've gone over the way to set up Nitro over and over again but I keep running into the same problem. I even destroyed nitro and deleted everything and restarted to see if I just did something wrong.
When I do "nitro create" I get the root to /home/ubuntu/sites/projectname/project/web but after mounting I get "Error: stat /home/randomfolder/projectname: no such file or directory.
I have tried to manually create those paths and run it all again and I still receive that same error. It adds to the nitro-dev.yaml file just fine and it says that it's mounting but I don't get anything beyond that and I can't open anything with the chosen hostnames.


texts: Relating entries to assets within an ElementAction

texts:
I'm following the Element Actions example from the official Craft docs.

I've defined an Artist entry type, and have defined an entries field on my Assets to relate an Artist to each Asset. To avoid assigning Artists one-by-one, I'm attempting to create a Element Action so that I can select multiple Assets in the Asset Index and relate them to an Artist entry in bulk.

I'm almost there. I can select an Artist (entry) from a dropdown I've created on the Asset Index page in the CP, but I'm struggling to save the relationship in the performAction function within my plugin. I assume I should be using the relations service saveRelations() method to accomplish this?

I'm new to Craft and not sure where I'm going wrong. I'm sure the fact that I'm doing this within an ElementAction is irrelevant, it's just that I'm doing something wrong while trying to save the relation. Here's the relevant part of the code as it currently stands:

public function performAction(ElementCriteriaModel $criteria)
{
    // Get the selected artist
    $artistId = $this->getParams()->artist;
    $artist = craft()->entries->getEntryById($artistId);

    // Make sure it's a valid one
    if (!$artist)
    {
        $this->setMessage(Craft::t('The selected artist could not be found.'));
        return false;
    }

    // Assign the artist to the selected elements
    $assets = $criteria->find();

    foreach ($assets as $asset)
    {
        $artistFieldModel = craft()->fields->getFieldByHandle('artist');
        craft()->relations->saveRelations($artistFieldModel, $asset, $artistId);
    }

    // Success!
    $this->setMessage(Craft::t('Artist successfully assigned.'));
    return true;
}

Any pointers gratefully appreciated.


texts: Error: "Variable "entry" does not exist" on basic template

texts:
I'm new to Craft and I'm stumbling at the first hurdle for Craft 3

I'm getting "Variable "entry" does not exist." and I'm certain it's something so simple I'm missing.

Case:

Install craft 3 via composer
Add a Single section called "Homepage" (URI: "/" | template: "index")
Add "templates/index.twig" - test it with basic markup; displays correctly
Add plain text field to homepage section ("homepageHeader")
Fill out homepageHeader in control panel and save.
Change template to literally only "{{entry.homepageHeader}}"
Error above after page refresh

I must be missing something VERY simple. What is it?


texts:
Help!

I have a parent page called 'Employment' that is a structure - it has 8 sub pages beneath it. I have just created a new single template and would like this to replace this page - is this possible?

Would really appreciate the help!


texts: Outputting .relatedTo() total entries number

texts:
I'm trying to get the total number of entires that match a .relatedTo() search.

{% set category = craft.categories.group('products').title(cat).first() %}
{% set entries = craft.entries.section('products').relatedTo(category).find() %}

I have tried ...

{% set entryCount = craft.entries.section('products').relatedTo(category).find().total() %}

But no joy. What Am I missing?


texts: Smart Map - displaying pin in center of zip code

texts:
I have addresses in my structure using the smart map address zip field. The Smart Map plugin looks up the Lat/Long just fine and checking independently the values seem to be correct. If I enter anything less than a full address (street, city, state, zip) even though the lat/long is there the map does not display properly, I either get a map of the world or a blue box.
I am a noobie so I am sure it is something I have not done correctly.
Example:

Zip: 90210
Lat: 34.10300320
Long: -118.41046840

Code:
    {% for entry in craft.entries.section('groups').limit(5).find() %}

{{ entry.title }} , {{ entry.address }}, {{ craft.smartMap.img(entry.address) }}

    {% endfor %}

When I click drag:

When the map renders:


texts:
Morning folks. First time doing multi-environment in Craft 3, and separate installations for staging and production is a bit overkill for this particular project. Instead I just want to show a few new bits in templates on the staging subdomain until sign-off.

Staging domain (https://staging.adddress.com) is pointed at the production 'public' directory. So in Craft 2, I'd just let the 'staging' key in my config.php set all the necessary environment variables. But in Craft 3 don't I need to load the correct .env first? Since it's all the same installation, is there a way to switch to .env.staging when on the staging subdomain? Is that the correct/best approach? Thanks.


texts: Is it worth caching product blocks for use on a category page?

texts:
So we have a Commerce project that shows lots of products per page/category as per any standard store.

Each product block comprises:

Product name
Product price
Brand (via category field) [eager loaded]
Image [eager loaded]

Is it worth caching each of these blocks with a unique key?


texts: Where to place a front-end 'entry form'?

texts:
I'm trying to add an entry form outside CP (for users with proper permissions), using this example:

http://buildwithcraft.com/docs/templating/entry-form

but there's no mentioning of how/where to add a page/template that will house the form. One place I was able to place it is the actual template for the entry which is also used for viewing the entry, but that's not what I need. I need a separate URL pattern and separate template file. E.g.:

mysite.com/recipes/{slug}/edit

or

mysite.com/edit-recipes/{slug}

Any help is greatly appreciated!


texts: Craft Nginx Cache Static Resources - Css, JS Errors

texts:
I'm currently trying to cache css and js files with the widely known config as follows:

location ~* \.(png|jpg|css|js|jpeg|gif|ico|xls|doc|zip|exe|mp3|mp4|pdf|ai|psd|eps|ppt|dmg|csv|key|numbers|cur|gz|pages)$ {
        expires 7d;
    }

I have also tried the following config from https://github.com/nystudio107/nginx-craft/blob/master/nginx-partials/expires.conf

location ~* \.(?:css|js)$ {
expires 1y;
access_log off;
add_header Cache-Control "public";

However with both of these configs I get 404 (not found) when trying to load css and js everything else works fine jpeg, png, ...etc.

When I remove js and css from the config it works perfectly, however its not being cached.

Any thoughts are much appreciated!

-Adam


texts:
Is it possible to limit the number of levels within a Structure element?

Let's say for example, I only want to max of two levels. So there can be only have something like the following with no way to allow a child of a child so to speak:

Parent

Child
Child

Parent

Child

Parent
Parent


texts:
With my plugin I am generating and saving a lot of data to a secondary table. Data that can be generated on the fly that is associated with entries. I have noticed a performance hit and was given a suggestion of caching some of that data instead of writing to a database.

Does craft have a built in caching system I can use for accomplishing something like this?


texts: Limit slugs to ASCII for auto-generated titles

texts:
I currently have auto-generated titles that contains accents and so does the slugs.

Since the slug is used to generate assets folders, accents aren't suitable and results in question marks in the folder names.

I was hoping that limitAutoSlugsToAscii would answer this problem but it only affects the javascript for dynamically generated slugs.

Is there a simple way to achieve this ?


texts:
Researching this online and not having much luck if anyone has done this before.

How would one get the content from the CMS to update the FE and also create new pages / modules as a normal CMS would allow you to do?

Little confused on this.


texts: Plugin Asset Subfolder Access Issue after Update

texts:
We are using the Asset Subfolder Access Plugin to manage the upload/view permissions for several user groups. The Plugin works great with Asset sources and also in the Assets Fields. But since an update*, it does not work anymore with the sources in Redactor. In Redactor it shows now all sources and it's also possible for users to upload files to these sources, even it's not permitted through the Asset Subfolder Access Plugin. Does anyone know how to fix this issue? Thanks a lot.

*In Craft Pro 2.5.2740 it worked without problems

Example 1

In Asset Sources (Correct: Shows only Folders with Permissions)

Example 2

In Redactor (Wrong: Shows all Folders)


texts:
I have a site with some poorly written code which creates the desired left hand menu from a structure with several hundred entries. Page generation on the server for uncached requests takes 3-5 seconds. Longer term I know I need to fix the code, but short term I have cached the section of code using {% cache %} and this works really well - until the cache is cleared.

Now I have tried Cache Warmer and on running the script I get the presumable success message "All urls are all warmed up". However all caches are clearly not warmed up when I test the pages - the first load is still slow (and it isn't local caching that helps). There are some numbers in the Cache Warmer plugin configuration screen that suggest there may be a maximum. Furthermore I have certain pages that are not based on their own entries e.g. A site map which runs straight off its own template. This page is particularly slow until it has been run once. So I am not entirely sure how Cache Warmer works and what I need to do to ensure that it warms the entire cache.

I am not using anything else. Varnish seems like a solution but for me its implementation might be a bit too complex (I don't have full server access and I am not very skilled on the server end).


texts:
So I'm trying to setup my first Craft installation on Digital Ocean. I'm bound to use Craft version 2.0.2535 since I'll be duplicating a site using this (so I cannot use Craft 3).

I've spun up a new Droplet on DigitalOcean. I've set up Apache, PHP and Mysql and verified it all works. After copying the the Craft files and resolved all the issues regarding rights to folders, I was finally ready to run the installer, I get this:

  Notice: Undefined property: Craft\WebApp::$urlManager in
  /var/www/craft/app/controllers/BaseController.php on line 37

  Fatal error: Uncaught Error: Call to a member function
  getRouteParams() on null in
  /var/www/craft/app/controllers/BaseController.php:37 Stack trace: #0
  /var/www/craft/app/framework/web/CController.php(308):
  Craft\BaseController->getActionParams() #1
  /var/www/craft/app/framework/web/CController.php(286):
  CController->runAction(Object(CInlineAction)) #2
  /var/www/craft/app/framework/web/CController.php(265):
  CController->runActionWithFilters(Object(CInlineAction), NULL) #3
  /var/www/craft/app/framework/web/CWebApplication.php(282):
  CController->run('renderError') #4
  /var/www/craft/app/framework/base/CErrorHandler.php(331):
  CWebApplication->runController('templates/rende...') #5
  /var/www/craft/app/framework/base/CErrorHandler.php(289):
  CErrorHandler->render('error', Array) #6
  /var/www/craft/app/etc/errors/ErrorHandler.php(149):
  CErrorHandler->handleError(Object(CErrorEvent)) #7
  /var/www/craft/app/framework/base/CErrorHandler.php(131):
  Craft\ErrorHandler->handleError(Object(CErrorEvent)) #8
  /var/www/craft/app/framework/base/CAp in
  /var/www/craft/app/controllers/BaseController.php on line 37

I honestly have no idea on what can be wrong. Any pointers would be very welcome...


texts: Correct behaviour for 'Login as user' when user cannot access CP?

texts:
A client uses the 'Login as user' behaviour to be able to see what users of the site are seeing, useful as it's an e-learning site and each user can see different content based on their progress. The users however, are only allowed to view the public site and not anything in the CP which means when the 'Login as user' is invoked the client is presented with the 'Unauthorized You don’t have the proper credentials to access this page' message.

Is this right? Looking through the code it seems the function _handleSuccessfulLogin() is called and if the user cannot access the CP then they should be redirected to the postLoginRedirect which in the case of this site is not set, so the user should be redirected to the homepage if I understand correctly.


texts: Saving some entries and a matrix field settings takes a very long time

texts:
I have some issues with saving fields and entries in Craft. For some reason, some entries, and a Matrix field I have, take approx. 1 to 2 minutes to save. There are then errors in my server log.

Initially I thought it was due to using Assets fields, as when I deleted those, the matrix field saved OK, and the entry. I recreated a field using Assets and when added some images to an entry, the issue came back.

It still saves, just takes 1 to 2 minutes.

For info, this is a site I copied from another site, then changed it's database, any paths/domains in config, then deleted a bunch of entries and assets we don't need on the new site, then the issue started to happen.

Here is the error in the server log. Online it says increate the timeout, but thats not a solution, it should not be taking this long in the first place.

[Fri Jul 08 16:00:24.139890 2016] [fcgid:warn] [pid 32671] (70007)The timeout specified has expired: [client xx.xx.xx.xx:50434] mod_fcgid: ap_pass_brigade failed in handle_request_ipc function, referer: http://mydomain.co.uk/admin/entries/homepage/2-homepage

Update: I have since copied the site again and gone through the same process as above, and its working OK now. So not urgent for me, but will leave this issue here nevertheless as its a serious issue of course.


texts: Live Preview only works for Entry variable?

texts:
Is there an undocumented shortcoming of Live Preview? Seems to only work where the entry variable is concerned.

I'm using a Structure section to create pages with "Chapters". The section (let's call it Areas) has a Max Level of 2. The idea is that level 1 entries  load a template that calls the content from all of that entry's children.

For instance, Areas looks like this in the CP:

Learning
-- Our Approach
-- Design Patterns
-- etc.

The front-end works just fine. /areas/learning loads the areas/_entry template where I call all of the entry's children and output their content to the page.

The issue is in Live Preview when editing a child entry, such as Our Approach. It looks like Live Preview only likes using the provided entry variable, but will not update anything nested, found in a loop, or otherwise loaded into the template's context.

For instance, this simplified template code, while rendering as expected, does not update in Live Preview:

{% if craft.request.isLivePreview %}
    {% set myEntry = craft.entries.slug(craft.request.getSegment(2)).first() %}
{% endif %}

{% set chapters = myEntry.children %}

{{ myEntry }}

{% for chapter in chapters %}

{{chapter}}

{% endfor %}

I renamed the entry variable as per this answer. Thoughts?


texts: Can I assign an image for a product type listing page?

texts:
I'm currently building a site using Craft and Craft Commerce. And when working between the two, I'm looking to make a page that shows all the products from a product-type, and have the header image change to reflect whichever product-type it is.

I know it is currently possible to make a category, assign an image to the category, and then add a category entry field to a product, allowing to organize products that way, but it seems terribly redundant, having to both put a product in a product-type, and then to also assign a category.

Is there any way to simply assign an image to the product type?


texts: How to create new variable from For Loop results

texts:
I need to get a list of all the "sizes" from my Table type field column. The list of sizes needs to be separated by a "|"... eg: small|medium|large

My Table type field name is "productAttributes" and the column in that field is "size".

How can I string together the results of a For Each loop to create a new variable with Twig?


texts:
I'm currently building a plugin that uses a table that contains rows with an 'active' field set to 1.

If an admin deletes a user from the system, I want to change this value to 0.

I found an 'onUserDelete' event documented but can't work out where or how to use it.

Any help would be greatly appreciated!

EDIT UPDATED:

I now have this code in the init() function of my plugin controller but deleting a user does not seem to fire the code:

    parent::init();

    craft()->on('users.onDeleteUser', function(Event $event) {
        $user = $event->params['user'];

        $userId = $user->id; // ???????

        $craft->memberships_membership->cancelMembershipById($userId);
    });

Any ideas?


texts: Is there a better way to localise channel url?

texts:
I'm working on a bilingual site (en and cy) and have a news channel with entry urls news/{slug} and the translated cy/newyddion/{slug}. Everything is working well with entries and if the url is accessed without the slug then a list of entries is displayed.

However, when accessing without the slug the translation of news is cy/news not cy/newyddion as required. If I attempt to access cy/newyddion I get a 404 not found error. I have tried different solutions such as adding files in templates/cy/newyddion but still get 404s.

The only way I've got it to work is by adding a new single section named news which has no content and loads the news index template and renaming the news section handle to avoid conflicts.

What I would like to know is if there is a better way of accomplishing this as it seems like a cumbersome way of doing it.


texts:
Very new to craft CMS, recently just installed XAMPP with php 7 and craft 3 and followed the getting started tutorial from Craft CMS. Then when I try to preview or open the page created from the tutorial, it gives me a 404 template not found error.
The error is as follows:
yii\web\NotFoundHttpException: Template not found: $PRIMARY_SITE_URL/$PRIMARY_SITE_URL/blog/this-is-my-blog in C:\xampp\htdocs\craft\vendor\craftcms\cms\src\controllers\TemplatesController.php:92
Stack trace:
#0 [internal function]: craft\controllers\TemplatesController->actionRender('$PRIMARY_SITE_U...', Array)
#1 C:\xampp\htdocs\craft\vendor\yiisoft\yii2\base\InlineAction.php(57): call_user_func_array(Array, Array)
#2 C:\xampp\htdocs\craft\vendor\yiisoft\yii2\base\Controller.php(181): yii\base\InlineAction->runWithParams(Array)
#3 C:\xampp\htdocs\craft\vendor\craftcms\cms\src\web\Controller.php(190): yii\base\Controller->runAction('render', Array)
#4 C:\xampp\htdocs\craft\vendor\yiisoft\yii2\base\Module.php(534): craft\web\Controller->runAction('render', Array)
#5 C:\xampp\htdocs\craft\vendor\craftcms\cms\src\web\Application.php(274): yii\base\Module->runAction('templates/rende...', Array)
#6 C:\xampp\htdocs\craft\vendor\yiisoft\yii2\web\Application.php(104): craft\web\Application->runAction('templates/rende...', Array)
#7 C:\xampp\htdocs\craft\vendor\craftcms\cms\src\web\Application.php(259): yii\web\Application->handleRequest(Object(craft\web\Request))
#8 C:\xampp\htdocs\craft\vendor\yiisoft\yii2\base\Application.php(392): craft\web\Application->handleRequest(Object(craft\web\Request))
#9 C:\xampp\htdocs\craft\web\index.php(23): yii\base\Application->run()
#10 {main}

and it looks like this:

I have followed all the instructions in the tutorial, and have created the _entry.twig in my templates/blog folder. Any help would be much appreciated


texts: How to get all users with active Commerce 2 subscription

texts: How do I get all the users with an active subscription in Commerce 2? I want to be able to filter entries by subscribed users.


texts:
I am trying to create a custom payment gateway by extending / adding it to Omnipay which is already implemented in Craft.

I have used the Ogone and other plugins as base, but I cant seem to get it working properly, probably because Klarna Checkout has quite a different flow than the ones I have tried to copy.

The flow I am trying to create:

The user have a cart with items, he press pay / checkout
On the payment page, he selects "Klarna Checkout" as payment option
At this point, we need to give Klarna some information about the customer and the items / price he is going to pay for along with some credentials. If all information is correct, Klarna returns a snippet (payment form) as HTML.
This snipped then needs to be embedded into the payment page (or redirected to a page that displays it).
When the user has payed using this payment form, klarna will redirect the user to a predefined endpoint, where we need to tell him, and Craft that the order is payed for.

What I am having problems with is the plugin itself, I have done the initial setup, I can choose it as a payment option and the code runs, but we are having problems with the sendData() function in purchaseRequest.php

This function seems to send data to an endpoint, and get some response, but exactly what that response should be, I cant seem to find out. Since Klarna Checkout do not have an endpoint, but is a PHP class / a set of functions we have imported with Composer, we cant just send data directly to Klarna, but need to create a order request using this class, and that class will then contact Klarna to get the snippet (payment form).

What I am having trouble with is figuring out what this function needs, if we need to use it at all, and how to work around it to display the payment form to the end user.

Any nudge in the right direction would be greatly appreciated!

Mathias


texts:
I have a Craft 3 beta project working fine on my local laravel/homestead box using nginx, however when I push to Heroku using their heroku-php-nginx build pack I get nginx (not Craft) 404s when trying to access the /admin area.

My Procfile looks like this:

web: vendor/bin/heroku-php-nginx -C deploy/nginx.conf public/

and my deploy/nginx.conf looks like this:

location / {
    try_files $uri @rewriteapp;
}

location @rewriteapp {
    rewrite ^(.*)$ /index.php?p=$1 last;
}


texts:
I am building a community website that currently have two user groups but it might increase so I am trying to automate everything. The current groups are: 'teachers' & 'candidates'.

I have a channel section named 'Community' and for this channel I have setup a category group called 'Community' that has two categories named as the user groups: 'teachers' & 'candidates'.

I am trying to display a list of all the registered users in a specific group as you are loading the category template.

This is the template that is being loaded:

{% extends "community/index" %}

{% set title = category.title %}

{% block main %}

{{ category.title }}

    {% set group = craft.users.group('{{ category.slug }}') %}

    {% for user in group %}

{{ user.name }}

    {% endfor %}

{% endblock %}

I was thinking that since the {{ category.slug }} has the same name as the user group, it can work but apparently not...

Can someone help me to understand how to relate the two?


texts: Can I cache an include for use elsewhere in a template?

texts:
I have an include that is doing a DB query (it generates a menu of entries) and that's used more than once on a template.

Is there a way I can cache the first parse for later use to cut down on DB hits?


texts:
It's the first time I'm using Wamp for local hosting my Craft website.
I've changed my Windows and Wamp apache host file for accessing my domainname instead of localhost. (ronvanderwerf.loc instead of localhost)

The front-end of the website looks fine:

(I'm getting a error because I still need to setup Craft)

The problem is, I can't access the admin panel. I get a 404 Not Found.

I've changed the directory order of my project for some hosting reasons:

My apache host file:

<VirtualHost *:80>
ServerName ronvanderwerf.loc
DocumentRoot c:/wamp64/www
<Directory  "c:/wamp64/www/">
    Options +Indexes +Includes +FollowSymLinks +MultiViews
    AllowOverride All
    Require local
</Directory>

My root htaccess file:

<IfModule mod_rewrite.c>
RewriteBase /

# Send would-be 404 requests to Craft
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/(favicon\.ico|apple-touch-icon.*\.png)$ [NC]
RewriteRule (.+) index.php?p=$1 [QSA,L]

I hope someone can help me.


texts:
Im making a plugin and have come to the stage where im making an edit form, for the plugin.

I would like the layout to look like this, with 2 columns and tabs above the left column.

My, question is what is the best way to achive this? currently im using extending _layouts/cp in my template, the page look like this.

thanks for your help


texts: Does a up to date boilerplate for Bootstrap 4 with live reload, sass and js build exist?

texts:
I'm pretty new to Craft, and a noob when it comes to build tools. Coming from WordPress I've been using Roots/Sage which is a starter theme with liveReload(browserSync), Bootstrap 4, SASS and JS compiling.

I've been googling for a long time now, and I haven't been able to find a good boilerplate for me to start doing development on.

What build tool isn't really important to me(WebPack, Gulp, etc.).

What I'm looking for is:

liveReload, CSS-injection or simple browserSync. So when I'm updating my SASS styles and Craft templates the site automatically updates.
Bootstrap 4
JS concatenation and uglyfing

Is there anything out there that fits my(and I know a lot of other developers) needs?


texts: Yearly/Monthy archive listing sorted by month

texts:
I've got a list of entries grouped by year which is working correctly except that the months are being output in the the reverse order.

This code outputs the years in the correct order but the months in reverse order:

    {# all entries sorted by year/month #}
     {% set allEntries = craft.entries.section('photoblog').limit(null).order('postDate desc') %}

  {% for year, entriesInYear in allEntries | group("postDate.year") %}

{{ year }}

        {% for month, entries in entriesInYear | group("postDate|date('F')" ) %}

{{ month }}&nbsp;({{ entries|length }})

        {% endfor %}

  {% endfor %}

If I change the '''.order('postDate desc') to asc then the months are in the correct order but the years are reversed. is there a way to get it so that the years are descending but the months are ascending?

screenshot of current code results


texts: Using Craft::import() to include external resource into the Craft Namespace

texts:
Looking at this answer, I suppose I am under the assumption that Craft::import() will take an alias, find the path, and import that class into the Craft namespace... which would be the benefit over simply using require_once().

Currently I import with:
Craft::import('plugins.myplugin.resources.chargebee.lib.ChargeBee', true);

Which works, however to use ChargeBee.php, I have to reference it from the global namespace. Not sure if this is the expected behaviour, but I would love to work within the Craft namespace if possible. Any help is greatly appreciated!


texts:
I am using the following form in Craft

    <form class="parts-search-block" action="{{ url('parts/results') }}" method="get">

        {#-- CATEGORY SEARCH --#}

            Search by Category:

            <select name="q">
                <option value="">--Select A Category--</option>
                <option value="Compressors">Compressors</option>
                <option value="Coolers">Coolers</option>
                <option value="Doors">Doors</option>
                <option value="Electrical">Electrical</option>
                <option value="Freezers">Freezers</option>
                <option value="Gaskets">Gaskets</option>
                <option value="GFV">GFV</option>
                <option value="Glass">Glass</option>
                <option value="Graphics">Graphics</option>
                <option value="Grills">Grills</option>
                <option value="Harnesses">Harnesses</option>
                <option value="Lighting">Lighting</option>
                <option value="Misc">Misc</option>
                <option value="Motors">Motors</option>
                <option value="Plastic">Plastic</option>
                <option value="Refrigeration">Refrigeration</option>
                <option value="Repair Panels">Repair Panels</option>
                <option value="Shelves">Shelves</option>
                <option value="Skins">Skins</option>
                <option value="Vendor">Vendor</option>
            </select>

        {#-- CATEGORY SEARCH --#}

            <button type="submit" class="cat-search">
                Begin Search
            </button>

    </form>

And calling it on the results page with...

    {% set query = craft.request.getParam('q') %}
    {% set entries = craft.entries.section('parts').search(query).order('score') %}

    {% for entry in entries %}

I am now using Craft Commerce and need to use the form to search my Commerce Products.  Is this possible?  Any suggestions?


texts:
I'm trying to add the ability to be able to align text left, right and center to my rich text fields. I have had a look into it and can only find a version which works perfect for body fields but not rich content.

The plugin I tried to use for this is here: https://github.com/elliotlewis/Redactor-Extras

I also looked at redactorstyles which did the same thing.

Is there possibly a way to apply this to all fields or is there another way I could go about it in redactors standard.json?


texts:
I am relatively new to Craft and I came across the lovely plugin Embedder and I have managed to make good use of it.

For some reason, I don't manage to apply the paramters. I have followed the advice on the following post but still, don't manage to apply the vimeo paramters.

My code looks like that:

{% set video = craft.embedder.url(entry.workVideo, {max_width:5000, max_height:8000, vimeo_color:ffffff}) %}

{% if video %}
    <div class="work_video">
        {{ video.embed_code }}
    </div>
{% endif %}

All is fine beside the fact that the vimeo_color parameter doesn't work. I have tried other parameters like vimeo_autoplay:true also with no success.


texts: Best practices in debugging an 'Unknown error'

texts:
How can I debug an 'Unknown error' message that I get with every request in Craft?
Logging says:

******************************************************************************************************
2015/01/16 14:03:36 [error] [exception.Craft\HttpException.503] exception 'Craft\HttpException' in /storage/www/imagecenter/acceptance/craft/app/etc/web/WebApp.php:873
Stack trace:
#0 /storage/www/imagecenter/acceptance/craft/app/etc/web/WebApp.php(218): Craft\WebApp->_processUpdateLogic()
#1 /storage/www/imagecenter/acceptance/craft/app/framework/base/CApplication.php(180): Craft\WebApp->processRequest()
#2 /storage/www/imagecenter/acceptance/craft/app/index.php(62): CApplication->run()
#3 /storage/www/imagecenter/acceptance/htdocs/index.php(16): require_once('/storage/www/im...')
#4 {main}
REQUEST_URI=/index.php?p=admin/actions/users/getAuthTimeout&dontExtendSession=1
HTTP_REFERER=http://acceptance.imagecenter.blinkdev.nl/index.php?p=admin/entries
---
2015/01/16 14:03:36 [error] [application]

******************************************************************************************************


texts: EagerLoading on category pages with different product types

texts:
I have a category template like so;

{% extends '_layouts/_site' %}

{% set products = craft.products
  .with( [
  'department',
  'productImage',
  'finish',
  'pcd',
  'variants',
  'thread',
  'seat',
  'hexHead'
])
  .orderBy('title asc')
  .relatedTo(category)
  .all() %}

{% block content %}
  <div class="flex flex-wrap px-12">
    {% for product in products %}
      {% switch product.type %}

      {% case product.type %}
        {% include "shop/products/_teasers/" ~ product.type %}

      {% default %}
        none

      {% endswitch %}
    {% endfor %}
  </div>
{% endblock %}

At the moment this is eagerLoading all the different fields across all the different products and this is only 2 product types. There will be more to follow.

For Example.
Wheel Spacers only require these fields:
'department',
'productImage',
'pcd',
'variants',

Bolts only require these fields:
'department',
'productImage',
'variants',
'thread',
'seat',
'hexHead',
'finish'

So depending on the product this adds a few additional calls. Probably not an issue in this instance, but I wondered if there is a way to only EagerLoad the right fields for the right products?

Thanks,


texts: How would I write this differently to make it compatible with MYSQL 5.7

texts:
There is an issue with using unique => true in defining an attribute as a primary key when using MYSQL 5.7.*.

protected function defineAttributes()
{
    return array(
        'eid' => array(AttributeType::Number, 'unique' => true, 'column' => ColumnType::PK)
    );
}

According to my setting this error should not occur. Here is the error.

CDbCommand failed to execute the SQL statement: SQLSTATE[42000]: Syntax error or access violation: 1171 All parts of a PRIMARY KEY must be NOT NULL; if you need NULL in a key, use UNIQUE instead

Here is the SQL executed.

system.db.CDbCommand.execute(CREATE TABLE `craft_venti_events` (
    `eid` int(11) NOT NULL AUTO_INCREMENT NULL,
    `eventid` INT(10) NULL,
    `startDate` datetime NULL,
    `endDate` datetime NULL,
    `allDay` INT(10) NULL,
    `repeat` INT(10) NULL,
    `rRule` VARCHAR(255) NULL,
    `summary` VARCHAR(255) NULL,
    `isrepeat` INT(10) NULL,
    `locale` VARCHAR(255) NULL,
    `dateCreated` datetime NOT NULL,
    `dateUpdated` datetime NOT NULL,
    `uid` CHAR(36) NOT NULL DEFAULT 0,
    PRIMARY KEY (eid)
) ENGINE=InnoDb DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci)


texts: favicon.ico throwing 404 TemplateLoader exception

texts:
This is my first Craft site, I inherited it. I've manually set a link tag to my favicon in my templates/_layouts/_header.twig file:

Everything else in that /dist/img folder renders fine - .png, .jpg, .gif. Everything inside the other /dist subdirs renders fine - /css, /js, /pdf... What am I missing? Going directly to the favicon.ico url, I get a blank page with this:

"Unable to find the template â€œ_layoutâ€."

I do not understand the routing - but that feels like a red herring here anyway. I don't have any routes set up in the cms, and everything else in the /dist directory renders fine when I link directly to it. Thanks for any ideas.


texts: Update an order custom field after order complete in Craft 3

texts:
I am trying to update an order's custom field after order complete.
I set it like this in my plugin:

Event::on(Order::class, Order::EVENT_AFTER_COMPLETE_ORDER, function(Event $e) {
        $order = $e->sender;
        $order->setFieldValue("customFieldHandle", "My value");
    });

But it is not working. I guess I used the wrong method to do it.


texts:
I'm attempting to update a craft 2 site to craft 3.

Following these instructions, I used composer to install Craft:
https://docs.craftcms.com/v3/upgrade.html#if-you-want-your-directory-structure-to-resemble-a-new-craft-3-project%E2%80%A6

I have got to the stage where I go to the domain.com/admin but I am getting the error:

  The requested URL /admin was not found on this server.

Thanks for any help - at a dead end I am sure its something v simple!


texts:
I'm running Craft CMS 2.6.2972 so I had to use the older Element API plugin.

I have downloaded the zip and then copied just the "elementapi" file in the zip to the plugin's folder.

Then I installed the plugin in the admin panel.

Then I made a file craft/config/elementapi.php with the contents

<?php
namespace Craft;

return [
    'endpoints' => [
        'news.json' => [
            'elementType' => 'Entry',
            'criteria' => ['section' => 'news'],
        ]
    ]
];

But if I hit the URL <myserver>/api/news.json then I get the following error:

2017/05/12 17:31:47 [error] [exception.Craft\HttpException.404] exception 'Craft\HttpException' in C:\inetpub\wwwroot\craft\app\controllers\TemplatesController.php:59 Stack trace:
#0 [internal function]: Craft\TemplatesController->actionRender('api/news.json', Array)
#1 C:\inetpub\wwwroot\craft\app\framework\web\actions\CAction.php(109): ReflectionMethod->invokeArgs(Object(Craft\TemplatesController), Array)
#2 C:\inetpub\wwwroot\craft\app\framework\web\actions\CInlineAction.php(47): CAction->runWithParamsInternal(Object(Craft\TemplatesController), Object(ReflectionMethod), Array)
#3 C:\inetpub\wwwroot\craft\app\framework\web\CController.php(308): CInlineAction->runWithParams(Array)
#4 C:\inetpub\wwwroot\craft\app\framework\web\CController.php(286): CController->runAction(Object(CInlineAction))
#5 C:\inetpub\wwwroot\craft\app\framework\web\CController.php(265): CController->runActionWithFilters(Object(CInlineAction), Array)
#6 C:\inetpub\wwwroot\craft\app\framework\web\CWebApplication.php(282): CController->run('render')
#7 C:\inetpub\wwwroot\craft\app\framework\web\CWebApplication.php(141): CWebApplication->runController('templates/rende...')
#8 C:\inetpub\wwwroot\craft\app\etc\web\WebApp.php(290): CWebApplication->processRequest()
#9 C:\inetpub\wwwroot\craft\app\framework\base\CApplication.php(185): Craft\WebApp->processRequest()
#10 C:\inetpub\wwwroot\craft\app\index.php(62): CApplication->run()
#11 C:\inetpub\wwwroot\public\index.php(14): require_once('C:\\inetpub\\wwwr...')
#12 {main} REQUEST_URI=/api/news.json
---

What might be wrong?

This is running on IIS and I've added .json to the mime types for the site.

This error is the same error as an unhandled link/route. So seems like it's not picking up the config or I have the wrong URL. The plugin did install ok.


texts: How do I remove segment 1 in my URL AND get the parent URI?

texts:
I have a structured group of pages in a static channel that I would like to display without "static" in the URL and show the parent URI. This is my structure:

patients-visitors
---- our-stories
-------- share-your-story
support-groups
---- healing-yoga

All of these entries are in a "static" channel. When I roll over the link in the Control Panel, my link look like this:

https://www.website.com/static/patient-visitors
---- https://www.website.com/static/our-stories
-------- https://www.website.com/static/share-your-story
https://www.website.com/static/support-groups
---- https://www.website.com/static/healing-yoga

However, I want the links to look like this:

https://www.website.com/patients-visitors
---- https://www.website.com/patients-visitors/our-stories
-------- https://www.website.com/patients-visitors/our-stories/share-your-story
https://www.website.com/support-groups
---- https://www.website.com/support-groups/healing-yoga


texts: Freeform: Change field conditions between multi-page forms

texts:
I'm trying to only show some fields on Page 2, if a condition from a <select> box is met on Page 1. However, when I add Field Rules, I only have access to fields from the same page of the form.

I can manually override this in the templates, but, is there not a way to bring in fields from another page for a condition to be true/false? For instance: if this is a sign up form, and there are different account types to choose from, can a checkbox group only appear on Page 2 if that account type was chosen on Page 1?

Note: I'm running Freeform 3.4.0 on a Craft 3.3.2 install.


texts: Craft unable to determine if an update is available?

texts:
I just cloned a production site to run in a local environment to test and make sure the site was compatible with PHP7 in preparation for a production server upgrade. For the most part, it seems to have migrated without any issue, except for when I try to check for updates, I get the error: Craft is unable to determine if an update is available at this time. Similarly, the edition button at the bottom of the dashboard gives the error: Craft is unable to fetch edition info at this time.

I tried deleting my license key and clearing caches to no avail, but then I checked logs and noticed this error had been showing up:

2018/02/26 23:50:58 [error] [application] Error in Craft\Et::phoneHome. Message: [curl] 35: Unknown SSL protocol error in connection to elliott.craftcms.com:443  [url] https://elliott.craftcms.com/actions/elliott/app/checkForUpdates

I can’t seem to find any other mention of this issue on StackExchange or elsewhere - any ideas? Thanks so much in advance.


texts: Using relative paths for assets for heroku deployment

texts:
I cant quite wrap my head around the way the way the heroku file system works, so I'd like to use relative paths for my asset File System Paths. Is that even possible?

I've tried to use CRAFT_BASE_PATH in the general settings file to define an environmental variable, but no real luck getting my assets folders to be recognized.


texts: How can I tell if a variable is an array or an entry/element query?

texts:
We have some components that are used to build pages, like normal, and some where we hydrate them with other data, so we are passing in arrays instead of entries.

If something is essentially an element, we need to do a .all() to not have deprecation warnings, but if you do that on an array, you get errors. I've read through A similar question with element queries vs arrays but since I'm not explicitly running a query on the page, this isn't quite applicable.

Both arrays and objects are iterable so that can't distinguish it. Ideally I'd like to do something like this:

{% if props.cards is array %}
    {% set cardArray = props.cards %}
{% else %}
    {% set cardArray = props.cards.all() %}
{% endif %}
{% for card in cardArray %}
...

Obviously, I'd be fine swapping the if/else conditions for the right test case


texts:
Is there a way to exclude a User Group from a sale?

We have a trade user account that applies a flat 20% discount across all products but we're trying to run a different sale for all customers on a few products.

The issue is any customer within the trade user group is getting the flat 20% discount and the further 25% on these specific products.

Thanks for any help.


texts: Have SEOMatic render a custom SEOMatic field

texts:
I've got a few pages on my site that are not content managed.

I don't want to create entries for these pages, but I do want the SEO for these pages content managed.

My solution here has been to set up a global matrix block, with each block having a handle and seomatic field.

This way the SEO for these non-entries is content managed, but the pages themselves aren't.

Is there a way for me to tell SEOMatic to render a custom SEOMatic field? I tried {% do seomatic.meta.setAttributes(myCustomSeoMetaField) %} but had no luck, and can't see anything in the docs.

PS the reason I want to do it this way is partly because the Global/default SEOMatic settings didn't seem to be coming through on a non-entry, so I was hoping using some sort of default hook will take care of this also.


texts: Sprout reports options can't find form fields

texts:
I'm getting an error on my options template when I run the report, the sprout from can't find the form fields template and I get this error

  Unable to find the template “_includes/forms” in
  "__string_template__1e75d07f7afb92cfc030941cdd0c214a5067c25743f143e36dcfc3dd77a06f62"
  at line 1.

When I remove the import I get this error

  Variable "forms" does not exist in
  "__string_template__68fd366166a1d3cc8e58752e3634a261ca9faaa526e284d487e82cc2434316c9"
  at line 2.

Here is my options.twig

{% import '_includes/forms' as forms %}

{% set limitByDateRange = settings.limitByDateRange ?? false %}

{{ forms.lightswitchField({
    label: 'Filter By Date Range'|t,
    name: 'limitByDateRange',
    on: limitByDateRange,
    value: 1,
    toggle: 'toggle-dateRangeFields',
    first: true
}) }}

    {{ forms.date({
        label: 'Start Date'|t,
        id: 'datetimeStartDate',
        name: 'datetimeStartDate',
        value: settings.datetimeStartDate is defined ? settings.datetimeStartDate : now|date_modify('-1 month')
    }) }}

to

    {{ forms.date({
        label: 'End Date'|t,
        id: 'datetimeEndDate',
        name: 'datetimeEndDate',
        value: settings.datetimeEndDate is defined ? settings.datetimeEndDate : now
    }) }}

{%- js %}
    $('#options-datetimeStartDate-date').datepicker($.extend({
        defaultDate: new Date({{ now.year }}, {{ now.month-1 }}, {{ now.day }})
    }, Craft.datepickerOptions));

    $('#options-datetimeEndDate-date').datepicker($.extend({
        defaultDate: new Date({{ now.year }}, {{ now.month }}, {{ now.day }})
    }, Craft.datepickerOptions));

    $('#modify-options-panel').attr('style', null);
{%- endjs %}

I also already tried to copy the examples templates from the plugin folder and I get the same error.
Does anyone have an idea what could be wrong? I appreciate any help, thanks.


texts: Redactor or another HTML editor that can inherit actual page styles?

texts:
is it possible for Redactor or any of the other editors to actually inherit the styles from the (front end) page it is editing?  My client has bootstrap columns etc and the pages have some elements with backgrounds and i wanted to make the content look more like the actual website they are editing rather than one long block of text.

I hacked around in the Redactor CSS files and i can kind of get it working by importing my sites stylesheets into the Redactor one but then that affects the whole Entry page's styles and also hacking in Redactors styles doesn't seem the best.

I do realise probably the best way to do this properly would be to create blocks for each type of content with Matrix (2 col or 1 col etc) and recreate all page elements but the site is coming from another system with lots of static pages and i just wanted my client to have a simple way to edit the existing content.

Anyone any ideas if this is possible at all?

Malcolm


texts: File upload error. Cannot upload .key (keynote) files

texts: I am trying allow users to upload keynote and powerpoint files. Powerpoint works fine. Keynote fails. I do not have any asset type restrictions in place. Why am I unable to upload asset type .key?


texts: Why am I getting only one result with "craft()->db->createCommand()"?

texts:
Why am I getting only one result with the following query?

$query = craft()->db->createCommand();
$entryRecord = $query->select('craft_content.field_releaseDate, craft_content.title, craft_entries.id, craft_entries.dateCreated')->from('content')->join('entries', 'craft_content.elementId = craft_entries.id')->where('craft_entries.sectionId=2')->queryRow();

Also the documentation says that the table prefix isn't required, but this doesn't work most of the time, weird.


texts: How to loop through matrix block fields and pull out handle and content?

texts:
Ok this is similar to a previously asked question How to display all fields belonging to current entry?

However I'd like to extend this so that it deals with matrix entry types. I have the following but I just need to know how to loop through all the blocks and pull out each blocks entry field handle and content. Any help appreciated.

{# loop through the fields in the entries fieldLayout Model #}
{% for fieldLayoutField in entry.getFieldLayout().getFields() %}

    {# get the field Model from the fieldId #}
    {% set field = craft.fields.getFieldById(fieldLayoutField.fieldId) %}

    {% if field.type == 'Matrix' %}
        {% set matrixHandle = field.handle %}
        {% for field in matrixHandle %}
            ...loop through matrix blocks fields and pull out field handles and content...
        {% endfor %}
    {% else %}
        {# print the field handle and the field content  #}
        {{ field.handle }} : {{ entry.getContent()[field.handle] }}
    {% endif %}

{% endfor %}


texts:
Is anyone aware of a solution for using Craft user data with something like MailChimp? This is a very simple use case of sending newsletters/announcements to registered Craft users. Would be even better if it could be by User Group, but I will settle for all users.

I understand that Sprout Email can connect to MailChimp mailing lists, but that does not address the issue of having to manually sync the Craft User data with a MailChimp list.

Thanks for any suggestions!


texts: How can I get the last Matrix block of a certain type?

texts:
I have a Matrix field with some different block types; images, videos, text, etc. When I loop over the blocks I have some extra code (facebook and twitter sharing, back-button, etc) that should only be output for the last "text" block.

How can I know, inside the loop, if the current block is the last of its type?


texts: How to place assets in plain text fields?

texts:
In ExpressionEngine i had a matrix field for images (assets) that i used in my entries.

I was using NSM Transplant and in my entries i could use {bild-1}, {bild-2} and so on wherever i wanted a image in my content.

The code is:

{produkte_ma_text_bilder}

  {exp:nsm_transplant:content id="bild-{row_count}"}

    {exp:ce_img:make src="{produkte_ma_text_bild}" max_height="{produkte_ma_text_bild_height}"}{/exp:ce_img:make}

  {/exp:nsm_transplant:content}

{/produkte_ma_text_bilder}

The matrix field looks like this:

When creating an entry it looks like this:

It seems like in Craft you need Super Table to do this.
But i can't figure out the code.

The solution is:

{% set mainText = entry.mainText %}

{% for row in entry.textImages.all() %}
    {% set findImage = '%%image' ~ loop.index ~ '%%' %}

    {% set replaceImage %}

    {% endset %}

    {% set mainText = mainText | replace(findImage, replaceImage) %}

{% endfor %}

{{ mainText | raw }}

Thanks to Andrew Welch from https://nystudio107.com/


texts: Change default status of entry publication (Lightswitch 'Status')

texts:
When I write an article and save it, I want to verify my text.
I don't want publish my article immediately.
If I'm tired, I sometimes forget to disable the Lightswitch 'Status'.
So, how can I disable it by default?


texts: Setting up multiple category listing pages on site with multiple locales

texts:
I’m having trouble setting up an additional category listing page from the one I have set with the Category URI Format and Template settings in my Category Site Settings. Specifically, I’m having trouble getting it to work on my site which has two locales.

I have one category group called “practices” and one structure section-type called “people.”  I’m trying to create two different pages that each loops through all the entries for a particular category.

In other words, domain.com/people/practices/categoryA and domain.com/people/foo/practices/categoryA would both display all the “people” entries that belong to categoryA.

For my “practices” category group, I have the Category URIs to be people/practices/{slug} and the template to be people/_practices. Everything on this category listing page at domain.com/people/practices/categoryA works as intended.

I can also get the category listing page at domain.com/people/foo/practices/categoryA to work by using the last segment (which would be the category slug) and setting the category object by passing in the category slug like this:

{% set categorySlug = craft.app.request.segments|last %}
{% set category = craft.categories.slug(categorySlug).one() %}

However, this category listing page is throwing an error when I’m using it with my language switcher code, which uses:

{% if category is defined %}
    {% set entry = category %}
{% endif %}

{% set supportedSites = entry.getSupportedSites %}

{% for siteForEntry in supportedSites %}
  {% if siteForEntry | length == 1 %}

    {# if category #}
    {% set site = craft.app.getSites.getSiteById(siteForEntry) %}
    {% set entryForOtherSite = craft.categories.id(entry.id).site(site).one() %}

  {% elseif siteForEntry | length == 2 %}
    {# if standard entry #}
    {% set site = craft.app.getSites.getSiteById(siteForEntry.siteId) %}
    {% set entryForOtherSite = craft.entries.id(entry.id).site(site).one() %}
  {% endif %}

  {% if site.id == entry.siteId %}
      {# This is the current language, mark it as active and don't retrieve its url #}

{{site.name}}

  {% else %}
      {# if it's not the current site, get the entry for this site #}

{{site.name}}</a

  {% endif %}

{% endfor %}

Specifically, I get the “Variable ‘entry’ does not exist” error. I’m not sure why I’m getting this error because I’m setting the “entry” variable with the “category” variable. This works with domain.com/people/practices/categoryA, but it’s not working for the other category listing page.

        {% if category is defined %}
            {% set entry = category %}
        {{ entry.id }}
        {% endif %}

Not sure what to do. I also set a route so that domain.com/people/foo/practices/{slug} loads the people/_practices template, but it still doesn’t work.


texts:
I use template inheritance:

In _layout.html every other template is loaded with {% block content %}{% endblock %}

The problem: _layout.html never reloads. I changed the CSS path in the head tag of _layout.html but I never see the change reflected. Why?

restarted MAMP (cache is already disabled)
restarted computer
emptied every cache I know of
cache tags aren't used
used all different browsers
deleted the storage/runtime folder

The above steps have no effect, and any changes on _layout.html don't appear to do anything. Why might this be?


texts:
I keep getting the error:

mydomain.com/craft/storage/runtime isn't writable by PHP. Please fix that.

I am running Redhat, and have set the folder permissions to 777, any ideas?

Thanks in advance.


texts:
With FeedMe I'm importing some data and one of them I get is a complete array that is stored a plain text field.

This array is a bunch of car options what I want to add in a table like this:

{% set options = entry.optionsAndAccessoiries %}

output {{ options }} = ["Achterbank in delen neerklapbaar","Airbag bestuurder","Airconditioning","Anti-slipregeling","Antiblokkeersysteem","Centrale deurvergrendeling afstandbediend","Elektrisch bedienbare ramen voor","Elektrisch verstelbare buitenspiegels","Getint glas","Hoofdsteunen achter","Hoofdsteunen voor","In hoogte verstelbare bestuurdersstoel","Metallic lak","Middenarmsteun voor","Mistlampen voor","Radio\/CD speler","Startonderbreker","Stoelverwarming bestuurder","Stoffen bekleding","Stuurbekrachtiging","Trekhaak","Verstelbaar stuurwiel"]

{% set items = options %}

  {% for row in items|batch(3, 'No item') %}

    {% for column in row %}
    {{ column }}
    {% endfor %}

  {% endfor %}

But this is causing an error:

array_chunk() expects parameter 1 to be array, string given

Who can help me out to point me in the right direction?


texts: Why does a Element Criteria Model Query with Strings on a custom element type not filtering?

texts:
having issues doing the classic element type query, works fine with numerical criteria (id, price etc.) but fails on strings, (code, name etc.). It just returns all elements.

$criteria = craft()->elements->getCriteria('GoWander_Trip');
$criteria->code = $code;
return $criteria->find();

Is there any step im missing in the setup of the element itself (code below)?

public function modifyElementsQuery(DbCommand $query, ElementCriteriaModel $criteria) {

    $query
        ->addSelect('
            trips.code,
            trips.templateId,
            trips.start,
            trips.end,
            trips.assetId,
            trips.price,
            trips.spots,
            trips.spotsAvailable,
            trips.elements,
            trips.shortDescription
        ')
        ->join('gowander_trips trips', 'trips.id = elements.id');

    if ($criteria->templateId) {

        $query->andWhere(DbHelper::parseParam('trips.templateId', $criteria->templateId, $query->params));
    }

}


texts: Ability to SUM() or GROUP BY from the template or ElementCriteriaModel

texts:
After twitter conversation with Brandon Kelly, is it possible to implement something similar to the following?

craft.entries.section("mySection").sum("myCustomField")


texts: Commerce: Template error: “Variable "option" does not exist

texts:
I am getting this error when trying to send a confirmation email to the user.

Template error: “Variable "option" does not exist

If I remove every bit of markup from my email template, and literally only have
Hello World
 I get an email.

I am able to click the "Download Receipt" link, and everything works great.

When I output the option variable: {{ option }}:
When I click on the "Download" link, I see receipt.

I am using the default template that ships with commerce, with the addition of a jpg header image. At the bottom of the template is this:

...
{% endset %}

{# Use the option param passed into the pdf template to show different
   order pdf's depending on the context #}

 {% switch option %}
 {% case "receipt" %}

Receipt for Order #{{ order.number[:7] }}

    {{ orderTable }}
{% case "ajax" %}

NA

{% default %}
    {{ orderTable }}
{% endswitch %}

So clearly it has something to do with option not getting set. I'm not sure where I might have un-done setting that variable.

Any suggestions are greatly appreciated!


texts: How to parse environment variables and globals from a field

texts:
I want the ability to parse environment variables such as {siteName} and globals from channel fields, for example a rich text field.

I have been using {{ include(template_from_string(entry.fieldName)|raw) }}, but this is not suitable because it gives authors the full power of twig.
Brandon Kelly pointed out that using the replace filter can work {{ entry.fieldName|replace('{siteName}', siteName)|raw }}

Using a macro I can make this manageable.

I would like the ability to use globals too, what is the best way to have all globals being options to replace or using another method?

Would having 20 possible variable options to replace cause any issues, I would be calling this 3-4 times in a template.


texts: Revolution Slider and Craft CMS conflict on placeholders

texts:
Revolution Slider is using Placeholders like this {{param1}}.
This is conflicting with Twig's variables.

Is there a workaround that Twig will ignore this for example?


texts: How do I fix getTemplatesPath() / setTemplatesPath() deprecation errors?

texts:
After updating to Craft 2.6.2778, my plugin is causing these deprecation errors:

PathService::getTemplatesPath() has been deprecated. Use TemplatesService::getTemplatesPath() or TemplatesService::getTemplateMode() instead.
PathService::setTemplatesPath() has been deprecated. Use TemplatesService::setTemplatesPath() or TemplatesService::setTemplateMode() instead.

How do I fix these?


texts:
I apologize in advance if I am just overthinking this and missing something obvious (feels like I am). I have a situation on a category page where I am wanting to override a block in the document this one is extending, but only if the category is equal to a specific value ('Smith' in this case). If I put the conditional outside the block definition, I keep getting an internal server error. But if I put it inside the block definition, then it will override the block on every category page, not just this one. I'm trying to avoid having multiple templates and instead just hide one nav section on one category page. Please let me know if you need any more information. Thanks in advance for any advice!!

Here are the two versions of the code that I have tried. First gives the Internal Server error, second overrides the block for all pages.

{% if category.title == 'Smith' %}
  {% block nav %} {% endblock %}
{% endif %}

{% block nav %}
  {% if category.title == 'Smith' %} {% endif %}
{% endblock %}


texts: I'm getting a 'couldnt save entry' error for a single but all required fields etc are filled

texts:
I'm getting a couldnt save entry error, but all the fields are filled and there are no additional errors or input highlighting. Has anyone has this problem? Tried clearing the cache and checking the logs but nothing, I was able to fill it in fine before but no longer.

This is a screen shot of the error.

Any help would be appreciated.

Thanks!


texts: Is it possible to change the default search result order (CP)?

texts:
Craft version: 3.3.19

Is it possible to set default order for CP entry search results? The default is search score but for instance for blog entries, news, etc. the date of the entry is usually more important than the relevance. I need to overwrite the default behaviour somehow.

Thx


texts: Forgotpassword: wrong url in reset password e-mail

texts:
I have a forgotpassword form on my front-end. This works and generates reset password e-mails. But the reset url leads not to the front-end, but to the back-end.

What I've already tried to fix the problem:

setpassword template on the front-end (setpassword.html)
route setpassword to setpassword.html

What am I doing wrong?

Thanks for your help!


texts: Trying to automatically add a product in Commerce

texts:
I'm trying to add a product to a cart (and emptying the cart first) if a user just visits a template. My goal is to make a one-page checkout: so I want the address info on the product page itself. This is what I have so far. I thought the first line would make a cart if there is no cart yet, but it seems nothing happens. (cart.id = null)

{% set cart = craft.commerce.carts.cart %}
Cart ID is {{ cart.id }}
{% do cart.setLineItems([]) %}
{% set lineItem = craft.commerce.lineitems.resolveLineItem(cart.id, product.id, [], 1, '') %}
{% do cart.addLineItem(lineItem) %}


texts: How do I output the siblings position number?

texts:
This question is related to this thread.

{% for sibling in entry.getSiblings() %}
{{ sibling.title }} {{ sibling.orderNumber }}
{% endfor %}

I thought you could pick this out of the ElementCriteriaModel, but that doesn't seem to be possible/available. Twig's for loop won't work either.

The result I am looking for is to echo the order number of the siblings in a structure.

Parent
Child order number 1
Child order number 2
Child order number 3


texts: How do I conditionally set active state in category navigation?

texts:
Here is the code I am trying to use to set an active state for category navigation:

    {% for category in categories %}

{{ category.title }}

    {% endfor %}

It seems that the conditional can't check against the category.slug output. Is this the case? What would be a better approach?

Any help is appreciated.


texts: Getting products with Craft 3 and Craft Commerce 2

texts:
I've never had success using Craft 3 with Commerce 2 beta. I always get an error that ".find()" is not recognized, and ".all()" doesn't work either.

My latest attempt has given me this error:

  Twig Runtime Error – Twig_Error_Runtime
  Calling unknown method: craft\commerce\services\Products::type()

The line in question is this one:

{% set silentItems = craft.commerce.products.type('silentAuctionItems').find() %}

If I delete

.type('silentAuctionItems').find()

the error doesn't come up, but I don't get any products displaying.

I've searched through the Commerce documentation, and I can't find anything about this problem.

Thanks for any help you can provide!


texts: Mixed relation criteria operator in Element API

texts:
I have a bit complex filtering system that I try to replicate using Element API.

So far I have this which works to a degree:

Example url: training.json?reg=124&cat=99&prod=129&erp=

'criteria' => [
            'section' => 'resources',
            'search' => (craft()->request->getParam('q') ? craft()->request->getParam('q')."*" : ''),
            'relatedTo' => [
                'and',
                craft()->request->getParam('reg'),
                (craft()->request->getParam('cat') ? craft()->request->getParam('cat') : craft()->request->getParam('reg')),
                (craft()->request->getParam('prod') ? craft()->request->getParam('prod') : craft()->request->getParam('reg')),
                (craft()->request->getParam('erp') ? craft()->request->getParam('erp') : craft()->request->getParam('reg')),
            ],
  ...

First of all, I don't know how to deal with optional parameters, I've solved this by re-using the only required parameter - reg. It works, but it's not nice, any help here would be appreciated.

The real issue though is that I need the reg parameter to be an array with all the elements in the array having OR operator.

So basically:

Example url: training.json?reg[]=124&reg=[]=123&cat=99&prod=129&erp=

(reg[0] OR reg[1]) AND cat AND prod AND erp

Is there any way I can achieve this in element API? I've tried something in the lines of the following, but with no luck.

'relatedTo' => [
     'and',
      ['targetRegions' => ['or', 124, 99]],
      105,
      231,
 ],


texts: Can guests upload files to assets in an entry form?

texts:
I'm using Craft Guest Entries plugin and the Entry Form technique elsewhere on my site. I'm currently trying to add a file upload to it. The entry is publishing but nothing is making it to assets.

Here's the code:

<form class="ajax-form" method="post" action="" enctype="multipart/form-data" accept-charset="UTF-8">
    <input type="hidden" name="action" value="guestEntries/saveEntry">
    <input type="hidden" name="sectionId" value="17">
    <input type="hidden" name="enabled" value="1">
    <input type="hidden" name="fields[whitepaperCategory]" value="{{entry.title}}">

    Name
    <input type="text" id="name" name="title" required>

    Email Address
    <input type="email" id="email" name="fields[email]" required>

    Resume and Cover Letter (.pdf)

        Upload Resume and Cover Letter
        <input type="file" id="resume" name="fields[resumes][]" class="upload" multiple>

    <button type="submit" class="btn btn-submit">Submit</button>
</form>

Is there anything obvious I'm missing?


texts: craft.request.getQuery returns empty on multi lingual site

texts:
I have the strangest bug. I have a site with two languages, Norwegian and English. In my code i check for craft.request.getQuery('prodid'). Locally in Apache this works fine with both language URLs, but in production on Nginx, it only works on the Norwegian version (the main language).

The URLS looks like this

http://onepark.no/leie-parkering/paleet?prodid=1
http://onepark.no/en/rent-parking/paleet?prodid=1

For the english URL (the second) craft.request.getQuery('prodid') returns an empty string. For the Norwegian URL it returns "1".

Nginx rewrite code:

location / {
    try_files $uri $uri/ @rewrites;
  }

location /en/ {
   try_files $uri $uri/ @enrewrites;
  }

location @enrewrites {
    rewrite ^/en/(.*)$ /en/index.php?p=$1? last;
  }

location @rewrites {
rewrite ^(.*) /index.php?p=$1 last;
}


texts: What is the current landscape regarding e-commerce plugins for Craft?

texts:
I'm developing an online store. The store needs to be seamlessly integrated with all of the editorial content on both the front and back-end. Craft is obviously a perfect candidate for the editorial content, but at this moment the options for e-commerce plugins are limited.

What e-commerce options are currently available for Craft?


texts: In plugin combine a returned entry with custom table data

texts: In a plugin I am returning entries from a section. Can I combine a returned entry from that section with data from a custom table into one model for output?


texts:
I would like "buy" product without the use of a gateway. The reason for this is that the customer will have the option to apply for a loan at the bank and when the loan it approved we'll get a callback and then the order will be executed.

Does anyone have a good idea for this solution?


texts: GraphQL: Prevent users seeing entries authored by other users

texts:
How can we filter what entries are returned by a GraphQL query so that users cannot see entries authored by other people?

For example, Editors can access everything but Writers can only access their own entries.


texts:
After endless trial and error I figured out the right syntax for a simple one level navigation.

{% set navi = craft.entries.section('not projekteintrag' ) %}
{% for entry in navi.order('id asc') %}

{{ entry.navigationTitle }}

{% endfor %}

Is there a parameter to just trigger single pages? Right now I grabbed the singles with filtering the entries.
What is the difference between writing the upper syntax and:

-

{% for entry in craft.entries.section('not projekteintrag' ).order('id asc') %}

{{ entry.navigationTitle }}

{% endfor %}


texts: Which is the best place to learn Craft CMS with tutorials?

texts: I am new to craft cms and would like to learn craft cms with tutorials. I am ready to pay for the subscription but would like to know is there any best place where I can learn the craft ?


texts:
I created a plugin for Craft 3 at pluginfactory.io.

I want to call it in my template variable

public function exampleVariable()
{

    // hint   AdminBar::$plugin->editLinks->exampleService()
    //$result = FacebookPageConnector::$plugin->eventsService->fetchEvents();
      $result =  FacebookPageConnector::$plugin->facebookPageConnectorEventsService->exampleService();

    //$result = FacebookPageConnector::$plugin->eventsService->fetchEvents();
    return $result;
}

But whatever I try to name my service, I get an exception like this:

  Getting unknown property: boscho87fbconnector\facebookpageconnector\FacebookPageConnector::facebookPageConnectorEventsService

What are the correct naming conventions?

I saw an example here: https://github.com/wbrowar/craft-3-adminbar/blob/master/src/services/EditLinks.php#L48,  but this did not work for me.

But when I call the predefined service from the pluginfactory: FacebookPageConnector::$plugin->facebookPageConnectorService->exampleService(),  it works fine .

here images with my code


texts:
I get "Variable career does not exist". I'll just go straight to the code example...

{# Set ECM and get the entries stored in variable "entries" #}
{% set entries = craft.entries.getAllSections('and, not career').type('news').order('RAND()').limit(3) %}

{# Conditional statement - if more entries than 0, we output them. If false, we set other conditional statement/s. #}
{% if entries|length > 0 %}

    {# Loop through entries #}
    {% for entry in entries %}

            {# My Stuff #}

    {% endfor %}

    {# Set ECM and get the entries stored in variable "career" #}
    {% set career = craft.entries.section('career').type('news') %}

{% elseif career %}

    {# Loop through career #}
    {% for career in career %}

            {# My Stuff #}

    {% endfor %}

{% endif %}

Is it because of the first variable entries?


texts:
I want to get the developer name from Plugin.php using the getDeveloper() method so I created a function devName() in Variable.php

public function devName() {
    return craft()->crmPortal->getDeveloper();
}

but when i want it to print it in my template, using this {{craft.crmPortal.devName}} I'm having this Error. Property "Craft\WebApp.crmPortal" is not defined.


texts:
I'm using the Venti events plugin to add recurring events to my site. However, I just want to show the most upcoming event and not all of them. This is a listing page which lists all of my events. This is what I currently have which lists all events.

{% set events =
  craft.venti.allEvents()
  .startDate('and', '>= ' ~ now)
  .limit(70)
  .relatedTo(categories)
  .order('startDate asc')
  .find() %}

{% for event in events %}
...
{% endfor %}

I found this in their documentation that supposed to show the next event, but this was on a detail page, not a listing page, so not sure exactly how to do this.

{% set next = craft.venti.nextEvent(event.id) %}


texts: Embedding a podcast player onto my Craft site

texts:
I'm pasting the embed code below into the HTML section but the player is not appearing. I do not have access to templates on my site. Is there a quick fix to get this to work?

I tried adding a plug in but can't work out how I do that.


texts:
I've got a default value defined in my model for a field

'limit' => array(AttributeType::Number, 'default' => 0)

When I create a new record, if the limit field is empty, NULL gets stored in the DB instead of 0. I thought $model->setAttributes() would set the default values if the values coming in were NULL. What am I missing?


texts: How do I add meta title/description and intro text to a Channel index page?

texts: I've created a Channel with templates blog/index and blog/_entry. Template blog/index will list the blog articles and blog/_entry will display individual blog articles. I want to have meta title/description and some intro text on the blog/index page that is managed by Craft. How can this be done?


texts: How can I use Ajax function in Craft CMS?

texts: I want to do an autocomplete search engine on my website. But I don't know how to use Ajax in Craft CMS. How can I set an Ajax function in Craft CMS templating? The search engine must have dynamic auto-complete feature according to title and content.


texts: How to Make getURL Output Complete URL (rather than root relative)

texts:
I'm using getURL() as follows in my Craft template:

{% set sharingImageURL = entry.sharingImage[0].getUrl('socialMedia') %}

Every time the output is a root relative URL and I'd like it to be a complete URL (including http://www.mydomain.com).

I can't figure out how to make that work. Can I do it with getURL() or is there a different method I should be using? Would appreciate some guidance!

Thanks.


texts:
Is there a straightforward way of creating a GUID or some other type of unique identifier within a Twig Template?

I'm aware of StringHelper.UUID (mentioned in a different question), but it doesn't look like I can use it directly in a template.

I'm comfortable creating a small plugin to expose this, or alternatively creating a twig filter to use a relevant PHP method, I just didn't want to go re-inventing the wheel if there's already a good solution I don't know about.


texts: Serving Craft from a sub-directory on Nginx

texts:
I'm starting with a clean install, empty database.

What would be the changes needed to this Nginx configuration to serve craft from /articles/ instead of "/"?

Any specific configurations that needs to be done to the Craft configs?

I've tried many combinations that all ended in 404.

Current layout:

/srv/www/app/craft <- "craft files"

/srv/www/webroot <- "public webroot"

/srv/www/webroot/articles/ <- "craft index.php here (with path set correctly to craft)".

Thanks.