texts: Stripe checkout, card declined but no frontend error

texts:
I have a Craft 2 site running commerce who have a small issue with the stripe gateway.

I am using https://checkout.stripe.com/checkout.js instead of the standard stripe markup.

JS looks like this (inside the standard commerce/payments/pay form:

var handler = StripeCheckout.configure({
    key: '{{ cart.paymentMethod.settings.publishableKey ?? '' }}',
    image: '',
    locale: 'auto',
    token: function(token) {
        // You can access the token ID with `token.id`.
        var stripeToken = token.id;
        // Get the token ID to your server-side code for use.
        document.getElementById('stripe-token').value = stripeToken;
        document.getElementById('payment-form').submit();
    }
});

document.getElementById('paymentButton').addEventListener('click', function(evt) {
    // Open Checkout with further options:
    handler.open({
        name: '{{ siteName }}',
        email: '{{ cart.email }}',
        currency: '{{ cart.paymentCurrency }}',
        description: 'Membership',
        amount: {{ cart.totalPrice|commerceCurrency(cart.paymentCurrency,convert=true,format=false) * 100 }}
    });
    evt.preventDefault();
});

// Close Checkout on page navigation:
window.addEventListener('popstate', function() {
    handler.close();
});

Currently, in some cases, the card is declined, but the popup from stripe acts as if everything is ok. You get a green check-mark when submitting, and then the checkout page just reloads instead of going to the order overview.

I am looking on network and console in Chrome, and cant see any responses or error messages. And in the basic checkout page from commerce I dont see any error array for the payment gateway.

Am I missing something? On test mode I can reproduce this using card number 4000000000000341. The cart looks like this in the CP:

Usually when the card gets declined there is a notification in the stripe popup. But not in this case. And as you can see from the picture Craft is well aware that the payment got declined. Is there any way for me to notify the customer of this? Instead of just having the checkout page reload?


texts: Overriding native CP template (without hacking the core)

texts:
Is it possible to create a plugin that overrides a control panel template, and still be able to update Craft normally?

What I'd like to achieve:

I have a custom field with information on every asset in the assets panel. I want to see this custom field when I upload / select an asset in an entry.

Template I want to customize:


texts: Help! My plugin is sending my email twice

texts:
For some reason that I cannot figure out, my plugin is sending 2 emails to each user instead on one. It sends the email on hit of an action url. Below is the function in my controller. Any help is greatly appreciated.

public function actionSendEmail()
{

    $date = new DateTime();
    $date->modify('-7 days');

    // Format datetime for use in query
    $timezone = new \DateTimeZone(DateTime::UTC);
    $date = $date->format(DateTime::MYSQL_DATETIME, $timezone);

    $criteria = craft()->elements->getCriteria(ElementType::Entry);
    $criteria->section = 'guide';
    $criteria->order = 'postDate desc';
    $criteria->dateUpdated = '> '.$date;

    $entries = $criteria->find();

    if ($entries) {

        $user_criteria = craft()->elements->getCriteria(ElementType::User);
        $user_criteria->groupId = '9';
        $users = $user_criteria->find();

        //Send to each User
        foreach ($users as $user) {
            //Send Mail
            $email = new EmailModel();
            $email->toEmail = $user->email;
            $email->subject = 'Updated in the Last 7 Days';
            $email->htmlBody    = 'Body Goes Here';

            craft()->email->sendEmail($email);
        }

    // Redirect after sending to each user in the loop to avoid 404
    $this->redirect('/');

    }
    else {
        // do nothing and redirect to avoid 404
       $this->redirect('/');
    }
}


texts: How can I set a custom URI for the confirmation link of account email update from a front-end form?

texts:
I have a front-end form to update user's email address, like this example:

<form method="post" accept-charset="UTF-8" enctype="multipart/form-data">
    {{ csrfInput() }}
    <input type="hidden" name="action" value="users/save-user">
    <input type="hidden" name="userId" value="{{ currentUser.id }}">

    New email address
    <input type="email" name="email" value="" id="newEmail">

    Password
    <input type="password" name="password">

    <input type="submit">
</form>

Once the form is submitted, Craft send a system message to the user email address, with a confirmation link. Once this link is clicked, the user is redirected to the root URL of the front-end website.

I changed the activateAccountSuccessPath, but whereas it works during account activation, it doesn't works during account email update.

Example:

'activateAccountSuccessPath' => array(
    'en' => 'my-account',
    'fr' => 'mon-compte'
)

Or:

'activateAccountSuccessPath' => 'my-account'

I also tried to enable / disable the autoLoginAfterAccountActivation setting, but the redirection is still not working. Even is user is already logged in, or if he is logged out.

I also checked the Craft logs, but I there's no error, no missing template, etc. ... nothing.

How can I set a custom URI on this link?


texts: Page currently being edited by another user notification?

texts: Any thoughts on how I could let  users know when they go to a page in the backend that/if another user is currently editing that page? I don't need it to lock editing, just to present a notice that it's being looked at/edited by someone else


texts:
I have setup a global set for images i use across the site. I have one for seo - where I have images for a twitter card and Facebook image in my seo settings. There is only one image for each field ( so hoping to avoid using the array syntax )

Two questions:

I am not sure how to access the images uploaded into this global variable. My global set has a handle "seo" and the image's handle is "twittercard". This isn't working :

meta(name='twitter:image:', content='{{ image.getUrl('seo.twittercard') }}')
Is this the most efficient way to store images used globally across the site? ( via global image variables?)


texts: Problem loading css files in some templates

texts:
I´m having problems loading css files in some templates.

Hi have this to load css files:

{% includeCssFile "assets/html/css/reset.css" %}
{% includeCssFile "assets/html/css/general.css" %}
{% includeCssFile "assets/html/css/typography.css" %}
{% includeCssFile "assets/html/css/layout.css" %}
{% includeCssFile "assets/html/css/formStyle.css" %}
{% includeCssFile "assets/html/rs-plugin/css/settings.css" %}
{% includeCssFile "assets/html/css/slidestyle.css" %}
{{ getHeadHtml() }}

This follows this path: http://localhost/craft/assets/html/css/filename.css

It works great , and load the styles for example, in the news section.
But, when i go to que news detail section, the styles don´t show.

The news detail template extends the template layout used for the home page and other sections.

The page looks for styles in this path: http://localhost/craft/news/assets/html/css/filename.css   and of course don´t find it.

I try with routes ( don´t know exacly how it works , but try and didn´t work ).

Help! :)

Thanks. Sebastian.


texts: Unable to update Craft: 'requires yiisoft/yii2-queue 2.1.0'

texts:
I've got another update issue with the following error. Can anyone help?

    craftcms/cms 3.0.27 requires yiisoft/yii2-queue 2.1.0 ->
    satisfiable by yiisoft/yii2-queue[2.1.0] but these conflict with your requirements or minimum-stability.

composer.json looks like this

{
"name": "craftcms/craft",
"description": "Craft CMS",
"keywords": [
"craft",
"cms",
"craftcms",
"project"
],
"license": "MIT",
"homepage": "https://craftcms.com/",
"type": "project",
"support": {
"email": "support@craftcms.com",
"issues": "https://github.com/craftcms/cms/issues",
"forum": "https://craftcms.stackexchange.com/",
"source": "https://github.com/craftcms/cms",
"docs": "https://craftcms.com/docs",
"rss": "https://craftcms.com/changelog.rss"
},
"require": {
"craftcms/cms": "3.0.23.1",
"vlucas/phpdotenv": "v2.4.0",
"craftcms/ckeditor": "1.0.0-beta.2",
"craftcms/redactor": "2.1.6",
"cebe/markdown": "1.1.2",
"composer/ca-bundle": "1.1.1",
"composer/composer": "1.6.3",
"composer/semver": "1.4.2",
"composer/spdx-licenses": "1.3.0",
"craftcms/oauth2-craftid": "1.0.0.1",
"craftcms/plugin-installer": "1.5.2",
"craftcms/server-check": "1.1.1",
"creocoder/yii2-nested-sets": "0.9.0",
"danielstjules/stringy": "3.1.0",
"doctrine/lexer": "v1.0.1",
"egulias/email-validator": "2.1.4",
"elvanto/litemoji": "1.3.1",
"ezyang/htmlpurifier": "v4.10.0",
"guzzlehttp/guzzle": "6.3.3",
"guzzlehttp/promises": "v1.3.1",
"guzzlehttp/psr7": "1.4.2",
"justinrainbow/json-schema": "5.2.7",
"league/flysystem": "1.0.44",
"league/oauth2-client": "2.2.1",
"mikehaertl/php-shellcommand": "1.2.5",
"paragonie/random_compat": "v2.0.12",
"pixelandtonic/imagine": "v0.7.1.3",
"psr/http-message": "1.0.1",
"psr/log": "1.0.2",
"seld/cli-prompt": "1.0.3",
"seld/jsonlint": "1.7.1",
"seld/phar-utils": "1.0.1",
"swiftmailer/swiftmailer": "v6.0.2",
"symfony/console": "v3.3.6",
"symfony/debug": "v3.3.6",
"symfony/filesystem": "v3.3.6",
"symfony/finder": "v3.3.6",
"symfony/polyfill-mbstring": "v1.8.0",
"symfony/process": "v3.3.6",
"yiisoft/yii2": "2.0.15.1",
"yiisoft/yii2-bootstrap": "2.0.8",
"yiisoft/yii2-composer": "2.0.6",
"yiisoft/yii2-debug": "2.0.13",
"yiisoft/yii2-queue": "2.0.2",
"yiisoft/yii2-swiftmailer": "2.1.1",
"zendframework/zend-escaper": "2.6.0",
"zendframework/zend-feed": "2.8.0",
"zendframework/zend-stdlib": "3.2.0",
"solspace/craft3-freeform": "2.4.0",
"dolphiq/redirect": "1.0.18"
 },
"autoload": {
"psr-4": {
  "modules\\": "modules/"
}
},
"config": {
"optimize-autoloader": true,
"platform": {
  "php": "7.0"
}
},
"scripts": {
"post-root-package-install": [
  "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
],
"post-create-project-cmd": [
  "@composer dump-autoload -o",
  "@php craft setup/welcome"
]
}
}


texts: How do I get an input value to dynamically update a Craft query on each keypress?

texts:
I want to set a Javascript variable using a Craft variable. Is this possible?

{% set searchJs %}

$( "#search" ).keydown(function() {

  var query = document.getElementById('search').value;

  {% set query = craft.request.getParam('q') %}
  {% set results = craft.weightedSearch.substringSearch(query) %}

  {% if results | length %}
    {% for entry in results %}
      console.log( "{{ entry.title }}" );
    {% endfor %}
  {% else %}
    console.log( "Sonuc Bulunamadı" );
  {% endif %}

  console.log( "{{ query }}" );
  console.log( query );
});

{% endset %}

{% includeJs searchJs %}


texts:
I try to use graphQL to get language specific entries from my Craft CMS. I (naively?) tried this:
query {
    entries (section: "newsIntranet", language: "fr") {
        title
        postDate
        expiryDate
        contentText
    }
}

because of this part of doc.
How can I get make sure that I only get entries of a given language when using graphQL from an extrernal system?


texts:
So there is this field called «Free Shipping» for each product.

But I can't find anything about this in the docs. I found out that I trigger it with

  product.freeShipping

But when activated it has no effect on shipping costs whatsoever.

What's the idea behind this thing, and how do I activate it?
(I'm fiddling around in the standard templates)?

I thought about creating a Free Shipping Category and then activate it via conditional. Or what's the idea about this?


texts: Allowing the user to update a CraftCMS pagination limit with listing filter options

texts:
I am building a pagination layout limiting the content to 10 because, well, it makes sense to break down large amounts of content to smaller chunks.

But as there is so much, a user might want to toggle how many they want to see. But because the pagination limit is done in the twig variables, is there a built in method for updating this on user interactions?

Standard CraftCMS pagination code:

{% paginate craft.entries.section(entry.slug).order('postDate desc').with: ['image'].limit(10) as pageInfo, pageItems %}

Cheers


texts: How do I create a plugin to create and save multiple entries from one front-end form?

texts:
I need to create several entries in different channels from a single front-end form. I realise that to do this I will need to create a plugin to handle the request.

Can I just to iterate over the post values in my controller action, validate them and build the entry models for each new entry, then loop around Craft's EntryService saveEntry() service for each entry I want to save?

Or do I need to write my own saveEntry() service to handle saving multiple entries?


texts:
I need to allow store managers to edit their store. I'm most of the way there and have the title field and a couple of other plain text fields set up. However there isn't any documentation available for other field types including:

categories
assets
lightswitch
relationship (entries)
Store hours https://github.com/craftcms/store-hours/

The documentation is only includes examples for input and textarea fieldtypes and not any other first party custom fieldtype .
What is the best approach to being able to edit these field types?


texts: Is there a way to eager-load fields in a global set?

texts:
I use a header global set to store various thing about my site header, including the company's logo.
I use it in my template like this:
{{ header.globalSetsHeaderLogo.one()logo.getImg() }}

Any idea on how I could eager-load this?


texts: Using the nav tag repeat the parent once in the children

texts:
I'm using the nav tag to build a menu which works great, but i just want to repeat the parent menu item over to any sub nav. So if there is a sub nav, at the top of the sub navs links, i want the parent url repeated once.

My current code is this

   {% nav page in blah %}

         {% if page.level == 1 %}
            {{ page.title }}
                {% else %}
                    {{ page.getLink() }}
         {% endif %}

         {% ifchildren %}

                {% children %}

         {% endifchildren %}

    {% endnav %}

and i'm looking at doing something like (but i would love it to work obviously)

   {% nav page in blah %}

         {% if page.level == 1 %}
            {{ page.title }}
                {% else %}
                    {{ page.getLink() }}
         {% endif %}

         {% ifchildren %}

{{ page.parent.getLink() }}
 -- this is dodgy
                {% children %}

         {% endifchildren %}

    {% endnav %}


texts: How can I make an entry (in this case a page from structure) only visible to users with cp access?

texts:
I tried 'draft page' but that only shows it in live preview. I need it accessible through the navigation as well. I was expecting a concept button in the CP that would allow this?

Do I need to make a specific light switch and create conditionals or is there some logic in the system?


texts: Exclude most recent entry type from a loop

texts:
Hey everyone I am trying to output entries on the homepage. My goal is that the most recent entry is styled differently.
I achieved this by calling the loop too times:
    {% for entry in craft.entries.section('blogPosts').limit(1) %}
than
   {% for entry in craft.entries.section('blogPosts').all() %}
and it works perfectly.
My only issue is that I want to exclude the most recent post from the second loop, so it only appear in the first loop.

Is there a way in craft for exactly the most recent entry or I should do this with ID?

Thank you for your help!


texts: Copy Content from original site to new site (multi-site)

texts: I have an English site with content, but now I need to create another site in French. So I'm setting up a multisite for my Craft install. I want to copy over all my English content over to my new site as a starting point, but their content will deviate in the future so I want to use the Propagation Method: Only save entries to the site they were created in. However, when I use this propagation method, all the content is gone. How do I copy over content from my original site to my new site?


texts: How can I access environment variables from a javascript file in Craft 3?

texts:
I see a lot of information about using environment variables on php files or twig templates, but I want to use them on javascript. I need to pass the environment, located on the .env file, to the Sentry init, located on assets/js/app.js.

How could I safely access this? Do I need to install dotenv or similar or is there a 'Craft way' of doing this?

I would appreciate any help on how to do this, or maybe a suggestion for a different approach.


texts: Trouble with curly braces in Entry URL Format / renderObjectTemplate

texts:
This works:

{{ craft.entries.section('products').relatedTo(object).first.uri }}/{slug}

However, in this case, I need to use the extended relatedTo property, which includes curly braces:

{{ craft.entries({relatedTo: {targetElement: object, field: 'productConfigs'}}).first.uri }}/{{ object.slug }}

Because of the way renderObjectTemplate replacement seems to happen, the braces get screwed up.

Any way to work around this?

I'd actually rather do this in PHP/plugin if possible, but I'm not sure if a relevant hook/event exists.


texts:
I have a dev site that I'm working on with around 1000 entries - mainly text content. I keep seeing "DeleteStaleTemplateCaches" stalled tasks come up - many times stacking 6-8 sets of similar stuck tasks.

I've read the article about stalled tasks but it seems to say they are the result of using a cache tag. I have no caching of any kind - no cache tags and no caching on the server (that I'm aware of). I'm sometimes able to clear the tasks using Task Manager (after many tries) but they always return.

Is there anything else I should check? Thanks in advance.


texts: How to find out which assets are being used

texts:
I want to be able to delete assets that are not linked to. I have adapted the following code from previous examples of this kind of thing, but it doesn't seem to pick up all the related entries, just some of them. Some photos do not show a related entry but if I go to the entry where I think it might have been used it is still in use. Am I missing something in matching the entries to the assets?

{% set photos = craft.assets.kind('image') %}
{% for photo in photos %}

{{ photo.filename }} / {{ photo.folderId }}

        {# Loop throught entries related to this asset #}
        {% for entry in craft.entries.relatedTo(photo).order('title') %}

{{ entry.title }}

        {% endfor %}

{% endfor %}

I have tried using the assetusage plugin but it doesn't seem to work with non images and I also wanted to test if it was working properly.
I also looked at the Asset-Use plugin but that is beta and only does images.


texts: Solspace Freeform: Looping through Radio group options in template

texts:
Using Solspace Freeform, I am trying to hardcode a radio gorup and its options in to a template. My effort is below but its not working

{# get the radio group field #}
{% set interestedIn = form.get("interestedIn") %}
{# Loop through the radio options #}
{% for option in interestedIn %}
<input type="radio" id="form-input-{{ interestedIn.handle }}" name="{{ interestedIn.handle }}" value="email">
<label for="form-input-{{ interestedIn.handle }}">Email</label>
{% endfor %}


texts:
I have installed Craft 2.2.2579 on my never-before-used website live rather than on my PC in a development environment. (I am not a developer.) Instructions were followed exactly (I believe), but when I point my browser to http://{mySiteName}/admin or the other alternatives, I get:

The index page of the website itself loads just fine as http://{mySiteName}.

Any ideas?


texts: Search through Linklist in Richtext field not working?

texts:
We launched a website last week based on Craft CMS.
One page contains mainly a list with links to sponsors (entered in a rich text field).

I make a fulltext search (via $critera->search) through the whole website, that works very fine, but it just didn't find the link texts inside a rich text field. (e.g. "Ascot", http://www.unidram.de/en/festival/partner-sponsors)

If I put the same text outside of the link, the search will find it. But that's not the solution, because the text should be the link.

I made a workaround and added Tags for every link to the page (except above given example). That did the job, but is additional work we won't normally do.

At first I clicked on "rebuild the search index".

The search on the website didn't find the page.
This is the template part of the search:

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

Then I searched for 'Ascot' in craft_searchindex in the DB.

Part of the content of the related field is this:

performance netzuniversitaetsgesellschaft potsdam sponsorenhochdreiascot bristolmedienpartnerpotsdamer neueste nachrichten

While the content looks like this:

So in fact the word 'Ascot' is saved as part of 'sponsorenhochdreiascot'.
As soon as I change it to 'sponsorenhochdrei ascot', the entry will be found by the search on the website.

The HTML Code of the part is:

Sponsoren

HochDrei

Ascot
Bristol

The search index seems to miss some space characters.


texts: Limit search by channel on the form rather than the results template

texts:
I'd like to use the same results template for all of my search functions so I'm wondering if it's possible to limit the search to a specific channel i.e. news or calendar in the form rather than in the results template.

Thanks!


texts:
When transforming images, we’re getting the following error on the client’s production server.

Internal Server Error
Argument 1 passed to Craft\AssetTransformsService::ensureTransformUrlByIndexModel() must be an instance of Craft\AssetTransformIndexModel, null given, called in /craft/app/services/ResourcesService.php on line 223 and defined

As a consequence image elements on the page don’t appear. When reloading the page a second time images are displayed as expected.
What might be the cause of this?

Edit
As requested in comments…
The .htaccess, below-pasted, is just the default.
<IfModule mod_rewrite.c>
    RewriteEngine On

    # 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]
</IfModule>

The template transform is very simple.
<img src="{{ block.image.first().getUrl({ width: 560, height: 310 }) }}" alt="">

The transform does work but only displays on the second page load.


texts:
So I have what seems like a simple problem but can't quite find a solution. On my entry template I'm trying to override the image fields as we're using the imager plugin for transforms. However, it doesn't seem to be working at all. No matter what I put inside the craft.sproutSeo.meta do loop, nothing happens. Even if I hardcode a value in there. It seems simple, but is there something I'm missing here? My code is below:

{% set cardEntryImage = craft.imager.transformImage(entry.blogHeaderImage.first(), { width: 1920, ratio: 16/9 }) %}
{% do craft.sproutSeo.meta({
    ogImage: siteUrl ~ cardEntryImage.getUrl(),
    ogImageSecure: siteUrl ~ cardEntryImage.getUrl(),
    ogImageHeight: cardEntryImage.getHeight(),
    ogImageWidth: cardEntryImage.getWidth(),
    ogImageType: cardEntryImage.getMimeType(),
    twitterImage: siteUrl ~ cardEntryImage.getUrl()
}) %}


texts: This seems like it should be straight forward. I need to set-up a structure section  with a parent page which uses the same section entry and same template. So the parent would have 'parent' as the slug and the children would have 'parent' as the first segment of the URL ie parent/children. Under the site settings in the section page I can include 'parent' before the slug, but this means the parent page gets the URL parent/parent. How do I get the parent page to keep the URL parent/?


texts:
I am having issues with search engines picking up my Craft site. I'm seeing x-robots-tag: none when reviewing my site's headers - which is shorthand for "no-index and no-follow".

The following is commented out in my nginx file as advised:
location = /robots.txt  { access_log off; log_not_found off; }
I have restarted nginx and the problem persists.
Robots.txt exists and works - I am using the SEOmatic plugin which generates the robots.txt file.
I have checked I'm using the live environment - which enables indexing.

How do I fix indexing at the header level?


texts: FortRabbit - performance - image transforms

texts:
Anybody else have problems with image transforms on FortRabbit?

They sent me this article as some background - https://blog.fortrabbit.com/imagemagick-issues

I was using the light level of hosting (https://www.fortrabbit.com/pricing) but encountered corrupted/slow transform images. I upgraded to 'Standard' and it seemed to be a bit better but still slow.

The transforms I had were only going from 1.5MB down to max 2000x2000 and there were 10's of them no 100's

I am new to Craft so not sure if this is a common thing, if other hosts have the same problem or if I just need to upgrade my hosting level on FortRabbit or another host?

Any advice appreciated.


texts: Specifics on ImageMagick and animated GIFs

texts:
I've looked through several StackExchange threads without specifics on how ImageMagick is tied into Craft. Web host says the binary is installed on server but not the module. Is the PHP module required?

  we looked into this further, and found that we do not have the ImageMagick PHP module installed, but we do have the binary. I'm not sure if Craft needs the PHP module, but if it does, that would be the reason for this not working.


texts:
I haven't used AJAX a lot, but what I want to do is the following:

I have a top navigation that outputs entries from a structure which link to various singles that display my data.
I want my navigation to stay and not reload when going to another page. How would I implement AJAX combined with Craft for that?


texts: Grabbing the existing address data to use with Smart Map

texts:
I'm new to Craft CMS, so pardon me. I've been using the VZ Address plugin to handle all our address entries, and have a couple hundred of workshop address entries already.
I'm trying to use Smart Map to generate a map, search by zip code, for the workshop addresses that are already been created with VZ Address. How can I grab that info from VZ Address field and use it with Smart Map?
Thank you for any help!


texts:
When working with a custom form that posts to a plugin function - what's the best way to return errors that would be displayed like the forgot password code example below

    {% if errors is defined %}

            {% for error in errors %}

{{ error }}

            {% endfor %}

    {% endif %}


texts: Session related question - opening browser with multiple tabs

texts:
We are having a situation wherein the users are trying to open URLs in the same browser with multiple tabs, while doing that the session variables which store unique identifiers are overwritten.

Is there some setting which can help in overcoming this problem?


texts: Use different template for paginated entries

texts:
Puzzle of the day: How does one load paginated entries on a different template?

Let's say in my homepage I'm loading the latest 5 entries and I would like to have pagination links below, however I want these to load on a different template. (in order to have less rings and bells than on the homepage)

I tried to use routes but it doesn't seem to be working, is this because the pagination works from the original template?

Here's what I tried for example.com where example.com/p2 is paginated:

'(?P<page>\d+)'     // page must be the answer, right?       nope...
'p(?P<number>\d+)'  // let's try combining 'p' and a number  nope...
'p\d+'              // how about with just the regex?        nope...
'(?P<page>)'        // also targets homepage so...           nope...

I also tried doing it in the CP with no results.


texts: Integrating and Caching Weather Data from Forecast.io API

texts:
Does anyone have any experience with integrating the forecast.io API for  location data for a Craft CMS site? I haven't been able to find any direct plugins for Forecast.io, but I was investigating the REST plugin as a possible option and I've also heard about FeedMe as well. Are there any preferred options as a best practice? My hope would be to be able to pull the data in and use it within a field of an existing entries page based on data on that entries page.

On a related note does wrapping Craft's caching tag around these plugin calls cache plugin output too? Probably a stupid question, just wanting to make sure I approach this solution correctly.


texts: block.image.one() shows more than one image

texts:
I'm sure I'm doing something wrong here, but I'm at a loss as to what. I'm using Craft 3. My travel entry has 7 fields, one of those being a matrix field. My matrix has two blocks, postText and postImage.

Here's the bit of code I'm working with:

{% for block in entry.mainPost.all() %}
  {% if block.type == "postImage" %}
    {% set image = block.image.one() %}
        {% if image %}
            <img src="{{ image.getUrl('summaryImage')}}" alt="">
        {% endif %}
  {% endif %}
{% endfor %}

I have an entry that has two images in the Matrix field. When I load the page, both images load. The documentation states that using .one() "Returns the first matching element". I have to assume that I'm not understanding the ElementCriteriaModel or Assets or the way Matrix works or something.


texts:
I had a section called vision which i renamed to articles. I did so by going in to sections and clicking the section and then changing..

Handle, Entry URL Format and Entry Template. I also copied and renamed all the template files.

Now i can load up the main page as server/articles. But none of the entry pages will load and I get a 404 error.

When i look at the entries they are still there and now say the uri is: articles/article-name and the data is all there..

Did i miss something that needs to happen to rename a section?


texts: Is there any way to code multiple lines in a twig file?

texts:
Instead of using:
{% ... %}
{% ... %}
{% ... %}

For each line, i'd like to know if there is a way to do something like:
{%

...
...
...

%}


texts: Intercept all requests before a Controller Action is executed

texts:
Is there a way to intercept a request before a controller action is run, so that you could preform additional authorisation checks?

Say I have an authorised user, but their access to actions is dependant on a 3rd party API. So I need a way to check, this 3rd party API or a stored session version, before each action is performed.

I can see the beforeAction() method, which is fine for new Controllers I have added, but I need site wide solution that will catch request that go through Craft and doesn't touch any plugins.

I can see the onBeginRequest Event, but aware this fires before Craft has had chance to setup. So I feel this might not be the best solution for me, as I would like to use services inside custom plugins. If there is no other way, I assume this is best place to look. If so what is the best way to add an Event listener for this?


texts: Is there a way to read IPTC, EXIF or TIFF Metadata in an Image uploaded to Assets?

texts: I'm trying to see if I can get the Date Created on images within an image upload. Not the date the file was created, but the date the picture was taken. If I open an image up in Preview, in the Inspector I can see that the IPTC, EXIF, and TIFF Metadata contains the information I'm looking for. Is that possible?


texts:
Is there any reason the mySQL, CraftCMS, and assets/images/content can't all live on the same server, assuming the server is appropriately sized and backed up?

Are there any sizing/scaling guidelines?


texts: What search engine does Craft CMS come with?

texts: New to Craft CMS. Our corporate website has been built using Craft. When using the site search, it is not finding all pages within the site. Wondering what the search engine technology is and how to re-index or broaden. Also, not crazy about the search results (SERP) display. What customizations are available?


texts:
I'm creating a website where I want users to be able to login. I'm using https://craftcms.com/docs/templating/login-form to achieve this. No problem so far.

When a user is logged in, I want the user to be able to reach the asset folder (depending on what the rights are for his user-group). When not logged in, I want the asset url to be private.
For this to work I've placed the asset folder outside the webroot, so you can't access the asset folder by default.

I've tried to achieve this with this plugin: https://github.com/tikiatua/internal-assets-plugin
But without any success.

My general config:

'enableTemplateCaching' => false,
    'devMode' => true,
    'siteUrl' => 'http://website.loc/',
    'loginPath' => 'http://website.loc/',
    'environmentVariables' => array(
        'internalAssetsPath' => CRAFT_BASE_PATH . "../media/",
        'internalAssetsUrl' => "http://website.loc/media/"
    )

I can upload a image in my internalAssetsPath, but when I try to show this in front-end, I get a 404.

{% for image in craft.assets.kind('image') %}

{% endfor %}

A solution for the 404 problem would be nice, but a solution for reaching the asset folder when logged in would be great.


texts:
Currently trying to use the new Donations feature of Commerce 2 - https://docs.craftcms.com/commerce/v2/donations.html

The order goes through fine and I can see the donation purchasable in the order.

What I can't do though is get it to assign the status of Donation to the donation/order. It currently comes through as a New status.

This is extremely handy to break apart Orders from Donations and vice versa.

Is there a way to set the donation status as default to all donations, or somehow assigning the status to the donation via the form when the payment is processed?


texts: Check if page is Search, use different classes

texts:
I'm looking for a shorter way of writing this check. If the user visits the search page, apply the 3 column to the search-block, else use the 5 column:

{% set currentPage = 'search' %}
{% if currentPage == "search" %}
   {% for project in pageEntries %}
      {% include '_partials/search-block' with {
         extraClasses: '3col'
         }
      %}
   {% endfor %}
{% else %}
   {% for project in pageEntries %}
      {% include '_partials/search-block' with {
         extraClasses: '5col'
         }
      %}
   {% endfor %}
{% endif %}


texts: Use REQUEST variable as dynamic upload location

texts:
How can I use a request variable used in an upload form like this?

<form method="post" accept-charset="UTF-8" enctype="multipart/form-data">
<input type="hidden" name="action" value="entries/saveEntry">
<input type="hidden" name="sectionId" value="29">
<input type="hidden" name="enabled" value="1">
<input type="file" name="fields[useruploads]">
<input type="text" name="challenge_id">
...

The idea is to use the field "challenge_id" as dynamic upload location.

Is there a way to get this?


texts: When including inline assets inside a rich text field is there a way to do trigger image transformations to include a different version of the photos that are embedded (thumbnail, resized etc.)?


texts: Trying to restore a Craft instance for a customer who was abandoned

texts:
I am new to Craft and a client asked us to take over a site as the previous service provider abandoned them.

For now just trying to get up and running on a Windows server in a test environment before deploying to a production server.

After restoring the mySQL db and getting it up and running via IIS the admin works, but the public site gives an error:

  Internal Server Error

  Craft\EntryModel and its behaviors do not have a method or closure
  named "placeCategory"

Does this imply we don't have the latest db of the site or all the files (or both)? Not sure what this error means or where to start troubleshooting.


texts: Can you remove the `translatable` option to a matrix field without losing locale content?

texts:
One of our admins have mistakenly added the translatable option to an important matrix field. We were using this option to synchronise content blocks across multiple languages.

This is the our main “Block Matrix Field” which is used across many of our templates and we have more than 5 different languages.

If I try to remove the translatable flag to the block matrix, it overwrites all the content for the matrix for all the languages on the first save.

We need to revert this change somehow, but we’re unsure of when the error was introduced.

Is it possible to make sure that the flag is disabled without losing all our content? I have a DB backup of before we did any saves with the flag disabled, which means that we can follow a recipe if you have one.


texts: Craft 3: Update database after CMS upgrade via console command

texts:
Is there any craft command command (shell) which can be used to perform the database updates necessary after a CMS update? (e.g. Craft3 beta-28 to beta29 or multi version updates)

Background: We are deploying our projects with Jenkins and I would want Jenkins to call such a command after each deployment (or after each CMS update). Going to the /admin/ Panel manually to be told that the database needs to be upgraded is not ideal.


texts: How to programatically (e.g. in a custom a plugin) create a Discount Code? (Craft Commerce)

texts:
I've been working on some custom plugins recently to handle various bits of API functionality for the project I'm working on, and I'm now roughly familiar with Craft's OO approach to carrying out this kind of task, e.g:
$product = new Product();
$product->title = "Sample Product";
// set other properties here
Craft::$app->elements->saveElement($product);

What I'm now trying to do is programatically generate discount codes (i.e. when a user performs a certain action, like signing up to the mailing list). I can hook into that event no problem, and I can even send out an email - it's just the actual creation of a Discount entity that I'm a bit stumped by.
Looking at the Class Reference for Products, which I can create successfully, I can see that what I'm ideally looking for is a Model, however this doesn't seem to exist for Discounts.
I think, therefore, what I'm looking for is the Discount Adjuster as that seems to be what this type of entity is called, however I'm not having much luck creating one. For example I would expect to see "Coupon Code" or similar as a field on this adjuster, but I don't see anything like that.
So the question is - how can I programatically create discounts with coupon codes (and whatever other options I would normally choose in the CP) in my custom plugin's controller action? I appreciate my problem is less to do with Craft and more my general rustiness with OOP... but hopefully this isn't a totally ridiculous request.
Thanks very much


texts: Correct way to getOrderByNumber() from my Plugin in Commerce 2

texts:
I am migrating my plugin to Craft 3 / Commerce 2.

What is the best way to call another plugins method like craft()->commerce_orders->getOrderByNumber($number) from my plugins service?


texts:
I've set up a shipping method/zone purely for testing but it doesn't show up during checkout. :/

I created a shipping zone only for the state of Oregon:

And for the shipping method there's just ONE rule with the ONLY condition being that the shipping zone is Oregon:

Here's the code I have for the shipping page of the checkout process:
http://d.pr/n/fizP

Finally, when I go through the checkout process, I make sure that my shipping address uses Oregon as the state. I've confirmed this by using this on the shipping page (not seen in the code above): {{ cart.shippingAddress.state }}

What am I missing??


texts:
I'm building a system which should have two parts CMS using craft cms 2.6.x. and Yii2 for logical modules and administration. I want to login to CMS directly once the user has logged into yii2 system. How can I do that? I can pass uid which in craft_user table. I need to build an API function but where shall I start?
Plus is this a good practice or there is something else I can do.

Thanks,


texts:
I run Craft Commerce and want people to get certain items for free, but still pass them through Commerce order system (in order to collect the emails and also perform some automation)

So basically they enter code and get 100% discount.

Now, if the person has ONLY free item in their cart, I don't want to ask them for credit card data or send to payment gateway. I want to just authorize the 'payment' of $0.00

I know I could use some template logic and use Manual or Dummy gateway, but I'm afraid some people will try to fool the system, so I want to make sure the 'free' gateway only works if order total is zero.

Does anyone know some plugin / custom gateway that I could use here?


texts: Error using environment variable for email setting

texts:
I'm trying to create an environment variable for email settings, but it doesn't work. Here is my email setting at config/general.php

'dev' => [
    '@host' => 'host',
    '@port' => '587',
    '@username' => 'user@user',
    '@password' => 'passwrod'
],

I have also tried before to configure the email setting using this way at config/app.php, but it doesn't work.

'components' => [
    'mailer' => function() {
        // Get the stored email settings
        $settings = Craft::$app->systemSettings->getEmailSettings();

        // Override the transport adapter class
        $settings->transportType = \craft\mail\transportadapters\Smtp::class;

        // Override the transport adapter settings
        $settings->transportSettings = [
            'host' => 'host',
            'port' => '587',
            'useAuthentication' => true,
            'username' => 'user@user',
            'password' => 'passwrod'
        ];

        return craft\helpers\MailerHelper::createMailer($settings);
    }
]

Am I doing anything wrong?


texts: Craft Commerce: Frontend Validation on Address Fields

texts:
Yes I know there is this post
But how do you do address validation in the frontend of Commerce 3?
The problem is the way Billing Address & Shipping Address are set up.
Billing Address are the same form fields duplicated via js and it is next to impossible to differentiate the two.
If I add required to any field this will also apply to the hidden field in the billing address form. Therefore, the html5 validation will always fail.
Has anybody a solution to this?


texts: Setting up Users to be able to only add/edit users they have set up.

texts:
I don't think this is currently possible. But maybe someone has done this already as a plugin or would I need to build one?

Situation is I need to set up First level Users who would be able to set up and manage other level 2 users. But only users they have set up themselves in a specified user group.

So as an example:

Level1 User1 sets up Level2 User1 & User2

Level1 User2 sets up Level2 User3 & User4

Level2 users are auto assigned to a Group called Guests.

So when Level1 User1 logs in he can only see, add and manage Level2 users in the Guests group that he has set up. i.e. Level2 User1 & User2.


texts: What is the correct syntax to check if a user has permission?

texts:
In my plugin, I am checking to see if the current logged in user has permission to save a commerce product.

$user = craft()->userSession->getUser();
if (craft()->userPermissions->doesUserHavePermission($user->id, 'ManageClothingProducts')) {
    // yes permission
} else {
  // no permission
};

However, it seems I'm always getting into the else.

The commerce docs mention this:

  Manage [type] products

Maybe I'm not using the correct syntax? I'm only using the clothing products as an example. Ultimately I'll be checking for my own products.

Thank you for any suggestions!


texts: Looking for a private commenting solution for member area

texts:
I've had a look through some previous posts and the craft docs and it doesn't look like anyone has done anything similar to what I want.

Essentially I have a 'client area' where a user can log in and just see photos and videos that are set on their profile (added by the admin). This all works great but I require functionality so the user can add a comment to said video or photo. I know solutions such as Disqus have been suggested but I can't see away of making them private and locked down so other guests and members cannot get access to the comments.

Does anyone know of any plugins, or methods through Craft that could be a possible solution or starting point to a solution?

Thanks!


texts:
I'm trying to upgrade my website to Craft 3, so I've imported all template files and installed the necessary plugins, but I can't deal with one error.

I've got a template named _layout.twig, and the first line used to import macros from other file called _helpers.twig. For some reason this doesn't work on Craft 3 - I checked in Twig documentation and it seems that everything is correct. I reviewed the changes in Craft 3 but didn't find anything related there. Running Craft 3.3 with Twig 2.11.3.

_layout.twig

{% import '_common/_helpers' as helpers %}
{{ helpers }}

Error

  Twig Runtime Error – Twig\Error\RuntimeError
  Variable "helpers" does not exist.

  in /craft3/templates/_layout.twig at line 2

Any ideas what can be the issue here?


texts: Multi-environment config SERVER_NAME not working

texts:
I have a problem with multi-environment variables.
I have used this before on a site and it worked perfectly, but now I'm on a different host and it seems that my SERVER_NAME isn't checked.
Every setting I put in the '*' => array is working fine, but in the 'domain.com' => array, it doesn't work at all.
It's like the domain isn't checked upon and I have no clue what this could be as I use the exact same code that worked on my previous host for another site.
I also did a test to check if my SERVER_NAME is correct and it is.

Does anyone have an idea?

Config file

<?php

return array(
    '*' => array(
        'omitScriptNameInUrls'  => true,
        'devMode'               => true,
        'cache'                 => false
    ),

    'cmgg.buthost.com' => array( // Use basePath and baseUrl in asset sources
        'environmentVariables' => array(
            'basePath'              => '/home/butpanel/public_html/cmgg/public/',
            'baseUrl'               => 'http://cmgg.buthost.com/',
        ),

        'siteUrl' => array(
            'nl' => 'http://cmgg.buthost.com/nl/',
            'fr' => 'http://cmgg.buthost.com/fr/',
            'en' => 'http://cmgg.buthost.com/en/'
        ),
    ),
);


texts: Model validation not run when using EntriesService saveEntry method

texts:
Currently i have to validate my model before saving because of some custom validation rules setted on the model which won't run when using the EntriesService saveEntry method.

This causes a two step validation when errors arise, first you get the custom validation errors and after that if there is still something wrong you get the "base" validation errors.

Is this a normal behavior?

$model->validate();

After that i am saving the model like so:

$result = craft()->entries->saveEntry($model);

Custom rules on model:

public function rules()
{
    $rules = parent::rules();
    $rules[] = ['state', 'validateState'];
    $rules[] = ['vacancyId', 'validateId'];
    //$rules[] = ['vacancyId', 'numerical', 'unique' => false];
    $rules[] = ['office', 'validateOffice'];
    $rules[] = ['sector', 'validateSector'];

    return $rules;
}

Why are the custom validation rules not evaluated on the saveEntry method?


texts: How do I use a Dropdown 'Entries' Field Type in a Front End Form

texts:
I have an Entries field that I need to have as a drop-down field in my front-end form. The code below is displaying the correct options, although after selecting and submitting the form, the tbdDesignerUrl-field is not populated with the selection in the entry.
It shows as nothing selected. (tbdDesignerUrl is the name of the Entires field I am trying to populate through the form and entry.designerUrl is the field I am using to select the entry in the options.)

{% set entries = craft.entries.section('designers') %}
  <select name="fields[tbdDesignerUrl]" id="fields[tbdDesignerUrl]">
    {% for entry in entries %}
     <option value="{{ entry.designerUrl }}">{{ entry.designerUrl }}</option>
    {% endfor %}
  </select>

Thanks for any help you can give! :)


texts: Craft Commerce Shipping Total Order Price rule

texts:
I have a webshop where you can get free shipping when the minimum total order price is €150.
Product prices are set up so they include VAT (21%).
VAT is removed when orders are shipped outside the Netherlands.
In most scenarios shipping cost calculation is not a problem but there is one VAT-related  specific scenario where it is not working.

Let's begin with the scenario that works as expected:

1) User buys product(s) which include VAT and the total order amount is  €151. Shipping address is inside EU so he is correctly eligible for free shipping.

Now lets go to the scenario where it does not work:

2) User buys the same product(s) as above and the total order amount is again €151. User is again eligible for free shipping but this time shipping is outside the Netherlands. That means that VAT is being excluded and therefore the final amount that user has to pay is below €150 and therefore he should pay for the shipping. But this is not happening.

It seems that system reads the 'total order price' as the total amount of the order before the tax reduction is applied. Therefore, according to the system user is eligible for free shipping. Though this is not correct.

My question is: Is there any way to make system look at the "final" total amount so the shipping calculation is correct?


texts: How can I save a tag value in an entry in Craft 3

texts:
I am working on a plugin and I have the following code

private function _tagProducts(array $products, array $names)
{
    foreach ($products as $productId)
    {
        $product = Craft::$app->getElements()->getElementById($productId, Product::class, null);
        $product['businessTag'] = ['something'];
        $product['purchasedWithVoucher'] = 'no';
        Craft::$app->getElements()->saveElement($product);
    }
}

If I remove/comment out the line $product['businessTag'] = ['something']; this snippet runs just fine and updates the field purchasedWithVoucher just fine. But, if I keep the businessTag line in I get the following error.

(Integrity constraint violation – yii\db\IntegrityException)

I have tried updating the tag field as $product['businessTag'] = 'something'; which at least throws no errors, but the product is not updated with the new tag, however the $product['purchasedWithVoucher']; line does update so I know that simply saving the changes isn't the issue.


texts: Handling path to assets (css, js) between local and production environment

texts:
How do you guys handle different paths between local and production environments regarding css and js files in your template twig files?

I am following the tutorials of nystudio107, which are simply awesome but can't see how this is be solved even in his pre-ready and configured craft3 download packages.

For example, in local dev I'd like to keep the css and js files separated from each other and unminified for better debugging. On production the files are combined and minified with gulp and moved to a /dist/css – /dist/js folder, which then does not matches the layout path I set in the twig files. Do you ran into similar problems and use a performant solution or do you hardcode the paths to the files on production environment?


texts: Craft 3 : Can't backup database ("failed with exit code -1")

texts:
I can't backup database, the log says :

  [error][yii\base\Exception] yii\base\Exception: Could not create
  backup: The shell command "mysqldump {{...blablabla...}} failed with
  exit code -1. in
  /home/user/craft/vendor/craftcms/cms/src/controllers/UtilitiesController.php:38

Any ideas what error -1 means ?


texts: Pull random image from entries marked with a certain category

texts:
I am trying to pull an image from services marked with a category of left. I would only like to display one image. I would also like to randomize the image if possible from all the images marked left.

{# RANDOM IMAGE FROM SERVICES - LEFT #}

    {% for homepage in craft.entries.section('services').limit('1').relatedTo(left).find() %}

{{ homepage.title }}

{{ homepage.description }}

                View Rental Pricing

    {% endfor %}


texts: Loop through all created fields and get the field type

texts:
I want to show some input fields on frontend template form.

  Type of input is dependent on the type of fields selected on the backend.

For example, if the text field is selected in the backend I will create a field of type="text". If a number field is selected I will show an input type="number" in the template.

I am trying to get the field type in my plugin.

$fields = Craft::$app->fields->getAllFields();
        foreach ($fields as $field) {
             $output[(int) $field->id] = array(
                'id'            => (int) $field->id,
                'handle'        => $field->handle,
                'name'          => $field->name,
                'instructions'  => $field->instructions
            );
        }

I checked the /vendor/craftcms/cms/src/services/Fields.php but not found any method.

Update:
I checked a few files and i found a method which returns the string.

$field->displayName();

Number
Lightswitch

Is it the only way to get the type of field.


texts:
I'm building a simple user backend and I would like to use Redactor for a couple fields. I see Redactor is a commercial product.

When I pay for Craft Pro does that include a license to use Redactor?
From an implementation standpoint, can I use the libraries already available?

I guess I wouldn't mind loading in another version of redactor for my front end. But I'm mostly curious if my craft license covers a redactor license.


texts: commerce_orders onOrderComplete not triggered?

texts:
Problem: I want to trigger an action (Instant Analytics plugin) whenever a payment (Craft Commerce plugin) is successful (webhook). Payment provider is Mollie.

So far I created a plugin that listens to the onOrderComplete event to send the analytics action. But it looks like the event onOrderComplete is not triggered.

Here is the code

craft()->on('commerce_orders.onOrderComplete', function(Event $event) {
    craft()->instantAnalytics->analytics()->addCommerceCheckoutStep($event->params['order'], 4, 'Payed');
    craft()->instantAnalytics->analytics()->sendPageView();
});

Question 1: Is this event a good one? Or is there an event that is thrown at the moment of a successful payment of an incoming webhook?

Question 2: Why is the onOrderComplete event not thrown?


texts: Modifying entry with 'onBeforeSaveEntry' event

texts:
I'm trying to modify a field on an entry before it is saved.

What I'm trying to do is use a field from a linked entry to populate the same field on the entry being saved.

From logging I know the event is triggered, and that I can access the seo variable on the linked element.

Edit: The field I'm trying to copy the content from is the SEO field supplied by the sprout SEO plugin.

However when I try to set the field on the main entry with the content from the linked one, I get the following message

  Property "Craft\EntryModel.seo" is not defined.

So my question is, how can I correctly set the seo field on the entry being saved?

Below you can see the code currently in my plugins init function.

craft()->on('entries.onBeforeSaveEntry', function(Event $event) {
    $entry = $event->params['entry'];

    if($entry->type['handle'] === 'service'){
        $serviceContent = $entry->linkToService->first();
        $event->params['entry']->seo = $serviceContent->seo;

        // Tried this aswell, gives second error mentioned below
        $entry->getContent()->seo = $serviceContent->seo;
    }
 );

After trying the answer provided by @justussimon91, the error message changed to:

  Property "Craft\SproutSeo_MetadataModel.metadata" is not defined.

Now this might be related to something specific with the Sprout SEO plugin so I'll raise the issue there as well.


texts: How do I check if a Global field exists in a template?

texts:
In a template, can I check whether a Global field exists, before I try to output its value? I want to ensure the page doesn't break entirely in the unlikely event of the field being removed from the CMS.

If I do:

{% if myGlobalSet.myField is defined %}
    Defined.
{% endif %}

then it works as expected; "Defined" isn't displayed if myField doesn't exist.

But if I have:

{% if myGlobalSet.myField is defined %}
    Defined. {{ myGlobalSet.myField }}
{% endif %}

I get:

  Craft\GlobalSetModel and its behaviours do not have a method or closure named "myField".

if that field doesn't exist. It's like it's trying to process the field even though it's not defined.


texts: Using Form to update User Profile and submit form

texts:
Checking the best way to achieve this or if it can be done without a plugin.
I need to allow people to register and create user accounts on my site with various profile information.

Then I will have a form on the site available to users to submit which saves it in the backend and alerts by email. (A&M forms looks like it has this functionality). When a user logs in this form should be prepopulated with data from their user profile.

When the form is submitted - can it update their user profile also?

It is basically a form for users to order repeat prescriptions - so I'm thinking user profile to save the standard date then use that to prepopulate the a&m form. Is what I'm suggesting the best way to achieve this?


texts: RegisterUrlRulesEvent rule to display site page

texts:
Within a plugin I have written I would like to route POST requests to the plugin controller and GET requests to a single entity created in craft.

When the user POSTs to http://example.com/start-your-quote it should be handled by the plugin controller. When the user GETs http://example.com/start-your-quote it should load the single entity with the slug 'site-start-your-quote'

I have written the following in the hopes of achieving this:-

 Event::on(
            UrlManager::class,
            UrlManager::EVENT_REGISTER_SITE_URL_RULES,
            static function (RegisterUrlRulesEvent $event) {
                $event->rules['POST start-your-quote'] = 'craft-lp-api-helper/lpapi';
                $event->rules['GET start-your-quote'] = 'site-start-your-quote';
            }
        );

The POST is working as expected, however the GET results in the following error:-

  Blockquote
  HTTP 404 – Not Found – yii\web\NotFoundHttpException
  Page not found.
  ↵
  Caused by: Invalid Route – yii\base\InvalidRouteException
  Unable to resolve the request "site-start-your-quote".

Hopefully I am missing something simple and someone can point me in the righ direction?


texts: Catch file-size errors in Guest Entries Form

texts:
I have a front-end entry form using the Guest Entries plugin, with a file input for the user to upload a photo. I am also using the jQuery Form plugin for AJAX submission, but the behavior is the same if I disable it.

The form works great with small file sizes, but if the uploaded image is larger than PHP's upload_max_filesize, I get a fatal error: Imagine\Exception\RuntimeException: Unable to open image.

If the uploaded file is larger than PHP's post_max_size, the page simply reloads - no error is registered. I gather that this error can be difficult to catch, so maybe it's impossible to have a more graceful failure in this case.

However, for file sizes between upload_max_filesize and post_max_size, shouldn't there be a way to return that as a proper error in the errors array, instead of dying in a way that is unhelpful to the end user?


texts: Working with Structure & Multiple Pagetypes

texts:
I have a site that's mostly 'static' content pages, with a few dynamic & more complicated pages mixed in.  To make editing & setting up the navigation easy, I started by creating a Structure that holds all the entries in my Pages section.  Let's say that structure looks something like this -

About

People
History

Products

Product A
Product B

It's more complicated, but just a longer version of that.  This structure is used to generate my navigation for the site, and everything is working as expected.

Now, all my content pages are in place and I need to add the 1-offs.  The first is a contact page, which is going to live @ /about/contact.  I'd like to place it within the structure because otherwise my navigation becomes a lot more complicated.

The problem is, it draws from a different template than my normal content pages, and a structure can only pull from a single template regardless of what sections are listed in it.  Ok, I thought, I could put the entry into that structure and then use a route to direct that page to the template I want to use.  That doesn't work, however, because page URI's are processed before routes.

So, the question is - what am I missing about doing this?  Is there a better way to set up what I'm doing?


texts: Craft Commerce: Displaying Individual Product Options in the Cart?

texts:
In the cart example code the selected options are displayed in an unformatted list like so:

{{ item.options|json_encode }}

I noticed that the note field text could be outputted individually like so:

{{ item.note }}

I'm looking to do the same for the select fields on my product, so if I had a list of options like the gift wrap example, how would I then output the result individually (so that I can format how I like)?

<select name="options[giftWrapped]">
  <option value="no">No gift wrap.</option>
  <option value="yes">Gift wrapped.</option>
</select>


texts: Displaying variable in array in array = Impossible to access an attribute ("date") on a string variable ("")

texts:
I'm trying to display a saved date from a json file.
I currently have:

{% set batchRowStats = craft.analytics.loadSavedBatch() %}

{% for stat in batchRowStats %}

        {{ stat['senddate'].date }}

{% endfor %}

And the information in the JSON file is:

[{"batchid":368,"total":1111,"opened":0,"clicked":0,"optout":0,"bounced":0,"subject":"subject line","senddate":{"date":"2017-06-02 06:00:22.000000","timezone_type":3,"timezone":"UTC"}}

I am getting this error:

Impossible to access an attribute ("date") on a string variable ("").

Which I am assuming it's because this information may be in a DateTime or object of sorts. I really need to just display "June 2, 2017" with a date_format but I'm not even sure how to get the string to display.


texts: Action route not available from URL. What do I have wrong?

texts:
I built a plugin for Craft 3 and need to run one of its actions via CRON. I know I can set this up as a console command, and will do that, but before I get there, I'd like to solve this issue.

I noticed my CRON was failing, and when I attempted to run the URL myself, at http://campaigns.gcx.loc/actions/gcxCampaignTools/stats/syncCampaignsRemote, I got this error:

yii\base\InvalidRouteException: Unable to resolve the request "gcxCampaignTools/stats/syncCampaignsLocal". in /Users/Chad/Sites/gcx-campaigns/vendor/yiisoft/yii2/base/Module.php:537
Stack trace:
#0 /Users/Chad/Sites/gcx-campaigns/vendor/craftcms/cms/src/web/Application.php(299): yii\base\Module->runAction('gcxCampaignTool...', Array)
#1 /Users/Chad/Sites/gcx-campaigns/vendor/craftcms/cms/src/web/Application.php(566): craft\web\Application->runAction('gcxCampaignTool...', Array)
#2 /Users/Chad/Sites/gcx-campaigns/vendor/craftcms/cms/src/web/Application.php(278): craft\web\Application->_processActionRequest(Object(craft\web\Request))
#3 /Users/Chad/Sites/gcx-campaigns/vendor/yiisoft/yii2/base/Application.php(386): craft\web\Application->handleRequest(Object(craft\web\Request))
#4 /Users/Chad/Sites/gcx-campaigns/public_html/index.php(21): yii\base\Application->run()
#5 {main}

Next yii\web\NotFoundHttpException: Page not found. in /Users/Chad/Sites/gcx-campaigns/vendor/craftcms/cms/src/web/Application.php:570
Stack trace:
#0 /Users/Chad/Sites/gcx-campaigns/vendor/craftcms/cms/src/web/Application.php(278): craft\web\Application->_processActionRequest(Object(craft\web\Request))
#1 /Users/Chad/Sites/gcx-campaigns/vendor/yiisoft/yii2/base/Application.php(386): craft\web\Application->handleRequest(Object(craft\web\Request))
#2 /Users/Chad/Sites/gcx-campaigns/public_html/index.php(21): yii\base\Application->run()
#3 {main}

The action works from a front end link with the following code when I am logged in (user must be logged in to use the entire app, so login is required to run the action as well):

Sync Campaigns

Because it worked when logged in, I thought I may need to allow anonymous in the controller, but that was already in place. I tried both protected $allowAnonymous = true; and protected $allowAnonymous = ['actionSyncCampaignsRemote']; with the same results.

Here is a screenshot of my plugin file structure and controller actions: screenshot

As you can see there I did put URL: /actions/gcx-campaign-tools/stats/sync-campaigns-remote in the code comments when I built this. Loading that URL produces the same error.

What am I missing here?


texts:
In Craft 2 I used:

{% for image in entry.imageGallery.offset(1) %}

to exclude the first image, as that is shown higher up in the template.
I get the depreciation error of:

  Looping through element queries directly has been deprecated. Use the
  all() function to fetch the query results before looping over them.

So I changed it to:

{% for image in entry.imageGallery.all() %}

But I can't find any example of how to apply an 'offset' in the Craft 3 docs.


texts:
The website I'm currently working on is a plattform where several 'subgroups' can post events but also have their own subpage. So the two affected secrions are 'event' and 'subgroup'.
Currently, every subgroup has an account which is author of their entry and they can create new event entries (which are linked through an entry field).

I'm wondering if it's possible to have multiple accounts for a subgroup which have the permission to edit their entries but not the ones of other subgroups.

Long story short: is it somehow possible to assign an entry multiple authors?


texts: Craft pro test environment expires? Can no longer access test environment

texts:
Can someone please help or advise me (I'm just starting to learn about Craft and setting up local servers. Sorry if this is a silly question).

I set up Craft Pro locally using MAMP. It worked yesterday just fine, but this morning I'm not able to access the admin side unless I go to "localhost:80", (localhost:8888 worked yesterday, but doesn't today. Is says it can't connect).

And even then, it's asking me to upgrade my license: "You’re running Craft Pro with a Craft Personal license, downgrade/upgrade." I thought that as long as you were running things locally it's ok to continue with the pro test version? Does the test environment have an expiry?

Thank you.


texts:
I'm trying to create a command line function, in my plugin, to import some data into entries. The problem is that the Craft\EntriesService->saveEntry() method seems to call the Craft\TemplatesService->renderObjectTemplate() method which uses the SERVER_NAMEconstant. Obviously there is no SERVER_NAME because the application is being run from the command line.

Is there a way to manually set this, or can this be bypassed in any other way?

I will include my stack trace here as well:

PHP Error[8]: Undefined index: SERVER_NAME in file myproject/craft/app/framework/web/CHttpRequest.php at line 352
0 myproject/craft/app/etc/console/ConsoleApp.php(252): Craft\ConsoleApp->handleError()
1 myproject/craft/app/framework/web/CHttpRequest.php(352): Craft\ConsoleApp->handleError()
2 myproject/craft/app/services/ConfigService.php(420): Craft\HttpRequestService->getHostInfo()
3 myproject/craft/app/helpers/UrlHelper.php(422): Craft\ConfigService->usePathInfo()
4 myproject/craft/app/helpers/UrlHelper.php(196): _getUrl()
5 myproject/craft/app/etc/templating/twigextensions/CraftTwigExtension.php(493): getUrl()
6 myproject/craft/app/vendor/twig/twig/lib/Twig/Environment.php(1276): Craft\CraftTwigExtension->getGlobals()
7 myproject/craft/app/vendor/twig/twig/lib/Twig/Environment.php(1200): Craft\TwigEnvironment->initGlobals()
8 myproject/craft/app/vendor/twig/twig/lib/Twig/Environment.php(1217): Craft\TwigEnvironment->getGlobals()
9 myproject/craft/app/vendor/twig/twig/lib/Twig/Template.php(355): Craft\TwigEnvironment->mergeGlobals()
10 myproject/craft/app/vendor/twig/twig/lib/Twig/Template.php(366): __TwigTemplate_5f77fd774cac1595e134b05c66db80e7998372598504ff29b7e2487f820a3d8c->display()
11 myproject/craft/app/services/TemplatesService.php(336): __TwigTemplate_5f77fd774cac1595e134b05c66db80e7998372598504ff29b7e2487f820a3d8c->render()
12 myproject/craft/app/services/EntriesService.php(157): Craft\TemplatesService->renderObjectTemplate()
13 myproject/craft/plugins/myplugin/services/Myproject_SomeService.php(312): Craft\EntriesService->saveEntry()
14 myproject/craft/plugins/myplugin/services/Myproject_SomeService.php(280): Craft\Myproject_SomeService->update()
15 myproject/craft/plugins/myplugin/consolecommands/ImportEmployeeCommand.php(24): Craft\Myproject_SomeService->createOrUpdate()
16 unknown(0): Craft\ImportCommand->actionImport()
17 myproject/craft/app/framework/console/CConsoleCommand.php(172): ReflectionMethod->invokeArgs()
18 myproject/craft/app/framework/console/CConsoleCommandRunner.php(71): Craft\ImportCommand->run()
19 myproject/craft/app/framework/console/CConsoleApplication.php(92): Craft\ConsoleCommandRunner->run()
20 myproject/craft/app/framework/base/CApplication.php(185): Craft\ConsoleApp->processRequest()
21 myproject/craft/app/etc/console/yiic.php(81): Craft\ConsoleApp->run()
22 myproject/craft/app/etc/console/yiic(4): require_once()


texts: Slow initial response time when website has been idle?

texts: I noticed my Craft website is slower to load when it has been idle for awhile. It can take up to 3-4 seconds for the first load, and then it goes down to about 500ms (which is fine) after the first page. I'm also using cache so I could get my query count to about 20-30 per page. I have other websites (non Craft) on the server that are fast to load even when they have been idle for awhile. Any idea what's causing this?


texts: Sideloading an image from a function in a plugin

texts:
I need to be able to side load an image and attach to an entry.

My image is coming from an external url... such as http://someplace.com/image.jpg - i can store this in a temporary file so its locally accessible.  But then how do I upload this image (without using $_POST or $_FILES) and attach to an entry.

The method i'm trying at the moment i'm using something like:
uploadNewAsset(UploadedFile $uploadedFile, $folderId)

But UploadedFile seems to only want to accept POST variables, unless i'm missing something

Any help would be great

Thanks


texts:
This should be fairly easy but I can't figure it out:
$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section = 'news';
$entries = $criteria->first(); // a simple "Single"
$videos = $entries->video; //the matrix
foreach ($videos as $item) {
    if($item->video[0]->id == $video) {
        $item->count = $item->count++;
        craft()->entries->saveEntry($entries);
    }
}

This was my original approach which throws Property "Craft\MatrixBlockModel.count" is not defined. (even though simply echoing $item->count does work.)
I subsequently tried 42 combinations of setAttribute() and the like up to the point where it didn't throw an error but so far my value was never updated. count is a simple Number field in a Matrix.
Thanks


texts: I am unable to correctly return the url of an uploaded asset

texts:
I'm a newcomer to Craft from the far-off lands of WordPress. I hope my stay is long and fruitful, but at the moment that prospect is in danger. The problem I'm having must be embarrassingly simple, but I can't find my way through it.

The simple task I am attempting to accomplish it to display an image I uploaded to an entry via a new asset field.

If there is a method or practice for displaying an image via asset fields found on the internet, I have tried it. Currently, this is how I am trying to render the image in my twig file:

{% for image in entry.featuredImage %}
    <img src="{{ image.url }}" alt="blah">
{% endfor %}

No image shows up.

When I dump(image), should it be returning an array with 666 lines? I understand an asset returns a kind of Asset File Model (although I don't entirely understand what that means), but I find it hard to believe it's supposed to be that large.

Hoping to find at least the url of the asset, I perform dump(image.url), but it only returns bool(false). Why would it be doing that?

I created my uploads directory, and setup my asset source. I've tried doing this on an entirely fresh, up-to-date and clean install, but it still behaves the same way.

What am I missing or doing wrong?

Thank you!


texts:
I am trying to find the last four Channel entries (Named: Post) with a Category relatedTo "Support" (id: 458) AND Tag relatedTo: "Widget1" (id: 469)
I've had success using Category or Tag but not both:
This Craft Query works for Category

for entry in craft.entries.section('Post').relatedTo('458').orderBy('postDate desc').limit(4).all()

How can I add the dynamic Tag to the Craft query? The dynamic Tag matches the slug of the current page "widget1" or slug of another page "widget2".

Thank you.


texts:
I am stunned by the typogrify extension for craft. https://github.com/nystudio107/craft-typogrify

Alas, the functionalities that are most relevant to me are not kicking in (anymore).
As Andrew says on https://nystudio107.com/docs/typogrify/#troubleshooting

  If it doesn't look like Typogrify is doing anything to the HTML you're
  passing it, it is probably malformed HTML (syntax errors, missing
  closing tags, etc.). Fix your HTML, and Typogrify will prettify it!

Well, in my case it's not, I'm outputting a text-only-field in a completely empty page.

{{ entry.lead|typogrify|smartypants }}

Most things are working: for example (c) is replaced by ©, and I can switch it on or off with "set_smart_marks" => true,

But I can't get the Hyphenation to work:

// enables hyphenation of text
"set_hyphenation" => true,

// defines hyphenation language for text
"set_hyphenation_language" => "de-CH",

At one point, the content was full of &shy;s which seemed to come from Typogrify. Not anymore. Why could that be?

I don't understand where typogrify gets the hyphenation rules from: maybe it requires additional php libraries that are missing?

Also, I wonder how – when it works – to switch the hyphenation language in a multilingual site?

[SOLVED:]

Quotes to guillemets

I wanted to convert all kinds of accidental double quotes into swiss style «Guillemets» (like the french, but there's no space).

I tried:

// curl quotemarks
"set_smart_quotes" => true,

// Primary quotemarks style
// allowed values for $style
"doubleGuillemetsFrench" => "&laquo;&nbsp;foo&nbsp;&raquo;",
"set_smart_quotes_primary" => Quote_Style::DOUBLE_GUILLEMETS_FRENCH,

The reason it wouldn't work were surplus spaces in twig:

{{ entry.lead | typogrify | smartypants }}

instead of

{{ entry.lead|typogrify|smartypants }}


texts:
Feed Me gives me, out of the blue, the error message below. I realized it only because i had "disable missing elements" active and all my entries where disabled. Feed Me was running over months without errors. I also made no changes to the Feed Settings at all.

Can anyone explain that to me? Thank you!


texts: How to output a resized Assets image in a template

texts:
How can I output a resized Assets image in a single entry template? I'm trying to do what I used to do all the time with CE Image in EE. I'm hoping that I don't have to create an image transform in the CP for every single piece of image resizing that I want to do as that would be very time consuming (compared to using the CE Image parameters for width and height in EE).

Here's my current code:

{% for asset in entry.mainImage %}

{% endfor %}

And for EE users, here's what I'm trying to replicate from EE:

{cf_static_image}
  {exp:ce_img:single src="{url}" width="800" height="600" alt="{alt_text}"}
{/cf_static_image}

Thanks for any help in advance.

Update: Here's what my final code looked like after following the example in the link provided by Brad below:

{% set thumb = {
  mode: 'fit',
  width: 800,
  height: 600,
  quality: 80
} %}

{% for asset in entry.mainImage %}

{% endfor %}


texts: Pantheon hosting alternative for Craft CMS

texts:
I'm coming from a WordPress background and use Pantheon for all my client websites. I love the service they provide, especially easy migrations and multi-environments (Multi-dev feature branches, Dev, Test, Live) they provide out of the box. It helps a small company off load all the dev ops work.

We also love Craft CMS, and would like to start using it more, but are struggling to find a host that provides the same/similar amount of features and support.

I've checked out Recommended hosting company for a Craft site? but none of the recommendations include features that I'm looking for.

Here are the main features I'm looking for:

Dev, Test, & Live
- Run a continuous integration workflow out of the box. Every site you create includes a Dev, Test, and Live environment connected by version control. Each has its own database, file system connection, and URL.

Cloud development environments
- Multidev allows you to fork your entire stack (code and content), work independently, then merge changes back into the master. Each branch is an entire development environment with the same configuration as the live site. Spin up cloud environments for feature branching, per-dev sandboxes, QA environments, and more. Multidev makes it easy to manage your development workflow and keep your team’s work in sync.


texts: How do I prevent a controller from creating unwanted routes?

texts:
I have a custom module that is adding sections to the CP, like this:

// Register CP routes
Event::on(
    UrlManager::class,
    UrlManager::EVENT_REGISTER_CP_URL_RULES,
    function(craft\events\RegisterUrlRulesEvent $event) {
        $event->rules['<controller:(subscriptions|purchases)>/<action:>'] = [
            'route' => 'module/<controller>/<action>',
            'defaults' => [
                'action' => 'index',
            ],
        ];
    }
);

// Add CP nav items
Event::on(
    Cp::class,
    Cp::EVENT_REGISTER_CP_NAV_ITEMS,
    function(craft\events\RegisterCpNavItemsEvent $event) {
        $event->navItems[] = [
            'url' => 'subscriptions',
            'label' => 'Subscriptions',
        ];
        $event->navItems[] = [
            'url' => 'purchases',
            'label' => 'Purchases',
        ];
    }
);

I have a SubscriptionsController and a PurchasesController, inside of which there is an actionIndex() method that computes some stuff and renders the appropriate template like this:

return $this->renderTemplate('module/cp/subscriptions/index', [
    'stuff' => $stuff,
]);

All this works fine, but I realized that the above registers some URLs that I do not want:

1) Controllers automatically register URLs in the format admin/actions/<module>/<controller>/<action> AND actions/<module>/<controller/<action>. I'm fine with the first one even though it causes duplicate URLs due to my custom <controller:(subscriptions|purchases)>/<action:> rule, but the second one is problematic because they're not even CP URLs, yet they invoke a controller that is only meant to be used in the CP. It's causing an error when trying to render the template, because the module template root is only registered for the CP with the code below:

// Set the base CP template directory
Event::on(
    View::class,
    View::EVENT_REGISTER_CP_TEMPLATE_ROOTS,
    function (craft\events\RegisterTemplateRootsEvent $event) {
        $event->roots['module'] = $this->getBasePath() . DIRECTORY_SEPARATOR . 'templates';
    }
);

2) Craft automatically creates routes based on my template structure, meaning I can render the module/subscriptions/index.twig template directly from this URL: admin/module/subscriptions. This is also causing an error because the template requires variables that are passed to it in the controller action, but they're not set when rendering the template directly. I usually work around this issue on the front-end by setting the general.php config setting privateTemplateTrigger to an empty string '', but it doesn't seem to have any effect on the CP.

Any help with these two issues would be greatly appreciated. :)


texts: Craft 3 updates & plugins without allow_url_fopen or SSH

texts:
I have set up a Craft 3 site on shared hosting. When I try to update Craft or install plugins via the CP, I get the following error:

  The "https://composer.craftcms.com/packages.json" file could not be
  downloaded: allow_url_fopen must be enabled in php.ini

allow_url_fopen cannot be enabled on this hosting & there is no SSH access

What are my options for updating Craft & installing/updating plugins in this scenario?

Is the only option to avoid CMS access temporarily, copy down the live database, do any updating locally and then upload the file changes & update the live database?

Thanks


texts: Change posts url without losing SEO positioning

texts:
I migrated a site with over 500 posts from Wordpress to Craft 2.6 recently but came across this problem: the WP site used to set post's urls as https://mysite.com/{slug} while the new blog is (correctly) saving them to https://mysite.com/blog/{slug}.

The problem is, a lot of the post entries have great SEO positiong and I don't want to lose that, what is the best way to achieve this?


texts: How should a multi-stage editorial process be implemented in Craft?

texts:
I'm building an editorial system on Craft which has 6-8 editorial stages, such as Assignment, Initial Proofing, Secondary Proofing, etc.  It seems that the simplest solution would be to have the current stage be a custom field.  I'd like to build this system entirely using Craft's backend so I don't have to reinvent all of the niceties Craft provides.

The fuzzy part, however, comes when I'd like to be able to have a "Send to Next Stage" button.  For instance, if the article is done with its initial proofing, the proofreader should be able to mark it as done and automatically send it to the Secondary Proofing step.  I realize that I could just have a dropdown where the user changes the status and saves it, but that feels cumbersome.  Stage 1 should only be able to send entries to Stage 2.  Stage 2 should only be able to send entries to Stage 3.  Things should never skip steps or move backwards.

My current thought is to hook into the entries.onSave event and have a switch or something to automatically change the status.  Then, I suppose that within a stage, all versions would have to be saved as drafts rather than entries, as saving would have that side-effect of essentially marking the entry as complete.

Is there a simpler, more foolproof, or more intuitive way to walk an article through an editorial process like this?  I suppose I could use categories rather than a custom field type, but the entries.onSave hook would still have to be the mechanism I'd use to automatically send the article to the next stage of the editorial process.


texts: Fetch/Remove all unused assets (by plugin)

texts:
The title is self-explanatory, but I need to buid a service function to remove unused assets, or at least to fetch those in order to delete found assets after.

Any simple solution?


texts:
My client is setting up a digital downloads shop (PDF's) and has a requirement that after one or multiple products are purchased the PDF's are then available for download.
He wants one or more of the following and i am just wondering if any of these are possible with any plugins or otherwise?

Password protect the PDF (the password could be the customers email or other random password)
Add a watermark - perhaps a logo and maybe date
Add header and footer with some dynamic information (e.g. date, email)

Its worth noting that the customer's PDF is wanted ideally to be created from an already existing base PDF but i see a lot of the plugins use HTML to create the PDF so could look into that possibly also
Many thanks
Malcolm


texts: Bad Request Unable to verify your data submission and unstyled CP

texts:
First of all the control panel login is unstyled, and I'm getting Bad Request Unable to verify your data submission when trying to login to the control panel. I can login using a form on the front end, but then I find the CP is still unstyled. Using console I can see the cpresources files cannot be found by the browser - but I've checked they are there, and have file permissions set.
Any ideas???


texts: Images lose quality when I upload to Craft

texts:
The images I upload to Craft lose their quality :(

Without applying any transformation, the original file is blurred and has a smaller size.

I read this on another question:

  Currently the images are being cleansed on upload, which means that they are being re-saved to make sure that no malicious code is injected in them.

There is a way to get Craft uploading my pixel-perfect images without re-save them?

An example of the problem:


texts: Overriding Craft's default routing process

texts:
I have a situation where I'd like to have an entry exist with a particular URL structure by placing it within an existing structure. Let's say this URI is:

/one/two/three

Where 'three' is the entry I've created in the CP. Currently, this structure uses this section's template, but I'd like to use a unique template for this single entry within the section. My first thought was to create a Dynamic Route that points this URI to the unique template, but that doesn't work.

It seems that Craft has a checklist of items for routing and a section's template will be checked for first, and if that exists, it gets loaded. Is it possible to override this and load a unique template for a single entry in a section?


texts: Issues upgrading Craft 2 to 3 - Keep seeing Install Screen not Update screen

texts:
I'm trying to update my development site on MAMP from Craft 2 to 3. I've installed Composer and tried both upgrade methods (keeping the current directory structure & using the new structure). But with both options, I keep getting shown the install craft screen instead of the update screen. Which is not what I want to do.

I've added my info to the .env file, but the only way I can seem to get the update screen is by using my old db.php file from craft 2. But then that means that I can use the .env file.

If I then go to complete the update, I tells me that craft can't do a database backup. If I then continue the update to craft 3, when I log in I'm shown the following dependency error:

The auto-generated validation key stored at /Applications/MAMP/htdocs/lorindafontainefarris/craft3/storage/runtime/validation.key has been deprecated. Copy its value to the “securityKey” config setting in config/general.php.

I don't see a validation key to copy, but I already have one that was created for the .env file. Its just not being used because I've used the old db.php file from my craft 2 build. I'm assuming that I shouldn't have to use my old db.php file to get the update to work.

So can anyone shed some light on why I keep seeing the Install screen when I go to update my craft2 project?

Thanks in advance,

Richard


texts: Get the author of current entry version?

texts: How would I go about to get the author from the current version / revision of the entry I'm on? Im trying to get "last updated by" in frontend, but authorId on the entry seems to be the original author, not the last that edited it.


texts: Any ideas on how to set/output something if the previous variant in a for loop has a parameter?

texts:
Realizing Twig can't escape a for loop, how would one go about setting a variable for the current item and not the following?

Scenario;
Color swatches are radio buttons, if default purchasable stock <= 0 and default purchasable unlimitedStock == false, the next radio button should be checked, and if this has stock <= 0 and so on, you get the idea, the next would be checked.

I can't seem to find a way to only check the next, and not all the following radio buttons if previous purchasable in the loop is out of stock.

A lot of checking of the checkers being checked here. Hah.


texts: Craft install locally with MAMP Pro/versioning

texts:
So... I've installed Craft online, and I wanted to start templating my CraftCMS, but I'd like to work with a repository so I can have some kind of versioning. The easiest way to do so seemed to me to install Craft on our hosting server, download those files locally and connect to the online database using MAMP pro.
I had some issues with our host (I had to whitelist my IP address), but now I can connect to the database using Sequel Pro, but when I try to access my craft CMS site through my local files I get the Craft message "service unavailable".
My Mamp Pro is pointed to my public folder (2 folders in my site: public and craft, and it's pointed to this public folder with the index file in it) and I've used the same db settings as the ones I've used in Sequal Pro. Still: no succes.
The only thing I've changed after downloading the site are these db setting for the host - as I had to do in Sequal Pro.
Can anyone help a newbie in Craft CMS out here :-)? Thanks!


texts: Why does loop.index not work with replace?

texts:
Good day!

In Craft CMS 3, I'm tring to configure the replacement of tags for markdown via replace, everything works except for the tag {{ loop.index }}

Please tell me how to properly configure to work correctly {{ loop.index }}?

{{ block.markdownContent|markdown

 |replace('
', '
')
 |replace('
', '
')
 |replace('<a ', '<a class="link link-color"')
 |replace('
', '
')
 |replace('
', '

')
 |replace('
 ', '

')
 |replace('
', '
')
 |replace('
', '

{{ loop.index }}')
 |replace('
 ', '

')|raw }}

Can you advise other ways of realizing this task.


texts: Search for entries with matrix field's value

texts:
I'm building a travel site containing Campaigns (entries)

Each of these campaigns has multiple travel dates, modelled by a matrix field of

[startDate, endDate, price]

I want to do the following searches:

Campaigns with a travel startDate next month
Campaigns whose duration is more than 30 days and less than 60 days (endDate-startDate)
One of those criteria
All of the above criteria

How can this be achieved with twig template or custom controller?

PS: I looked into relations but that only applies to entries field, not matrix, and neither does it allow filtering on the related entity.


texts: Display user photo within a User field type

texts:
I'm making a staff page with a User field type, so you select all the users you want displayed. I'm having trouble showing each user's photo though. This works:
{% for user in block.staffList.all() %}
   Image URL: {{ craft.assets.id(user.photoId).one().url }}
{% endfor %}

But seems far from the ideal solution. Is there a more graceful way to do this?


texts: How to create subfolders in the Assets view?

texts: I can't find any information on this issue, but I'm not seeing any way to create subfolders in the Assets view of the control panel. I just see all of my images with no folders. Is this feature restricted to paid versions?


texts: What's the difference? SQL_MODE error in one site and not the other

texts:
I have 2 Craft sites that share the same Craft codebase. For both sites, i was getting the following error:

Internal Server Error CDbCommand failed to execute the SQL statement: SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #18 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'creighton_mma_craft.structureelements.root' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

I found this Craft Stack Exchange solution and implemented Brad's second suggestion ('initSQLs' array) on both sites (see config/db.php below). It seems to have fixed it in the site called 'craft' but not the site called 'pc'. Though the question referenced above says that he can reach his control panel, i cannot reach the site or the control panel. What am I doing wrong? As far as I know, there are no differences between the 2 sites. All configuration details listed below.

O/S:

O/S: GNU/Linux

Issue: Ubuntu 16.04.1 LTS

Kernel Release: 4.4.0-43-generic

Kernel Version: #63-Ubuntu SMP Wed Oct 12 13:50:36 UTC 2016

Apache:

Server version: Apache/2.4.18 (Ubuntu)

Server built:   2016-07-14T12:32:26

MySQL:

mysql  Ver 14.14 Distrib 5.7.15, for Linux (i686) using  EditLine wrapper

PHP:

PHP 7.0.8-0ubuntu0.16.04.3 (cli) ( NTS )
Copyright (c) 1997-2016 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies
    with Zend OPcache v7.0.8-0ubuntu0.16.04.3, Copyright (c) 1999-2016, by Zend Technologies

Craft:

define('CRAFT_VERSION', '2.6');

define('CRAFT_BUILD', '2949');

define('CRAFT_SCHEMA_VERSION', '2.6.7');

define('CRAFT_RELEASE_DATE', '1475689624');

define('CRAFT_MIN_BUILD_REQUIRED', '2570');

define('CRAFT_MIN_BUILD_URL', 'https://download.craftcdn.com/craft/2.1/2.1.2570/Craft-2.1.2570.zip');

define('CRAFT_TRACK', 'stable');

Craft's db.php:

<?php

return array(
        '*' => array(
                // The database server name or IP address. Usually this is 'localhost' or '127.0.0.1'.
                'server' => 'localhost',

                // The database username to connect with.
                'user' => '<redacted>',

                // The database password to connect with.
                'password' => '<redacted>',
        ),

        'devappsCraft' => array(
                // The name of the database to select.
                'database' => 'craft',

                // The prefix to use when naming tables. This can be no more than 5 characters.
                'tablePrefix' => 'path',

                // Work-around for newer version of MySQL
                'initSQLs' => array("SET SESSION sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';"),
        ),

        'devappsPc' => array(
                // The name of the database to select.
                'database' => 'craftPc',

                // The prefix to use when naming tables. This can be no more than 5 characters.
                'tablePrefix' => 'pc',

                // Work-around for newer version of MySQL
                'initSQLs' => array("SET SESSION sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';"),
        ),
); ?>


texts:
Does anyone know, if craft gets support for MongoDB in the near future? Or is any solution out there for using MongoDB? This would be awesome. :)

Kind regards
Ron


texts: How to disable template caching? devMode isn't doing it

texts: I'm trying to disable template caching in my development environment. I've tried a few things but thus far nothing has worked. I had thought that just setting devMode to true in the config would do the trick, but I'm still caching. The control panel shows the caution lines to indicate I'm in dev mode, but I still have to manually clear the cache before template changes show up. What am I overlooking?


texts: How do I install the FormBuilder 2 plugin in my local Craft project?

texts: I tried cloning https://github.com/roundhouse/FormBuilder-2-Craft-CMS to my plugins folder of my local Craft project and opened the plugins module from admin settings but the formbuilder2 plugin did not show in the list. Can you please help me if somebody has used this plugin for their Craft CMS project? Thank you.


texts: Sorting categories into list put single one at end of it

texts:
I'm trying to put a single category (as long as it's populated) at the end of an category list. My code is working so far, is there an easy way to pick out the 'Others' category and append it to the list?

{% set entryIds = craft.entries.section('toys').ids() %}
{% set categories = craft.categories.relatedTo({ sourceElement:
    entryIds }).craft.categories.group('brands').find() %}

{% for category in categories %}
    {% set image = craft.assets.relatedTo(category).first() %}

        {% if image|length %}

        {% else %}

        {% endif %}

{% endfor %}

Thanks for any help, ready to learn something new.


texts: Users not being deleted from the craft_users table?

texts:
Since upgrading to craft 2.6.2785 when I delete a user it appears to remove the user from the elements and elements_il8n tables but does not delete the user from the users table.

If you then search for the user in the CMS it does not find them however the user has not been removed from the database so if you try and set up a new user with the same email address it fails with "email has already been taken message".

Update on this. I re-imported the database from dev to staging. In my dev deleting users works fine. When importing the database which is fairly large due to 20k+ users I get this error:

SQL Error (1452) Cannot add or update a child row:a foreign key constraint fails ('databaseName'.'#sql-1510_62265', CONSTRAINT 'craft_matrixcontent_newscontent_elementId_fk' FOREIGN KEY ('elementId') REFERENCES 'craft_elements' ('id') ON DELETE CASCADE)

Then when trying to delete a user it says it's deleted removes the elements from the element tables but does not remove the user from the users table.