texts: phpmailer Exception while using Pixel & Tonic contact-form plugin

texts:
Link to Github repository for plugin: https://github.com/pixelandtonic/ContactForm

Being given an error by the plugin where it is interpreting my Twig variable literally as a string instead of what the variable is representing. I am looking for a way to fix this using the current set-up but having an alternate setup is fine as well. Also for reference, I have followed the guidelines on the README in regards to changing the craft/config/contactform.php file. Much appreciated for the help!

This is my code:

{% macro errorList(errors) %}
{% if errors %}

        {% for error in errors %}

{{ error }}

        {% endfor %}

{% endif %}
{% endmacro %}

{% from _self import errorList %}

<form method="post" action="" accept-charset="UTF-8">
    {{ getCsrfInput() }}
    <input type="hidden" name="action" value="contactForm/sendMessage">

Email to {{default.defaultcontactreason}}

            <input type="hidden" name="toEmail" value="{{ '{{default.defaultContactEmail}}'|hash }}">{{default.defaultContactEmail}}

    {% for category in craft.entries.section('Contacts') %}

Email to {{ category.contactReason }}

            <input type="hidden" name="toEmail" value="{{ '{{category.contactEmail}}'|hash }}">{{category.contactEmail}}

    {% endfor %}

Your Name

    <input id="fromName" type="text" name="fromName" value="{% if message is defined %}{{ message.fromName }}{% endif %}">
    {{ message is defined and message ? errorList(message.getErrors('fromName')) }}

Your Email

    <input id="fromEmail" type="text" name="fromEmail" value="{% if message is defined %}{{ message.fromEmail }}{% endif %}">
    {{ message is defined and message ? errorList(message.getErrors('fromEmail')) }}

Subject

    <input id="subject" type="text" name="subject" value="{% if message is defined %}{{ message.subject }}{% endif %}">
    {{ message is defined and message ? errorList(message.getErrors('subject')) }}

Message

    <textarea rows="10" cols="40" id="message" name="message">{% if message is defined %}{{ message.message }}{% endif %}</textarea>
    {{ message is defined and message ? errorList(message.getErrors('message')) }}

    <input type="submit" value="Send">
    <input type="hidden" name="redirect" value="{{siteUrl}}Contacts">
</form>


texts: Output Placeholder, Max Length, Line Breaks, Initial Rows values for Fields in Sprout Forms

texts:
I'm trying to create a dynamic form that loops through all the form fields and dynamically applies the HTML that matches the field type.

I can't seem to find what to use to output: Placeholder, Max Length, Line Breaks, Initial Rows.

Other values like field.type, field.required, field.handle work fine. But trying field.placeholder or field.settings.placeholder does not work.

{% set fields = tab.getFields() %}

{% for field in fields %}

    {% set required = field.required %}
    {% set field = field.getField() %}

    {% if field.type == "PlainText" %}
        <input type="text" name="fields[{{ field.handle }}]" value="{{ attribute(submittedEntry, field.handle) }}" placeholder="">
    {% endif %}

{% endfor %}


texts:
I'm trying to access a CP template from the frontend, and i'm doing something like this in my plugin:

<?php

...
$oldMode  = craft()->templates->getTemplateMode();
craft()->templates->setTemplateMode(TemplateMode::CP);

$widget = craft()->templates->render('plugin/Plugin_Template', array(
    'chatraID' => $chatraID,
));

craft()->templates->setTemplateMode($oldMode);
...

I'm getting the Unable to find the template error, though. I have verified that the plugin is installed, and that the template  plugin/Plugin_Template is accessible from the CP.


texts:
Im using a pretty standard method for calling for entries, but with one small caveat in that I'm setting the limit inside a variable which is passed through to an include

so my index.twig file is like so

{% include 'homepage/_latest' with {'postCount' : 9} %}

and my homepage/_latest file has the following

{% cache %}
{% set latest = craft.entries.section('blog').limit(postCount ? postCount : 12) %}

<div class="entries entries--latest">

    {% for entry in latest %}

    {% include 'blocks/_entry-item-latest' %}

    {% endfor %}

</div>

{% endcache %}

Is that variable the issue for me/ I save a post and it doesnt know up on the homepage. I had it setup to invalidate every 15 minutes, but we put out 3-4 posts a day so theres no real need to invalidate that content every 15 minutes


texts: Upgrade to 3.6 Error: One of Craft CMS’s migrations failed. Undefined class constant 'Trial'

texts:
I am trying to update to Craft 3.6 but getting the following error:
Is it related to a plugin being on Trial? I have the plugin Freeform on Trial during development.
Error: Undefined class constant 'Trial'

Migration: craft\migrations\m201124_003555_plugin_trials

Output:

Exception: Undefined class constant 'Trial' (C:\Websites\grants\craft\vendor\craftcms\cms\src\migrations\m201124_003555_plugin_trials.php:22)
#0 C:\Websites\grants\craft\vendor\craftcms\cms\src\db\Migration.php(52): craft\migrations\m201124_003555_plugin_trials->safeUp()
#1 C:\Websites\grants\craft\vendor\craftcms\cms\src\db\MigrationManager.php(232): craft\db\Migration->up(true)
#2 C:\Websites\grants\craft\vendor\craftcms\cms\src\db\MigrationManager.php(148): craft\db\MigrationManager->migrateUp(Object(craft\migrations\m201124_003555_plugin_trials))
#3 C:\Websites\grants\craft\vendor\craftcms\cms\src\services\Updates.php(250): craft\db\MigrationManager->up()
#4 C:\Websites\grants\craft\vendor\craftcms\cms\src\controllers\BaseUpdaterController.php(509): craft\services\Updates->runMigrations(Array)
#5 C:\Websites\grants\craft\vendor\craftcms\cms\src\controllers\UpdaterController.php(203): craft\controllers\BaseUpdaterController->runMigrations(Array, 'restore-db')
#6 [internal function]: craft\controllers\UpdaterController->actionMigrate()
#7 C:\Websites\grants\craft\vendor\yiisoft\yii2\base\InlineAction.php(57): call_user_func_array(Array, Array)
#8 C:\Websites\grants\craft\vendor\yiisoft\yii2\base\Controller.php(181): yii\base\InlineAction->runWithParams(Array)
#9 C:\Websites\grants\craft\vendor\craftcms\cms\src\web\Controller.php(190): yii\base\Controller->runAction('migrate', Array)
#10 C:\Websites\grants\craft\vendor\yiisoft\yii2\base\Module.php(534): craft\web\Controller->runAction('migrate', Array)
#11 C:\Websites\grants\craft\vendor\craftcms\cms\src\web\Application.php(274): yii\base\Module->runAction('updater/migrate', Array)
#12 C:\Websites\grants\craft\vendor\craftcms\cms\src\web\Application.php(665): craft\web\Application->runAction('updater/migrate')
#13 C:\Websites\grants\craft\vendor\craftcms\cms\src\web\Application.php(212): craft\web\Application->_processUpdateLogic(Object(craft\web\Request))
#14 C:\Websites\grants\craft\vendor\yiisoft\yii2\base\Application.php(392): craft\web\Application->handleRequest(Object(craft\web\Request))
#15 C:\Websites\grants\craft\web\index.php(21): yii\base\Application->run()
#16 {main}


texts:
I'm trying to display a list of favorited entries. I have a wishlist with entry id's build with Shortlist. So now I want to display them but it doesn't work. The first part getting the favorited id's works perfect.

Here is my code so far:

        {% set favIds = [] %}

        {# LOOP TRUE FAV IDS AND MAKE ARRAY #}
        {% for list in lists %}
            {% if list.items is empty %}

No wishlist

            {% else %}
                {% for entry in list.items %}
                    {% set favId = entry.id %}
                    {% set favIds = favIds|merge([favId]) %}
                {% endfor %}
            {% endif %}
        {% endfor %}

        {# CONVERT favIds array in comma separated list #}
        {% set favIdString = favIds|join(', ') %}

        {% set wishlist = craft.entries.id(favIdString).fixedOrder('true') %}

        {% for entry in wishlist %}
            {{ entry.title }}
        {% endfor %}

But nothing shows up. If I output {{ favIdString }} I get a nice list if entry ID's. 9619, 9620, 9621, 9622, 9624, 9625


texts:
Does anyone know how to make Craft by default use .twig extensions. It helps IDEs better understand Twig blocks. I have tried .twig and .html.twig but it doesn't appear to work by default.

I don't want to set up special configs for every template.


texts: Programatically change a lightswitch value on an entry on save

texts:
I have a simple plugin that fires some events entries.onSaveEntry based on if a lightswitch is turned on with that entry. What I would like to do as the last event in my plugin would be updating the value of the lightswitch with that entry to be turned off (or 0) so if you went back in to the entry it would be turned off again.

Would appreciate any guidance.


texts: How do I add input a value to a Craft/Twig request?

texts:
This might be a stretch.

How do I (literally) modify the (Tableau API) javascript function below to print a specific fieldName ("Country") so that it can place the "Country" into the CraftCMS/Twig request below?

{% set results = craft.entries.section('posts').search('countryName:"Value Goes Here"') %}


texts: Guest user registration using Commerce 3

texts:
I have just started using Craft Commerce (only Lite version currently) and I'm currently trying to get to grips with what is possible. My question is regarding subscriptions.
The site that I'm working on needs to support subscriptions. It has a single, flat rate plan which would charge users monthly. Not only that but it requires that once a user/guest has subscribed to a plan, they are then registered as Craft users. So far I have set up the plan in Stripe and in Craft using the standard template below.
{% set plans = craft.commerce.getPlans().getAllPlans() %}

{% for plan in plans %}
<form method="post">
    <input type="hidden" name="action" value="commerce/subscriptions/subscribe">
    <input type="hidden" name="planUid" value="{{ plan.uid|hash }}">
    {{ csrfInput() }}

{{ plan.name }}

    {% set paymentSources = craft.commerce.
        getPaymentSources().
        getAllGatewayPaymentSourcesByUserId(
            plan.getGateway().id,
            currentUser.id ?? null
        )
    %}

    {# if we don’t have a saved payment soruce, collect details for the gateway #}
    {% if not paymentSources|length %}

            {{ plan.getGateway().getPaymentFormHtml({})|raw }}

    {% endif %}

    <button type="submit">{{ "Subscribe"|t }}</button>
</form>
{% endfor %}

When I try to submit this form it simply reloads the current page. Nothing is recorded in Stripe or Craft. Not too sure why this would be.
Ideally what I'd like is for a user to subscribe to a plan and simultaneously register themselves as a user on the site, so that they would be able to log in and out. Is Commerce able to support user registration when purchasing a subscription?


texts:
Running into a weird issue with the site build I'm working currently:

We're creating users based on email addresses coming from an event platform API and are sending activation emails to those users (from our plugin,
using craft()->users->sendActivationEmail($user)).

The email gets sent out but the activation {{link}} is missing the host part of the URL. Instead we're seeing links like this: http:/actions/users/setpassword?code=bo2EDjfC7ebsrEpsx5T%7EyJ2Q6TRR0bI6&id=912b5712-89f6-4dbc-9337-dec15b518536.

Add the host in between and the link works perfectly. I've tried setting a {{ siteUrl }} specifically the locale I'm in but that doesn't do the trick either.

When I go to the new user in the back-end and copy the activation URL there, that one is correct.

Any pointers as to what might be causing this? Thanks!

UPDATE

This is the craft/config/general.php we're using:

<?php

if (!defined('PROJECTCODE')) {
    define('PROJECTCODE', strtolower('seapla'));
}

if (!defined('ENV')) {
    switch (strtolower($_SERVER['DOCUMENT_ROOT'])) {
        case '/data/sites/web/'.PROJECTCODE.'/subsites/'.PROJECTCODE.'.live.be/public';
            define('ENV', 'live');
            break;

        case '/data/sites/web/'.PROJECTCODE.'/subsites/'.PROJECTCODE.'.staging.be/public';
            define('ENV', 'staging');
            break;

        default:
            define('ENV', 'local');
            break;
    }
}

$settings = [
    'subscriptionPrice' => 275,
    'subscriptionPeriod' => 'P1Y',
    'invoicePrefix' => 'ECF2017',
    'autoLoginAfterAccountActivation' => true,
    'useEmailAsUsername' => true,
    'setPasswordPath' => '_members/_reset',
    'logoutPath'=> 'e-learning',
    'defaultCpLanguage' => 'en_be',
    'defaultWeekStartDay' => 1,
    'logoutPath' => 'logout',
    'enableCsrfProtection' => true,
    'omitScriptNameInUrls' => true,
    'postCpLoginRedirect' => 'entries',
    'addTrailingSlashesToUrls' => false,
    'defaultSearchTermOptions' => array(
        'subLeft' => true,
        'subRight' => true,
    ),
    'environmentVariables' => [
        'basePath' => getcwd(),
        'baseUrl' => strtolower((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https://' : 'http://') . $_SERVER['SERVER_NAME']),
    ],
    'siteUrl' => strtolower((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https://' : 'http://') . $_SERVER['SERVER_NAME']),
];

switch (ENV) {
    case 'live':
        $settings['devMode'] = false;
        $settings['cache'] = true;
        break;

    case 'staging':
        $settings['devMode'] = true;
        $settings['cache'] = false;
        break;

    default:
        $settings['devMode'] = true;
        $settings['cache'] = false;
        break;
}

return $settings;


texts: Encrypt ID on front-end and decrypt on back-end

texts: I have a front-end form that posts through the ID of a particular element/entry to a back-end controller. Is there any way to encrypt/hash that ID on the front-end, so the plain ID number is not visible, and then decrypt that ID in the back-end controller?


texts:
I am having problems with the ContactForm plugin. It stopped sending mails.
I'm getting following error after submitting "Could not instantiate mail function."

PHPMail should be working.
I checked with a simple php outside of craft. Also the sendmail option in ContactForm does not work.

I don't now when it stopped working. I thought when I added a second locale, so I added a new test single including a from with only one locale. But that single cannot send the form, too.

Craft Pro 2.3.2626
ContactFrom 1.4


texts: Replace placeholder string in text field with HTML generated by Asset query

texts:
I have a Matrix block with a text field and an Assets field. The text field has a Markdown filter applied to it.

I'd like the content owner to be able to enter a placeholder reference to one of the images uploaded to the sibling Assets field.

For example, when the template processes…

This is a **paragraph**.

%%img2%%

This is some more text.

…then %%img2%% (or some such syntax that won't conflict with Markdown) gets replaced with the HTML generated for the second image by the relevant Assets query running in the template.

I've done things like this before with MXjumper and ExpressionEngine but am pretty new to Craft and not sure how to go about it.

I figure I need to:

Set a dynamically named variable (because I don't know in advance how many images are in the image field)
Use replace on the text field, but the replace statement should incorporate dynamically named search strings and the replacements would be the variables named at step 1 not strings.

Really not sure how to execute either of these 2 steps in Twig.

Would something like the following work for step1?

{% for img in sectionImages %}
    {% set n %}{{ loop.index }}{% endset %}
    {% set img ~ n %}

        {% if img.caption|length %}

            <span{{ img.caption }}

        {% endif %}

    {% endset %}
{% endfor %}

And what then for step 2…

{{ block.sectionText|markdown|replace('%%img' ~ n ~ '%%': img ~ n) }}

My step 1 code feels like it's close but I suspect it's not right. And in any case I feel sure my step 2 code is further off from what's needed.

I think maybe I need to be storing img as key|value pairs in an array and working with that somehow.

Any pointers much appreciated.


texts: Adding items to cart from related entry not working

texts:
Folks:

I have a list of accessories related to a main product. After adding the main product to the cart, the user can then add accessories related to that product.

The code seems to check out. The price and purchasableId for the related product are coming through just fine. However, when you click the "Add to Cart" button for the related product, the page refreshes but nothing is added to the cart. Relevant code:

{% set cart = craft.commerce.cart %}
{% for relatedProduct in product.relatedAccessories %}

{{ relatedProduct.title }} - {{ relatedProduct.accessoryDescription }} - {% for variant in relatedProduct.variants %}{{ variant.salePrice|currency('CAD', true) }} - {{ variant.purchasableId }}{% endfor %}

 <form method="POST">
    <input type="hidden" name="action" value="commerce/cart/updateCart">
    <input type="hidden" name="redirect" value="commerce/cart">
    <input type="hidden" name="qty" value="1">
    {% for variant in relatedProduct.variants %}<input type="hidden" name="purchasableId" value="{{ variant.purchasableId }}">{% endfor %}
    <input class="btn  btn-d  btn-lg" type="submit" value="Add to cart">
</form>
{% endfor %}
{% endfor %}

The source code for the rendered page looks like this:

Accessory description - $50

<form method="POST">
    <input type="hidden" name="action" value="commerce/cart/updateCart">
    <input type="hidden" name="redirect" value="commerce/cart">
    <input type="hidden" name="qty" value="1">
    <input type="hidden" name="purchasableId" value="65">
    <input class="btn  btn-d  btn-lg" type="submit" value="Add to cart">
</form>

As far as I can see, this should be working. But again, nothing is added to the cart.

Does anyone have any ideas?


texts:
I am trying to setup some products in my test website. I am unsure how I should go about creating the products. Should each product category be created as a product type?

An example is, if I have some art, how should I construct the products?

Imagine if I have these different "things" on the shop:

Prints
Paintings
Illustrations
Something
Something Else

I tried to create a different product type for each but then I ran into issues because I needed a template for each product type. Also I couldn't view the archive page.

Should I create an "Art" product type and work out a way to display these? Or just create each as individual product types?

I am also confused about templating with archive/entry pages. Say if I have  templates/shop/art/_entry.twig does craft automatically know that the archive template should be in the same directory?


texts: phpdotenv with multi-lang Craft setup on MAMP

texts:
I inherited a Craft site which uses phpdotenv (which I'm unfamiliar with) and which I now have to make multi-lingual (https://craftcms.com/docs/localization-guide) with an added es and fr locale on top of the english language site.
The question is regarding the setup on MAMP which seems to never find the .env file.
On my production server in /es/index.php this works:

// Composer autoload
require_once('../../vendor/autoload.php');

// DotEnv
try {
    $dotenv = new Dotenv\Dotenv('../../');
    $dotenv->required(['DB_HOST', 'DB_NAME', 'DB_USER', 'DB_PASS']);
} catch (Exception $e) {
    exit('Could not find a .env file.');
}

// Path to your craft/ folder
$craftPath = '../../craft';

// Tell Craft to serve the spanish content
define('CRAFT_LOCALE', 'es');

However, the same code on my local MAMP install will not find the .env file no matter what path I enter into the new dotenv statement....
Anyone have any idea or suggestion? Truly stumped here.


texts: How do I view / output the gateway response message?

texts:
I'm working through the integration of a new Authorize.net gateway and bumping into errors trying to successfully process payments.

How do I view / output the response that's coming back from Authorize.net after the failed transactions in my template for debugging purposes?

I spit out {{ dump(paymentForm) }}, but I'm not seeing anything especially insightful.


texts: Craft periodically goes down due to plugin migrations

texts:
Our application seems to be crashing periodically, on a seemingly unknown cadence. Sometimes it goes down once every few days, and sometimes (like today, when I'm at the end of my rope) it goes down 30 times a day or so.

When hitting the site on the frontend, the user gets a message saying that the site is unavailable; the maintenance mode error message. When we visit the admin panel, we are prompted to update two of our plugins, Geo and Embedder. After performing the updates the site comes back online.

In the craft logs before the site goes down, we're hit with a bunch of 404 errors:

Level       error
Category    exception.Craft\HttpException.404
Message     Craft\HttpException in /var/www/vhosts/production/craft/app/controllers/TemplatesController.php:72

these range from requests trying to hit /wp-admin and other random pages

Then it looks like the site goes down, because then we get hit with 503s:

Level       error
Category    exception.Craft\HttpException.503
Message     Craft\HttpException in /var/www/vhosts/production/craft/app/etc/web/WebApp.php:971

When we hit /admin, the logs show the following:

******************************************************************************************************
2018/06/02 20:52:43 [info] [application] [Forced] Preparing to update embedder.
2018/06/02 20:52:43 [info] [application] [Forced] Finished preparing to update embedder.

******************************************************************************************************
2018/06/02 20:52:43 [info] [application] [Forced] Starting to update the database.
2018/06/02 20:52:43 [info] [application] [Forced] The plugin "Embedder" wants to update the database.
2018/06/02 20:52:43 [info] [application] [Forced] Running migrations...
2018/06/02 20:52:43 [info] [application] [Forced] No new migration(s) found for the plugin Embedder. Your system is up-to-date.
2018/06/02 20:52:43 [info] [application] [Forced] Taking the site out of maintenance mode.
2018/06/02 20:52:43 [info] [application] [Forced] The plugin "Embedder" is done updating the database.

******************************************************************************************************
2018/06/02 20:52:43 [info] [application] [Forced] Starting to clean up after the update.
2018/06/02 20:52:43 [info] [application] [Forced] Clearing the update cache.
2018/06/02 20:52:43 [info] [application] [Forced] Flushing update info from cache.
2018/06/02 20:52:43 [info] [application] [Forced] Finished Updater.
2018/06/02 20:52:43 [info] [application] [Forced] Finished cleaning up after the update.

Now I don't think this is related to those two plugins; I think either Craft is getting out of sync somehow, or something is up with our cloud database.

Has anyone run into this issue before? What would be forcing the plugin migrations to initiate again and again, to make updates to the same database?


texts: How should I include my custom enums class in my plugin?

texts:
If I was going to include my custom enums for my plugin, should the include be outside of my plugin class or use the init() method. What is the best way to handle this and are there any pros or cons to either?

Current method:

<?php
namespace Craft;

// include enums for custom statuses
include(dirname(__FILE__) . '/enums/PluginNameEnums.php');

class PluginNamePlugin extends BasePlugin
{
    // etc
}


texts: My account is locked and I cant figure out how to unlock it. I tried resetting the password, but have yet to receive an email with a new one. Is there an alternative way to logging back on? I recently changed the password and because it is a shared dashboard, I think someone (who was unaware of the pw change) may have tried logging in too many times which is how the account locked.


texts:
Is there a way to make fields conditionally required?

I have a toggle field that is used to hide or show a section (see screenshot: "Section 3 enabled"). If the section is shown (toggle: on), the fields need to be filled. If the section is hidden (toggle: off), the  fields can be left empty.
Note that the section's fields can be of any type (text, matrix, entry, assets, ...).

I already tried the plugin Reasons, and unfortunately it's not what I need because it will still return a validation error for the hidden but required fields.

My Craft CMS version is 2.6.2983.


texts:
When installing a plugin from the plugin store I get a popup telling me:
"The git command requires the command line developer tools. Would you like to install the tools now?"
"Choose Install to continue. Chose Get Xcode to install Xcode and the command line developer tools from the app store."
Options are "Get Xcode", "Not now" and "Install"
I tried just clicking Install, and it seems to have worked but I got another prompt like above at the end. So I don't know if something will fail sometime down the line or not.
After installing on my local Mamp setup it's not obvious which files I need to upload to the live server as there isn't a plugin folder. I only installed 2 plugins and 12 folders in the Vendor folder showed updated files in them.

I don't use git, I don't use the command line and I didn't install Composer and I don't really want to in the future either. I just want to keep things simple. Does this mean that I won't be able to use Craft now unless I become a command line expert?
Even the Mijingo video tutorials which have been really easy to follow in the past have started to be full of complicated command line stuff.
I have a rubbish memory and only use a few keyboard shortcuts as I can't remember more than 3 or 4, so remembering all those command line options isn't going to happen.


texts:
I am trying to get to grips with Eager Loading. I have the following code:

{% for article in entry.relatedArticles %}

            {% set array = article.title|split(' ', 2) %}

{{ attribute(array, 0) }} {{ attribute(array, 1) }}

Posted on {{ helpers.date_formatted(entry.postDate) }}

Related Article

                        {{ article.title }}

                        <time datetime="{{ entry.postDate|date('Y-m-d H:i:s') }}" class="date">
                            <svg role="img" class="icon // icon-date" title="Date Icon">
                                <use xlink:href="/assets/img/icons.svg#icon-date"></use>
                            </svg>{{ helpers.date_formatted(entry.postDate) }}
                        </time>

Read Article

{% endfor %}

Looking on the console this combined with the other page requests totals 76 requests. I thought I perhaps should add some eager loading 9at least tot he image transform) So I tried the following:

{% for article in entry.relatedArticles.withTransforms('cardImage') %}

            {% set array = article.title|split(' ', 2) %}

{{ attribute(array, 0) }} {{ attribute(array, 1) }}

Posted on {{ helpers.date_formatted(entry.postDate) }}

Related Article

                        {{ article.title }}

                        <time datetime="{{ entry.postDate|date('Y-m-d H:i:s') }}" class="date">
                            <svg role="img" class="icon // icon-date" title="Date Icon">
                                <use xlink:href="/assets/img/icons.svg#icon-date"></use>
                            </svg>{{ helpers.date_formatted(entry.postDate) }}
                        </time>

Read Article

{% endfor %}

However, this also still results in 76 requests.

So my question is this; Have I misunderstood when I need to use Eager Loading? or is my code incorrect and thus eager loading isn't actually taking place?

Thanks.


texts: Is it possible to set up Amazon's "Subscribe and Save" type feature for Craft Commerce

texts:
I'd like to allow customers to be able to automatically set up recurring purchases at a discounted price, much like Amazon's Subscribe and Save.

I had originally skimmed through the subscription portion of the documentation assuming this type of subscription would be supported, but soon realized that the current implementation is more meant for service-based subscriptions (for instance, it doesn't seem possible to add a subscription product to the cart).

I'm guessing at this point I will need to create a custom plugin to allow for a feature like this, but as a last resort decided to post my question here in case someone has needed something similar and had success.


texts:
Using the Sprout Email plugin. The only notification triggers that are working are related to users. Any notifications with triggers related to entries (created, updated, deleted) do not send an email, not even a test email.

I'm using Craft Client 2.4.2688.


texts:
I have a matrix field set up as global (strategies).
Inside each matrix block there is a SuperTable (pairs)
On each row in the SuperTable there is a lightswitch (active)
I need to toggle the lightswitch programatically for each row.
Looking at the SuperTable and Craft docs, I still can't make heads or tails of this. Can anyone help?
Edit
Ended up with a poor man's solution by going directly to the table and editing the column. Would still love to know how to do this "properly, though.
$disable = StcThreePairs::find()
    ->where(['elementId' => $pair->id])
    ->one();

$disable->field_active = 0;
$disable->save();


texts:
I have written a plugin that works fine, it has a subnav which i build like so:

public function getCpNavItem()
  {
    $item = parent::getCpNavItem();
    $item['subnav'] = [
      'moderateentries' => ['label' => 'Moderate Entries', 'url' => 'entry-moderator'],
      'notificationmessages' => ['label' => 'Messages', 'url' => 'entry-moderator/notificationmessages'],
      'log' => ['label' => 'Log', 'url' => 'entry-moderator/log'],
    ];
    return $item;
  }

Problem i am having is that i cannot get the left hand nav item to display as active, the only one that has the sel class applied is 'moderateentries', if i click on the second or third nav item, the first one is the one that is displayed as active with the sel css class. where am i going wrong?


texts: Craft 3 Plugin not returning custom field value

texts:
I am trying to get the value of a custom field in entries, but I can't seem to get it to grab that value. I'm assuming I'm pulling it too early or too late, otherwise I have no idea.

I can pull the value the of the lightswitch enabled

Event::on(Elements::class, Elements::EVENT_AFTER_SAVE_ELEMENT, function(Event $event)
    {
        $request = Craft::$app->getRequest();

        // will successfully send email if enabled lightswitch is on
        if($request->getBodyParam('enabled') == 1)
        {
            $html = $request->getBodyParam('enabled');
            $subject = "testing";
            $mail = "example@gmail.com";
            return $this->sendMail($html, $subject, $mail);
        }
    });

The below doesn't return anything at all for the custom field fields[sendEmail]

Event::on(Elements::class, Elements::EVENT_AFTER_SAVE_ELEMENT, function(Event $event)
    {
        $request = Craft::$app->getRequest();

        // will not send email no matter what position the lightswitch is in
        if($request->getBodyParam('fields[sendEmail]') == 1)
        {
            $html = $request->getBodyParam('fields[sendEmail]');
            $subject = "testing";
            $mail = "example@gmail.com";
            return $this->sendMail($html, $subject, $mail);
        }
    });

I tried changing the event handler to EVENT_BEFORE_SAVE_ELEMENT but it made no difference.


texts:
I have a plugin that I developed in a symlinked folder locally.
I now want to deploy it to production.
But when I do composer require namespace/pluginhandle it gets symlinked.

What I want is to install it just like all the other production plugins - without a symlink.

I couldn't find instructions on how to do this in the docs.


texts: Splitting a Twig Variable into 2 Variables

texts:
I want to split my variable into two new variables before and after the dash character "-".

How do I adjust my code below to enable this to happen?

{% set name = 'first-last' %}
{% set firstNameSlug = name|split('-')[1] %}
{% set lastNameSlug = name|split('-')[2] %}

{{ firstNameSlug }}
{{ lastNameSlug }}


texts: Can a field type detect if it's being edited inline in Craft 2.3?

texts: Is there was a way for a field type to detect if it is being instantiated for the inline editor or even the live preview? I am working on some responsive UI's to make Google Maps for Craft work optimally on all screen sizes, but current smaller screens are posing a problem. Obviously media queries are being used, but was also wondering if I could easily detect where the field type was being instantiated and then I could possible add additional classes to my field type wrapper.


texts: How to hide createAccount select by default • Charge 2 Plugin

texts:
I'm adding a basic annual subscription to a portion of a website.

I have Registration Behaviour set to
Always - creates an account for all guest payments

But on the subscription form the createAccount select still appears (Save my account, No don't create an account".

I'm including the customerDetails fields like this:

{% include 'charge/_includes/inputs/customerDetails' with { 'registerGuest' : true }%}

I see the form logic in customerDetails.html but that doesn't feel like something that should be edited.

I want to remove the select, since I should always be creating a new account by default OR I want to replace it with a hidden field.


texts: Admin assets not being served over https

texts: I switched my craft install to be completely served over SSL. The front end continued working fine, but the backend is 404'ing all static assets. I assume this is because the http was handling the /admin/resources/ rule fine but not the https. I'm using NGINX but am using the exact same config that I was before, just adding in my SSL Certificate keys. Any thoughts on config settings to look at or lines of code to investigate?


texts: Can plugins in the Plugin Store require development versions of libraries via Composer?

texts:
I recently put together a basic Constant Contact plugin for a project, and I'd like to clean it up and improve it for a public release. The problem is that it requires a development version of the Constant Contact SDK for compatibility with PHP 7+. I did this by adding a custom repository to the composer.json file pointing to the github repo, and then requiring the development branch.

"repositories": [
  {
    "type": "git",
    "url": "https://github.com/constantcontact/php-sdk.git"
  }
],
"require": {
  "craftcms/cms": "^3.0.0-RC1",
  "constantcontact/constantcontact": "dev-development"
},

In order for this to work, I had to change the stability requirements in my main composer.json file:

"minimum-stability": "dev",
"prefer-stable" : true,

It seems to me this would not be ideal for a plugin in the Plugin Store. Is packaging all of the dependencies up into a vendor subfolder within the project a better option?


texts: How do I include custom fields of an entry type in the Guest Entries form?

texts: I want any visitor to be able to submit links to my blog via the Guest Entries plugin, but how do I include the custom fields of my "Links" entry type in the Guest Entries form? For example, a category field, text fields...


texts: Disabled entries don't show up in the Linked entries field when displayed in the CP entry list

texts:
As you can see, I would like to see what challenge the submission is linked to, even though that Challenge might now be turned off (expired or disabled).  Is this a bug or intended behaviour.  Is there an easy way to get this up and running?

If it's intended, I'm not sure why there's a green "enabled" dot on it, there's no way they can be anything else.

In my screenshot, the field Challenge is an entry field and the entry "Challenge #1" is assigned to, but is now expired and not showing in the table.


texts: Set email recipient based on value of select in freeform - possible?

texts:
Basically I have a select in my freeform, say with values catalogue A, catalogue B, catalogue C.
Is it possible to set the email recipient depending on the value that the user will select? e.g. requests for catalogue A,B should go to one email address, catalogue C to another one. Any advice appreciated!


texts: Database Exception Column not found: 1054 Unknown column 'configVersion' in 'field list'

texts:
I get this Error when i want to save a Field. Also when i want to create a new field. I can hit the goback button and strangely the field gets still saved.
I work local and have project config activated. At the moment i have no idea where to begin to eliminate that error.
I hope someone can help.


texts: Ordering Looped Results by Field's Numerical Value

texts:
I’m looping through some text fields on the form results page and need to order the numerical output from low to high.

How would I do this using twig?

{% for field in submission %}
  {% submission[field.handle].value %}
{% endfor %}

Note: I am using the Freeform Plugin. They have informed me that I would need to create a custom filter but before I do that wanted to see if there was a better way to do this.


texts: Can I apply an image transformation to an arbitrary image (non-Assets field)?

texts:
Curious if I'm able to use the resizer on a random, sourced image, not coming from a field anywhere.

So I would just be passing a string to the path of the image.


texts:
The development site works locally, but on a live hosted server the admin CSS is missing. The admin JS shows up. The public-facing site works fine on the live server and I can log in to the admin area, but with the admin CSS missing, the admin area is nearly useless. A few potentially useful pieces of information:

I followed the Craft "Troubleshooting Missing CSS/JS in the Control Panel" instructions  and verified that zlib.output_compression is disabled.
The generated CSS links from the admin area look like they should work, especially since the JS links do work.
I'm running PHP 7.0.0 locally, using MAMP.
The hosting company, Nexcess, is running PHP 7.0.6 on my account.

I'm stumped as to why this is happening or how to troubleshoot it.


texts: Contact Form email address set in the plugin's setting being changed by Linode server?

texts:
I've used the contact form plugin many times with no issues. However I have a site set up on a Linode server and for some reason the from address that I have added in the contact form settings e.g. contactus@mydomain.com is being changed to contactus@localhost.localdomain when the email comes through.

Anyone any ideas what is causing this. I'm thinking it's a server setting but wanted to check the plugin wasn't causing anything weird to happen as well.

Cheers


texts: How can I check from a plugin config file if devMode is enabled?

texts:
Using the Pixel & Tonic Contact Form plugin, I added a config file (config/contactform.php) to override plugin settings from the CP.

I would like to change some settings if devMode is enabled : recipients from the contact form plugin, to separate my tests addresses from my client addresses.

<?php

$recipients = array(
    'devMode' => 'example@domain.com,example@domain.com',
    'prodMode' => 'john@doe.com,jean@dupont.com'
);

if (devMode == true) {
    $recipients = $recipients['devMode'];
} else {
    $recipients = $recipients['prodMode'];
}

return array(
    'toEmail' => ($recipients ?: null),

How can I check if devMode == true? Can I access to this value using craft()->config or something else that?


texts:
How do you get a list of the fields that are on an entry?

I tried {{ dump(entry.subentry) }} but that isn't any help ...


texts: Display news (from a channel) on the Homepage

texts:
I have started my very first Craft project (coming from EE) - so, apologies if this is a to simple question.

On the homepage I want to display the latest news entry - and short excerpts from a few older ones. No other type of entries on the page.

Question: Should the section type of the homepage be a "channel" then, or a "single"? Or is there a something completely different way to do this?


texts: GraphQL query order entries by Lightswitch and DateTime field

texts:
I have an entries with the "highlighted" lightswitch that puts entry on top of the result list when enabled, also I need to sort items by post date. So, in the end there should be the following order: highlighted entries ordered by date, then other entries also ordered by date
I am using orderBy: "platformHighlighted DESC, postDate DESC" variable, however I see the postDate ordering is broken in the middle of the list
Is there something I do wrong in the query?
Thank you


texts: Checking if a matrix field with entries has more than one entry

texts:
In my HTML-prototype I have two ways of showing a module of employees. One version shows one employee, and the other shows two.

To build this in Craft I have setup a Matrix field (with a handle named 'contactMatrix'). It contains a headline, some text and an entry field to pick employees (with a limit of two).

To output this in my front end I need a way to check if the user has picked one or two employees. Something like:

if one employee within the matrix field is chosen
do this html
else
if two employees within the matrix field is chosen
do this slightly different html
end if

Help, anyone?


texts: Add a column to entries list using defineAdditionalEntryTableAttributes?

texts:
What I'm looking for is to add in a custom column that either has a checkmark or not based on if the entry's slug has a certain set of characters.

Example:

This would get a check: sluggyslug-SC_01234X

This would not: sluggyslug

I would be looking at the slug and matching via regex for the SC_XXXXX portion.

I see there is the hook defineAdditionalEntryTableAttributes and getEntryTableAttributeHtml but I get an error when I try to set them.

The code I tried in my plugin:

public function defineAdditionalEntryTableAttributes()
{
    return array(
        'something' => "Some Column",
    );
}

public function getEntryTableAttributeHtml(EntryModel $entry, $attribute)
{
    if ($attribute == 'something')
    {
        if (preg_match("/(?:SC_\w{5})$/", $entry->slug)) {
          return '
&#x2713;
';
        }
    }
}

If I try to add the column, I just get this via the getElements ajax call.

CException
Property "Craft\EntryModel.something" is not defined.

Is there anyway to add a column like this?


texts: Sometimes getting sent to /admin/undefined after login

texts:
After logging in to the Craft admin area I sometimes(!) get routed to /admin/undefined instead of /admin/dashboard.

Anyone knows were to start looking to solve this issue?


texts: How to create a template file for Categories?

texts:
below is my categories url.

http://example.com/index.php?p=categories/vaporizers

i create a template files for categories like

templates/categories/index.html
templates/categories/_entry.html

my index.html is not called when categories view. please tell me where i create a mistake.

Thanks


texts: Solspace Calendar: custom fields not outputting

texts:
I'm unable to get custom fields to output using Solspace Calendar on Craft3. I am not getting any errors indicating that the field does not exist, it's just not outputting. The field is a Redactor type.

{% set event = craft.calendar.event(segment2, {targetDate: occurrenceDate}) %}

{% if event %}

{{ event.title }}
 {# THIS OUTPUTS #}
        {{ event.eventDescription }} {# THIS CUSTOM FIELD DOES NOT OUTPUT AND THERE ARE NO ERRORS #}

{% endif %}

UPDATE: I tried using the field handles that are in the Solspace Calendar templates (location and description), but neither of those output:

{% if event['location'] is defined %}

        Location

            {{ event.location }}

{% endif %}


texts: How to update Matrix field on frontend for user profile

texts:
I have used the following code to allow our users to update their own profile. Everything works fine apart from not being able to update existing Matrix entries.

New Matrix field entries work fine. Can anyone spot the mistake I've made?

          <form method="post" accept-charset="UTF-8">
          {{ getCsrfInput() }}
          <input type="hidden" name="action" value="users/saveUser">
          <input type="hidden" name="redirect" value="/account/profile">
          <input type="hidden" name="userId" value="{{ currentUser.id }}">

          First Name
          <input type="text" id="firstName" name="firstName" value="{{ currentUser.firstName }}">

          Last Name
          <input type="text" id="lastName" name="lastName" value="{{ currentUser.lastName }}">

          Telephone
          <input type="text" id="telephone" name="fields[telephone]" value="{{ currentUser.telephone }}">

Additional Contacts

          <input type="hidden" name="fields[alternativeContacts]" value="">

          {% for block in currentUser.alternativeContacts.type('contact') %}

            <input type="hidden" name="fields[alternativeContacts][{{ block.id }}][type]" value="contact">
            <input type="hidden" name="fields[alternativeContacts][{{ block.id }}][enabled]" value="1">

            <input type="text" name="fields[alternativeContacts][{{ block.id }}][fields][firstName]" value="{{ block.firstName }}">
            <input type="text" name="fields[alternativeContacts][{{ block.id }}][fields][lastName]" value="{{ block.lastName }}">
            <input type="text" name="fields[alternativeContacts][{{ block.id }}][fields][telephone]" value="{{ block.telephone }}">
            <input type="email" name="fields[alternativeContacts][{{ block.id }}][fields][email]" value="{{ block.email }}">

            <button class="btn btn-xs btn-danger" data-action="delete-contact"></button>

          {% endfor %}

New Contact

            <input type="hidden" name="fields[alternativeContacts][new1][type]" value="contact">
            <input type="hidden" name="fields[alternativeContacts][new1][enabled]" value="1">

            <input type="text" name="fields[alternativeContacts][new1][fields][firstName]">
            <input type="text" name="fields[alternativeContacts][new1][fields][lastName]">
            <input type="text" name="fields[alternativeContacts][new1][fields][telephone]">
            <input type="email" name="fields[alternativeContacts][new1][fields][email]">

          <input type="submit" value="Save Profile">
      </form>


texts: When clicking blogposts it redirects me to localhost

texts:
I've installed CraftCMS on my localhost in a subfolder called blog, when creating a new blogpost and clicking on the link it redirects me to my localhost instead of the blogpost.

This video should show what happens.
https://gfycat.com/DemandingBitterGoldenmantledgroundsquirrel

My index php looks like this:

<?php

// Path to your craft/ folder
$craftPath = '../../craft';

// Do not edit below this line
$path = rtrim($craftPath, '/').'/app/index.php';

if (!is_file($path))
{
    if (function_exists('http_response_code'))
    {
        http_response_code(503);
    }

    exit('Could not find your craft/ folder. Please ensure that
$craftPath is set correctly in '.__FILE__);
}

require_once $path;

Could someone please advise me on how I can get the posts to upload correctly?


texts:
I thought that a simple .fixedOrder(true) would make the files order in the same way as in the CMS. Instead of that, there is no output. Where I go wrong?

{% set files = craft.assets.kind('pdf,word,excel').fixedOrder(true) %}

                {% for file in files %}

                    {{ file }}

                {% endfor %}


texts:
I'm having an issue with the login-page and since this is my first Craft website, I'm a little unsure of where to begin to look.

When attempting to log in to the admin interface, my username/password is rejected only with the message "An unknown error occured". The same goes for trying the "Forgot your password?" function.

As far as I can tell, the only change recently made was running the auto-update to the latest version (2.X) last week. Have not logged back in since, so this could very well be the culprit. The front end loads just fine. I do have a couple of plugins installed, but not sure how I can deactivate them without using the admin interface.

Are there some log files in the /craft folder where I can start to look?

Any help much appreciated.


texts: Can't find the "share entry" functionality

texts:
I have Craft Pro (2.1.2564) and cannot locate the "share" functionality outlined below.
When I edit an entry, The Live Preview button in Chrome (OSX) has only the Live Preview button with the eye icon and then an arrow. That row triggers the Live preview and not any sharing function.

http://buildwithcraft.com/updates#build2554
Added a “Share” button next to entries’ Live Preview button, which opens the current entry/draft/version on the front end, with a tokened URL that can be shared with others without requiring them to be logged in.


texts: How to use a note from the Line Item Model

texts:
Working with the example Commerce templates. In the cart template there is an example for adding a note. https://craftcommerce.com/docs/line-item-model#note

The code for this form:

<form class="shopForm" method="POST">
<input type="hidden" name="action" value="commerce/cart/updateLineItem">
<input type="hidden" name="redirect" value="shop/cart">
<input type="hidden" name="lineItemId" value="{{ item.id }}">
{{ getCsrfInput() }}

    Note
    <input type="text" size="20" name="note" value="{{ item.note }}">

    Quantity
    <input type="number" name="qty" min="1" value="{{ item.qty }}">

<input type="submit" class="btn btn-outline" value="Update">

Very useful but after submitting the form, how can we display this later on in the ordering process? For example on a receipt or the order overview. Also can we view this in the Commerce back end? I was not able to find …

Can anybody shed some light? Thanks!


texts: How do I get tags to only display on posts that have that tag?

texts:
I’m trying to add tags to my blog posts.

I’ve created a tags group with the handle ‘default’.

In Setting/Fields I’ve got a field called bodyElements which is setup as a matrix, and within bodyElements I’ve added to the Configuration a block type called Tags with a handle of ‘tags’, and then within that there’s a field called Tags with a handle of ‘blogTags’ and this is set as the Field Type of “Tags” and the Source is set as “Tags”.

Now when I go to a blog post, I can type in my content and click the button to add a Tag. I can then type in a tag and it attaches to that particular entry.

The issue I’m having is that when I view the blog posts on the front end, the tags are showing up on every single post, even though they don’t have those tags attached to them.

On https://craftcms.com/support/active-tags it says to insert the following code to display only the tags that are in use

{% set entries = craft.entries.section('news').limit(null) %}

    {% for tag in craft.tags.relatedTo(entries) %}

{{ tag.title }}

    {% endfor %}

but that doesn’t display the tags at all.

My blog section has a handle of ‘blog’, so in the above code I tried replacing ‘news’ with ‘blog’ and still no tags appear.

The only way I can get tags to appear on my posts is by using the following code:

{% for tag in craft.tags.group(‘default’) %}

{{ tag.title }}

{% endfor %}

but the above code caused the tags to appear on every single blog post, even if they’re not tagged with anything.

How do I get the tags to only appear on the posts the tags are attached to?

Thanks.


texts: How to display multiple entry loops on the homepage (Single section type)

texts:
I've been learning Craft 3 for a couple weeks and I've run into a little snag. I have a homepage that I would like to display multiple entry loops and/or types. However, I cannot find how to do this on a Single (section). Ive been experimenting around, and I can get the desired effect by making the homepage a Structure (section) via multiple entry types, but that gets janky with the URL/URi setup (I've seen other articles saying to use the __home__ method, but seems like it gets messy to try and work around that with sub-pages).

Here is kinda what I'm going after for the homepage:

Hero Element (has a few of it's own fields)

Intro Element (has a few of it's own fields)

Image Slider Element (loops through some image asset entries)

MAIN ENTRY LOOP (loops through some entries that you click to go to the full entry (which has its own template))

So in summary,
How can I have multiple entry loops/types on a Single, OR Use a Structure section as the homepage without getting to janky with the URL/URi? OR is there a better way to set this up that I'm not thinking of?


texts: yii\web\ServerErrorHttpException Craft 3 install

texts:
I'm new with Craft CMS and receive this error when I try to install it

-------------------ERROR-----------------------------
An Error occurred while handling another error:
yii\web\ServerErrorHttpException: The info table is missing its row in C:\xampp\htdocs\craft\vendor\craftcms\cms\src\base\ApplicationTrait.php:512


texts: Can images embedded in a Rich Text field be resized on output?

texts:
I see how to use Image Transforms when the image tag is its own field but don't see a way to handle images within Rich Text fields or force a size on upload.

I need to have the image dimensions match the size the client sized the image to in the Rich Text field. Is there a way to do this?


texts: Performance issues from matrix vs rich text?

texts:
I'm finding myself using matrices a good deal on my site for a specific client. My client has little experience with any content management systems, and I liked the structure matrices could provide.

For example: Instead of having them use the rich text editor, each time of content they can use on a certain page is part of a matrix field. They can add an image, then add a paragraph below, then add a pull quote, then maybe another image or paragraph etc etc. I thought this gave me a great deal of control over the styling as well.

But I'm wondering if matrices have an effect on performance? I suppose I could use the rich text field, though I would have to hold my client's hand a bit more.

I'm noticing my initial time for anything to load onto the screen is pretty poor. I've followed some steps from Patrick Pohler on Craft performance optimization, and after the initial wait time my page loads fine, but I'm wondering if my use of matrices has something to do with my initial load time?


texts: One select search for Users in user.group

texts:
I'm a complete newby on Craft CMS and twig templating so please bear with me.

I currently have a users base which I want to filter by category (a custom field)

This would be my only input search element:

<select name="professionalita">
    <option value="" disabled selected>Professionalità</option>
    {% for category in craft.categories.group('professionalita') %}
    <option value="{{category.url}}">{{ category.title }}</option>
    {% endfor %}
</select>

This is what I tried to build on results.html page.

{# Get the search data #}
{% set profParam = craft.request.getParam('professionalita') %}

{% extends "_inc/layout" %}

{% block main %}
    {# Find and list matching entries #}
    {% set members = craft.users.group.('members').relatedTo(profParam) %}

    {% if members|length %}

            {% for member in members %}

{{ member.firstName }}

            {% endfor %}

    {% else %}
        No members found.
    {% endif %}
{% endblock %}

I get no results even if there are actually correspondencies between the users and the category name being searched for.


texts: Craft 2: possible to control plugin triggering order?

texts:
I have a Craft site which has 2 different plugins listening to the same event (the Contact Form beforeSend event).
The outcome is one is being triggered before the other and this is causing issues. Is there any way of specifying the priority of one plugin over the other or ensuring that they happen in a specific sequence?
Cole


texts: Converting array of entries to an array of ids

texts:
If I've got an array of entries, is there a less long winded approach to convert that to an array of ids so I can use it in another lookup.

{# Look up authors that match the entered query.
{% set authorEntries = craft.users.search('fullName:*' ~ query ~ '*')|default([]) %}

{% set authorIds = [] %}
{% for author in authorEntries %}
    {% set authorIds = authorIds|merge([author.id]) %}
{% endfor %}

Thanks!


texts:
I am new to Craft CMS and am struggling with what and how to get the correct files in the right places. I started out with a LAMP stack on a Ubuntu 18.04 Digital Ocean droplet and proceeded with the Craft CMS setup. Currently I get a 404 ERROR stating "The requested URL /index.php was not found on this server".

Where should I put it? Does this answer help and still work in this case : https://stackoverflow.com/questions/5891802/how-do-i-change-the-root-directory-of-an-apache-server/23175981#23175981?

My VH file:

<VirtualHost *:80>
     ServerAdmin admin@example.com
     DocumentRoot /var/www/html/craftcms
     ServerName example.com
     ServerAlias www.example.com

     <Directory /var/www/html/craftcms/>
          Options FollowSymlinks
          AllowOverride All
          Require all granted
     </Directory>

     ErrorLog ${APACHE_LOG_DIR}/error.log
     CustomLog ${APACHE_LOG_DIR}/access.log combined

     <Directory /var/www/html/craftcms/>
            RewriteEngine on
            RewriteBase /
            RewriteCond %{REQUEST_FILENAME} !-f
            RewriteRule ^(.*) index.php [PT,L]
    </Directory>
</VirtualHost>


texts: How to apply an Image Transform on output from plugin PDF Transform

texts:
In an attempt to autogenerate PDF Thumbnails I found this Plugin, PDF Transform. The plugin works fine, but I'm trying to figure out how to apply a Craft Image Transform to the results. I'll preface this by saying I'm new to Craft so I'm sure I'm missing something simple, but I created a transform called pdfThumb, but I can't figure out how to apply it to the code needed for the plugin since it's not using the getUrl
Working Plugin code without the transform:
{% set rel = block.pdfFile.one() %}
{% set asset = entry.pdfAsset.one() %}

My obviously misguided attempt with Craft Image transform:

I've tried several variations of this but I'm obviouly on the wrong track and would appreciate any pointers.


texts:
I had a problem with my cloud server and all my sites were generating 500 errors. The response page the visitor saw varied between Craft 2, Craft 3 and ExpressionEngine 2 sites.
The Craft 3 ones showed:

  CDbCommand failed to execute the SQL statement: SQLSTATE[HY000]:
  General error: 1 Can't create/write to file '/tmp/#sql3fa0.MYI'
  (Errcode: 28)

Some showed what I think is the generic cPanel page:

  Internal Server Error

  The server encountered an internal error or misconfiguration and was
  unable to complete your request.

  Please contact the server administrator at webmaster@scottish6days.com
  to inform them of the time this error occurred, and the actions you
  performed just before this error.

  More information about this error may be available in the server error
  log.

  Additionally, a 500 Internal Server Error error was encountered while
  trying to use an ErrorDocument to handle the request.

Others a blank page.

I now want to have a nice/useful/descriptive 500 error page shown if it happens again.
So after reading up on this, in particular, the  NY Studio 107 article on error pages I want to be able to test if my new 500 error page does get shown when there is a real 500 error situation.

The hosting company suggested adding a 500.html file in the public_html, adding ErrorDocument 500 /500.html to my .htaccess and creating a script file with this in it:

<?php
ini_set('display_errors', 0);
throw new Exception('Test');
?>

and calling it in the browser, but it didn't work. Their response was:

  Sorry, in this case the HTTP 500 error is not caught by Apache in a
  way it can handle it. There are ways of doing PHP error handling in
  PHP, but it will depend on the application to do it for you.

Any suggestions as to how to test that it's all working properly?


texts: How can I get a user to choose in which group he registers using the User Registration Form

texts:
Is there a way to allow a registrant to choose a user group in the registration form?

I tried using the following code but it didn't work:

<input type="hidden" name="userGroups" value="3">


texts: Modifying Commerce line items after order is complete

texts:
I am in the process of building a gift card system for a Craft Commerce site. The current process is that the customer will order a gift card and proceed through checkout as with any other item.

The only information passed through the options is the amount, which is used to generate the gift card. The process works perfectly, and the gift card is generated exactly how it is supposed too.

The next step is to modify the line items using the event onBeforeOrderComplete or onOrderComplete. I would like to change the options to include the amount, and the gift card code.

This is the process I have at the moment, which is just one of the many variations that I've attempted. Nothing I do seems to change the options on the order.

craft()->on('commerce_orders.onBeforeOrderComplete', function($event) {
    $order = $event->params['order'];
    $items = $order->lineItems;

    foreach( $items as $key => $item ) {
        $type = $item->getPurchasable()->getProduct()->getType();
        if ($type->handle === 'giftCard') {
            $options = $item->options;
            $giftcard = new GiftCards_GiftCardModel();

            $giftcard->amount = $item->price;
            $giftcard->balance = $item->price;
            $giftcard->isActive = 1;

            craft()->giftCards->saveGiftCard($giftcard);

            $options['code'] = $giftcard->code;
            $items[$key]->options = $options;
        }
    }

    $order->lineItems = $items;
});

My only other solution is to generate the gift card code when the gift card is added to the cart and change the active status when order is complete. This would solve my problem completely, but it runs the risk of having hundreds or even thousands of gift cards generated and never completely activated.


texts:
I have a custom asset bundle defined in my plugin. My plugin has a controller. The controller has a action:

/**
 * Handle a request going to our plugin's index action URL,
 * e.g.: actions/entries-by-group/entries-by-group
 *
 * @return mixed
 * @throws \yii\base\InvalidConfigException
 */
public function actionIndex()
{
    $this->view->registerAssetBundle(EntriesByGroupAssets::class);
    $result = 'Welcome to the EntriesByGroupController actionIndex() method';

    return $result;
}

As you can see, I am trying to register my asset bundle. I am getting the error:

  ReflectionException

  Class recoveryfinder\entriesbygroup\assets\EntriesByGroupAssets does
  not exist

My namespaces are:

namespace recoveryfinder\entriesbygroup\controller;

or in the asset bundle file:

namespace recoveryfinder\entriesbygroup\assets;

My plugin is in a folder called (note the hyphens):

  vendor\recoveryfinder\entries-by-group\src\controllers\EntriesByGroupController.php

It seems that when code gets to ClassLoader::LoadClass I get the error referenced above - class does not exist. It looks to me like ClassLoader is using the namespace as the path spec (without the hyphens) rather than the actual location (with the hyphens).

I must need to set paths in my plugin? If not what is wrong here?


texts: I would like to be able retrieve all entries based on a category selected in a drop down list. From a UX perspective, I would like this to be as seamless as possible and not have to do full page refresh. Is this something I should build using the ElementAPI or is there better way to accomplish this?


texts:
I want to scan my user list to see if anyone hasn't been assigned to a group.

Is there a way to show user groups as a column at admin/users?


texts: Craft 2 CMS - How to change Limits in Dashboard

texts:
I'm very new to Craft CMS.

The company I work for, has their website build with Craft. The website was build by a 3rd party company, Now they gave me the responsibility to give the site a facelift.

Currently I'm struggling to increase the limit of services displaying on the home page.

We have 4 services, but only 3 display.

In the back end of Craft Dashboard, I can only assign 3 services, can I increase this to 4?

And if I can, how can I do it?

Looking forward to some feedback.


texts: Steps for integrating an HTML design to a website page and managing its content from backend

texts:
I am a beginner to Craft CMS. I have an HTML design for Craft integration. I need to covert this to a live URL page on my website. Also, I need to manage its content from the backend. I think we need to do something related to entries, but I don't know what part I need to do first and what to do second, etc. Can anyone please help for the steps needed for this?

Thanks in advance.


texts:
Is there any way of partially paying for an order, so if the order total amount was $100, how can I programmatically set the payment amount to $50, and then pay the other $50 using another payment method later on?
There was a way to do this in Craft2 using a custom plugin, but in Craft3 I tried using the Payments::EVENT_BEFORE_PROCESS_PAYMENT event but the variable is null in the $event->transaction.
Please let me know, thank you!


texts: How do you guys handle SEO? Do you just make your own meta fields and add them in the template manually or am I missing something? I did notice there are some plugins being developed but there are sites in the wild now so it's been handled some how. Thanks!


texts: How do I query for orders that were completed between two dates?

texts:
I am attempting to get orders that were completed between two dates and the "before" and "after" criteria parameters don't seem to work. Perhaps I am using the wrong syntax? Example of how I am using them:

.after('2017-06-02 00:00:00')


texts: How to save Order Status Message in Craft Commerce using frontend form

texts:
It's easy enough update the order status from the frontend using:

<input type="hidden" name="action" value="commerce/orders/updateStatus">
<input type="hidden" name="orderId" value="{{ order.id }}">
<input type="hidden" name="orderStatusId" value="{{ order.orderStatus.id }}">

But I'm wanting to add a message to go with the status. Any pointers? It looks like the message is part of the Order History model, not the Order Status model.


texts:
I'm trying to load a plugin template via ajax inside another plugin template like so:

 $("#modal").load("/mypluginname/myplugintemplatefolder/myplugintemplate.html?queryvar="+var);

but it keeps looking for myplugintemplate.html on the frontend templates folder instead of in my plugin template folder - I don't understand how to tell it that I'm trying to load a file from my plugintemplate folder

Basically I'm trying to refresh a section of my template by reloading an include


texts: Is is possible to add a bespoke Twig template loader?

texts:
Twig lets you provide alternate (or multiple) template loaders. I'd like to take advantage of this to do use a bespoke loader to pull in components from a pattern library using a shorthand syntax like {% include '*mycomponent' %} or similar.

Does Craft expose the environment used for loading templates in a way that I can append/overwrite the default filesystem loader with my own custom implementation?

Any pointers in the right direction would be much appreciated!


texts: How can I handle exceptions on the front end

texts:
So I have some exceptions being caught in a plugin, and have to assume that in some cases a 500 error is going to occur at some point.

How can we set up Craft so that a server error displays a template rather than the default message display (assuming devMode is OFF)?

This would be something we'd want working across the whole site, not just on one plugin.


texts: Tried to duplicate site in local environment but loading blank

texts:
I'm trying to duplicate an existing Craft CMS site by moving it from an online server to a local installation using MAMP. I have copied the /craft folder and all files in the root of /public_html (including the htaccess file). I have exported and reimported the database using PHPMyAdmin.

But now when I go to localhost:8888 I get a "server not found" error because I've been redirected to www.localhost — is this the issue? I tried swapping out the htaccess file to the default one from the craft installation packet but then instead of getting a server not found I get blank pages.

Any ideas? I'm pretty sure the database imported correctly because I could login to /admin before I moved the /craft folder to the local server.


texts: Is it possible to define a default filter for an image inserted in Redactor text ? Filter twig for front or config ? Thanks


texts: Remove white space and parenthsis from global from entry variable

texts:
I am using a phone number in a global variable called {{ global.phone }} with the format "(555) 555-5555". I'd like to use that same variable/string and remove spaces, dash, and parenthesis to use for the href tel link. I've tried a few different things from Twig and Craft documentation, but nothing is working. Here's what I have right now.

Ph: {{ global.phone }}

Is this possible to do? If so any advise how to accomplish this?


texts:
I need to implement Comet Chat, a facebook-chat-like third-party script, into my Craft project.

Comet Chat can connect to most CMS and PHP framework but there is no Craft integration yet, so I tried to use the "custom coded site" procedure.

http://www.cometchat.com/documentation/installing-cometchat/custom-coded-site/php-site/

Comet Chat need to access a session variable to authenticate user. Ex: $_SESSION['userid'].

The problem: Craft write its session variables with some nice sorcelery that makes outside script unable to read it.

So, the Comet Chat is not able to read the userid, even if I made a Craft plugin who writes UserID in $_SESSION['userid'].

I also tried, by the Craft cookie ($_COOKIE values are bidirectionally accessible unlike $_SESSION values, of course) to find some relation or mechanism to tells Comet Chat who's the current user in Craft, unsuccessfuly.

Perhaps some other PHP scripts or cases may need to read the Craft session, so I'm pretty sure this question can be relevant for more than Comet Chat integration.

Any ideas?

Thanks in advance!


texts: How I add security header on the front-end on Craft CMS

texts:
I have Mod_headers installed and active on my server, I know that Craft adds some headers from PHP but only for Control Panel requests. How can I add security headers to the front-end?
Thank you


texts: Image not found with some transforms in english locale

texts: I'm working on a page that has 2 different locales. The German locale is perfectly fine but in the english locale some assets that use the transforms seem to not be working at all. Funny thing is this is not working on staging or local environment. The images that don't seem to tranform appear to have the locale in the transform url e.g. /en/ but right next to these images there are other images using the same transform that seem to work. This appears to be random but always the same images are affected never other images when reloading for example. I've tried reindexing the images, deleting the cache, emptying the indexes in the database and adding the convertFilenamesToAscii setting to true in the general config.


texts: 400 error logging into local Craft 3 project

texts:
I have just tried to log into an old local Craft 3 project that hasn't been worked on in a few months and I'm getting the following:

HTTP 400 – Bad Request – yii\web\BadRequestHttpException

Unable to verify your data submission.

yii\web\BadRequestHttpException: Unable to verify your data submission. in /Users/user/Development/project/build/vendor/yiisoft/yii2/web/Controller.php:166
Stack trace:
#0 /Users/user/Development/project/build/vendor/craftcms/cms/src/web/Controller.php(82): yii\web\Controller->beforeAction(Object(yii\base\InlineAction))
#1 /Users/user/Development/project/build/vendor/yiisoft/yii2/base/Controller.php(155): craft\web\Controller->beforeAction(Object(yii\base\InlineAction))
#2 /Users/user/Development/project/build/vendor/craftcms/cms/src/web/Controller.php(103): yii\base\Controller->runAction('login', Array)
#3 /Users/user/Development/project/build/vendor/yiisoft/yii2/base/Module.php(528): craft\web\Controller->runAction('login', Array)
#4 /Users/user/Development/project/build/vendor/craftcms/cms/src/web/Application.php(282): yii\base\Module->runAction('users/login', Array)
#5 /Users/user/Development/project/build/vendor/craftcms/cms/src/web/Application.php(538): craft\web\Application->runAction('users/login', Array)
#6 /Users/user/Development/project/build/vendor/craftcms/cms/src/web/Application.php(266): craft\web\Application->_processActionRequest(Object(craft\web\Request))
#7 /Users/user/Development/project/build/vendor/yiisoft/yii2/base/Application.php(386): craft\web\Application->handleRequest(Object(craft\web\Request))
#8 /Users/user/Development/project/build/public/index.php(42): yii\base\Application->run()
#9 {main}

The front end of the site fine, the login page at /admin works and I've restarted MAMP multiple times. I have also locally run composer update in case there were any issues with my packages.

But nothing seems to make it want to successfully sign me in.

UPDATE:

After more research, a lot of people have had their issues like this resolved by clearing the cache of their browser. I have tried this in three separate browsers all to no improvement.


texts: How can I make my custom FieldType show up in an element index?

texts:
I've built a custom FieldType, and I'd like editors to be able to add any fields using this FieldType to element indexes. Unfortunately, fields using my custom FieldType aren't included in the list of fields in the Customizable Element Index configurator.

How can I make it possible to add fields using my custom FieldType to element indexes?

Also, is it possible to define how the value returned from my custom FieldType displays in the element index?


texts: Can't access Pending user's profile info

texts:
I have public user registration enabled with the "Verify email addresses" setting checked.

User registration form includes these "action" and "redirect" hidden fields:

<input type="hidden" name="action" value="users/saveUser">
<input type="hidden" name="redirect" value="signup/payment/{id}">

User's ID is coming through correctly in the last segment of the URL, but I can't fetch their profile. This is throwing a template error:

{% set userId = craft.request.lastSegment() %}
{% set profile = craft.users.id(userId) | first %}

But if I hardcode an existing Active user's ID it works:

{% set profile = craft.users.id(30) | first %}

Is there a way to access a Pending member's (albeit limited) profile info? What I really need to do is insert their email address into a subsequent form on the success page.


texts: Not able to catch exception sending SMS with Twilio in plugin

texts:
Not sure if this is the best place to post, but since it's a Craft 3 plugin I'll give it a shot.

foreach ($numbers as $number){
    $number = $twilio->lookups->v1->phoneNumbers($user->mobil)->fetch(['countryCode' => 'NO'])->phoneNumber;

    try {
        // Send SMS
        $twilio->messages->create(
            $number,
            [
                'from' => $settings->twilioNumber,
                'body' => $request->post('body')
            ]
        );
    } catch (\Exception $e) {
        continue; // Continue (loop) to next number as this one failed/is invalid.
    }
}

In short, whenever a $number is invalid, execution stops giving Twilio\Exceptions\RestException [HTTP 404] Unable to fetch record: The requested resource /PhoneNumbers/"the-invalid-number" was not found.

It seems that the catch is never reached.

Note that I have tried replacing \Exception with the following to no avail.

use Twilio\Exceptions\ConfigurationException;
use Twilio\Exceptions\DeserializeException;
use Twilio\Exceptions\EnvironmentException;
use Twilio\Exceptions\HttpException;
use Twilio\Exceptions\RestException;
use Twilio\Exceptions\TwimlException;

Regardless, I thought \Exception would catch any exception?

Edit: Here's the solution.

try {
    // Validate the number
    $number = $twilio->lookups->v1->phoneNumbers($user->mobil)->fetch(['countryCode' => 'NO'])->phoneNumber;

    // Send SMS
    $twilio->messages->create(
        $number,
        [
            'from' => $settings->twilioNumber,
            'body' => $request->post('body')
        ]
    );
} catch (\Exception $e) {
    // Number is invalid; continue to next number
    continue;
}


texts: Conflict with assets folder and section URL

texts:
I have come up against an issue, and I want to check the best way to resolve this; here is a brief explanation.

So by default I have setup the craft assets folder to be called 'resources' and this lives in the top level of the website (although I think location is irrelevant). The client has now introduced a section called resources that has several child pages and a top level page. Which is accessed at /resources/ - I think the most sensible change is to rename my resources folder that holds all the uploaded assets. I will probably rename it uploads. However, what is the best approach to rename this without upsetting the system or having big issues.

I should also mention my resources folder also contains several sub folders for assets too.


texts: I am getting this message when creating a new project

texts: Cannot create cache directory /home/cmnd/.composer/cache/repo/https---repo.packagist.org/, or directory is not writable. Proceeding without cache


texts: get category id & category-group field handle (several), then append it to link (compose url POST parameters)

texts:
I have an overview page for entries from an structure. I output the single entries, this works just fine. (simplified code here)
{% set singlerugs = craft.entries.section('rugs').all() %}

    {% for item in singlerugs %}

                {{ item.title }}

    {% endfor %}

the overview page has a filter, where the entries can be filtered, via a JS Code.
In the backend, the Categorie-Groups have fieldhandles like "catColors", "catSizes" and "catPlaces".

Now i want to get the ids from the categories of the clicked ones by the user
(like in the example, color 2, size 7 and place 8 and put them to the entry link from above:
something like: ".../?catColors=2&catSizes=7&catPlaces=8
i need this later for the getPrev/getNext link on the detailpage of the entry.
How can i achieve this? is it something with craft.app.request.getQueryParam()?
i tried this, Compose URL POST parameters to filter entries by category?, (quite old) made the change to the newer craft.app.request.getQueryParam(), but get the twig error: Impossible to access an attribute ("slug") on a string variable ("30738"). where 30738 is an id of an categorie of the catPlaces Category-Group.
changed slug to id, but still no luck.


texts:
I`ve got a multilingual site (DE/EN) with a Structures section (pages) and one Single for the homepage.
In general.php I set up my localized site as described in the docs for a multi-environment config. German at the top level; English from en/ subfolder:
'domain.dev' => array(
    'siteUrl' => array(
        'de' => 'http://domain.dev/',
        'en' => 'http://domain.dev/en/',
    ),
),

Within my public html folder I copied .htaccess and index.php to en/ and added define('CRAFT_LOCALE', 'en'); to index.php
Navigating to domain.dev shows the german pages:

Seite 1
Seite 2
Seite 3

Changing the URL manually to domain.dev/en/ shows their right translations

Page 1
Page 2
Page 3

and also their right links, e.g. http://domain.dev/en/page-1
BUT following the link to domain.dev/en/page-1 the german content shows up again and the navigation switches back to german.
{% set pages = craft.entries.section('pages').level(1) %}

        {% for page in pages %}

{{ page.getLink() }}

        {% endfor %}

Going to any other english page (e.g. domain.dev/en/page-2) doesn't show up the english content (a translatable field) at all but neither the german content. So I think there is something wrong with my localization setup. Any ideas? Thanks much!

UPDATE
I set up a new craft installation and also a Localized Site as described in the docs.
When defining the site URLs this way everything works like a charm:
return array(
    'siteUrl' => array(
        'de' => 'http://craft.dev/',
        'en' => 'http://craft.dev/en/',
    ),
);

in combination with my multi-environment config it is not working.
return array(
    'craft.dev' => array(
        'siteUrl' => array(
            'de' => 'http://craft.dev/',
            'en' => 'http://craft.dev/en/',
        ),
    ),
);

So I think my config is missing something to transmit the locale the right way?
Is there another way to set up a localized site with multi-environment config?


texts: Implication of old task backlog suddenly being released

texts:
I have a Craft website that has become quite big with several dozen sections and many templates - my first bigish Craft site - being a local government one with more than a thousand pages, forms and assets.

The Task Icon (I think is its name) had indicated there were uncompleted tasks and this has been stuck there for a couple of months while the site was being built and there have been many content and structure updates during this time.

Eventually I got around to attending to the issue after several half hearted attempts at finding out "what that stupid circle meant" (embarrassed much). A few minutes ago I followed the instructions at http://buildwithcraft.com/help/stuck-tasks and the task list was released like opening a flood gate - "hundreds"(?) of them suddenly ran, mostly "Resaving Meetings entries", Meetings being one of my sections, "Importing csv files" (which had consistently failed before, I now know why) plus "Updating element slugs and URIs". Also "Deleting stale template caches" which might explain another headache.

I'm now wondering if this will likely have any undesired impact on the site content given that I am now worried about old data replacing the new  via Imports, Resaving, and Updating that has carried on. I'm not a content editor on the site so I am not too familiar with what should be the right data set and business only opens again in about 12 hours.

Can anyone advise on what these tasks might do if run as a very delayed process?


texts:
For templating, I need to be able to see what the categories of the current entry is. I'm aware of how to get all categories in craft via

{% set categories = craft.categories %}

however I haven't come across a way to simple get the categories that are set for the entry. Is there a simple way of doing this?


texts: Pagination with randomly ordered entries

texts:
I have a need to list a set of entries 9 at a time but with a random order.

The pagination happens via Ajax, with each next set of 9 entries loaded onto the page when the user clicks the "See more" button.

I'm fetching the entries with

{% paginate craft.entries({
        section: 'customers',
        limit: 9,
        order: 'Rand()',
    })
    as pageInfo, pageEntries
%}

then looping through the set and outputting as normal

{% for customers in pageEntries %}

{{ customers.title }}

    etc.
{% endfor %}

and then adding a button to load the next set of results

{% if pageInfo.nextUrl %}
        See more
{% endif %}

I thought I had this figured out but I'm seeing some duplication in the returned entries. Oddly it doesn't feel like there is enough duplication to make me think my method is wrong. From about 100 entries, showing 9 at a time I might see 1 or 2 duplicates at most.

If I remove the order: 'Rand()' from my criteria then it all works fine (except obviously not in a randomised order).

Why am I seeing duplicates? If the randomisation was applied after 9 entries were retrieved then surely the first set of 9 would always be the same entries in random order. Likewise the second set, third set etc. Which isn't the case.

But if the randomisation is applied to the entire set of entries before the set of 9 is returned then why would there be duplications?

So I suppose the randomisation occurs on the full set every time and 9 entries are returned. But if this was the case surely I'd see more duplications.


texts: twig for loop put every 2 elements in a new container

texts:
I have this loop:

{% for div in myHandleHere %}

 {{ block.text }}

{% endfor %}

That actually outputs something like:

 one

 two

 three

 ...

What I want is, every 2 div, put them in a new container, like:

 one

 two

 three

 ...

Please help


texts: Multi-lingual site with a splash (language select screen) at the root

texts:
I'm trying to get something working and I keep breaking my internal links doing it.

Here's what I'd like:

public/index.html (this page would be the language select screen and can be dealt with outside the cms)

public/fr/index.php (craft loader for french)
public/en/index.php (craft loader for english)

I would also like the CP to load from the root.  I thought of having it redirect to a "craft.php" page that would be the loader if the requested file doesn't exist, and it worked for the CP.  But of course, it grabs any of the calls to the site that is not fr/ or en/ only.  As soon as there's something else in the uri, it goes to 404.

Any idea for this one?


texts: Add variable to purchasable variant to modify price?

texts:
Is it possible to somehow (plugin or otherwise) modify the price of a lineItem/variant based on variables like material or any other additional modifier (basically affecting the same stock of items).

For example:
Pillow (with variants being color)
— Stuffing material
— Print yes/no

The pillow base product itself is a finite number of items for each color, but the stuffing isn't fixed in that sense, effectively being infinite in terms of stock.

Would it be possible to create separate products and use the Multi Add plugin for this, rather than doing some form of (preferably simpler) custom approach?


texts: Alphabetical index for a list of entries

texts:
I would like to build an alphabetical list of craft entries, but group them by the initials of one field of each entry. Thus, getting some kind of alphabetical index, like

A

Apples
Ananas

B

Beer

How do I do that?


texts: How can i get all values in a global set

texts:
I would like to get all the fields (with their handles and values) for a given global set.

For example : My set is called 'labels'.
I know I can get the set by using :

$criteria = craft()->elements->getCriteria(ElementType::GlobalSet);
$criteria->handle = 'labels';
$labels = $criteria->first();

Or with :

$labels = craft()->globals->getSetByHandle('labels');

Then I can get a specific data with

$labels->myDataHandle

But how can I get all the data/fields in the set ?
I would like to have an array or an object with all my labels (in my controller I return the value using returnJson).

Thanks for your help !


texts: Bulk selecting Members and then including them in an email to another specific Member in a different member group

texts:
I'm wondering if the following is possible within CraftCMS and suggestions for making it happen?

We have two Member groups (Customers and Contractors). When a Customer makes an enquiry they complete a series of pre-set questions.  These pre-set questions are used to filter individuals from the Contractors group.

On submission the Customer receives a notification email with a link.  Admin also receives a notification with the same link.

The link takes the customer to a page which displays:

Customers own submitted information and responses to the pre-set
questions.
Same page also displays a list of matched Members from the
Contractors group who fulfil the criteria which is matched using the
pre-set questions fields.

Customer can then decide which contractor they wish to work with.

Customer clicks "Hire" and an email is sent to the selected Contractor.  Email contains the Customers contact details.

Any help/advice is very much appreciated.

Martin


texts: Sort entries by a related entry (lastName) and then paginate

texts:
I have two channels books and authors

I need to list all books sorted alphabetically by author. I have this working with the following code:

    {#
    // loop through authors so we can sort books
    // by author last name
    #}
    {% for author in craft.entries.section('authors').order('lastName').all() %}

        {# find all books related to the author #}

            {% for entry in craft.entries.section('books').relatedTo(author).all() %}

{{ entry.title }}

            {% endfor %}{# end books for each author #}

    {% endfor %}{# end authors #}

This works fine, but I"m not sure how to paginate this. I want to paginate the books which is the nested loop and will likely only contain 2-4 books per author.

If I paginate the authors loop I'll have 5 authors per page but each author will have a different number of books so each page will have different number of books. Not what I want.

If I paginate the book loop it's not going to see all the books only the ones from the author of the current author loop.

However the total number of books is 100+. How do I paginate the total number of book results.

--------------

If it were possible to do the alpha sort based on the related field without nesting for loops that would be ideal? Is this possible?

------------- UPDATE ----------------

add a new field to the books channel where the authors last name is manually added and now using .order('authorLastName') which works but it clunky becaue they have to select the author from the authors channel and add in their last name in a second field.


texts: layout file changes get deleted overnight

texts: I've had a problem for a few weeks whereby any changes to a layout.html file get deleted overnight on a server. As a sanity check I just want to make sure there isn't anyway this can be done by Craft? (The updates have expired on the install, but surely this can't be the problem?)


texts: Is there any danger to Craft from upgrading from PHP 5.5 to PHP 5.7?

texts:
As of July 2016, PHP branch 5.5 is unsupported. The PHP version my server currently is running is 5.5.9 which implies that the server will not receive any security updates going forwards.

I'm told that Craft recommends using 5.7. Is there any danger that parts of my website may stop working if the PHP is updated?


texts: Move entry from one structure to another with parenting

texts:
Seeing as moving entries between sections isn't supported (yet) through the Craft interface, I followed Brandon's answer for a workaround through the database.

I am moving entries from one structure to another; updating the sectionId in the database works fine and the entries are moving over without a problem.

However the issues start when I try and make some of the entries children to others that have also been moved.

I have tried both dragging the entry through the Structure view and setting the parent in the dropdown while editing the entry, but both are coming up with the same error:

  An unknown error occurred.

And I am getting a 500 Internal Server error on this file

/index.php?p=admincp/api/structures/moveElement 500 (Internal Server Error)

Is this a bug within Craft, or have I missed out on some other information that needs to be updated in the database?


texts: Registration into default group is not working as expected

texts:
Here are my settings for user registration:
\

When front end registration completes the users are added fine but not into the default user group as expected. They are just in the system with no group.
I was expecting them to be registered into the default group - am i missing something?


texts: How to display plain text only from redactor without any line break or format

texts:
Is there a way to display plain text only without any line break or format style. I have an input field using the redactor. I want the result to shows plain text without any formatting for this particular page. How can I modify it?

{% set desc = desc|slice(0,150) %}
{% set _desc = desc|split(' ') %}
{% set __desc = _desc|slice(0,-1) %}
{% set desc = __desc|join(' ') %}
{{desc|raw}}

Thanks.


texts:
I've got this working but it seems terribly verbose to do something, that in my opinion should be easier.

Is there a better way to get the assets from 2 different fields, merge them and output them in a random order?

{% set clientLogos = logos.clientLogos.all() %}
{% set agencyLogos = logos.agencyLogos.all() %}

{# set empty array #}
{% set logoIds = [] %}

{# add logos from clients #}
{% for logo in clientLogos %}
  {% set logoIds = logoIds|merge([logo.id]) %}
{% endfor %}

{#  add logos from agencies #}
{% for logo in agencyLogos %}
  {% set logoIds = logoIds|merge([logo.id]) %}
{% endfor %}

{# looped through merged logos #}
{% for logo in craft.assets().volume('uploads').kind('image').id(logoIds).orderBy('RAND()') %}
  <img src="{{ logo.url(croppedlogo) }}" alt="{{ logo.title }}" class="m-4"/>
{% endfor %}


texts:
I have an external php app that sits in a subdirectory in the public folder on the same server (and domain) as craft. I am trying to use bootstrap.php to check the logged in status of the current user. Is this possible?

It is currently working for me by checking that the user is logged in (it does return false while not logged in) - but after the user logs out of craft the bootstrap.php continues to return true that the user is logged in.

$craft = require '../../craft/app/bootstrap.php';
if ($craft->userSession->isAdmin() && $craft->userSession->isLoggedIn() ){
 // this returns after a log in, but continues to be true after a log out. It does not return true initially before using both craft and this script.
}

Hopefully that makes sense, any ideas?

I also could not get the onLogout or onBeforeLogout to execute. I see it is in the class reference, but not listed in the event documentation:

public function init()
{

    craft()->on('usersession.onLogout', function(Event $event) {
        echo "THIS DOES NOT EXECUTE";
        die();
    });

    parent::init();
}

Is it possible the log out event is not triggering?


texts:
This is a head scratcher. We have a site we are about to launch that was ready to go when suddenly at some point in the day yesterday a bunch of Matrix fields within a group went missing. Just gone. Of course this broke the site and our templates started erroring out. Our first instinct was that they were manually deleted but the client is saying that they didn't touch the fields area. We also talked to the web host / Arcustech and they said that everything looked fine on their end. We had to restore the database which was a bummer.

So my question is, could this have been due to a recent bug? Is there a way we can see what fields get deleted via the logs? It's really bothering us that we can't pinpoint exactly what happened here.

I should mention we were on 2.2.2592 when this happened. Thanks for any help.


texts: Navigating through entries within a category when they belong to multiple

texts:
I need some advise on the best way to achieve this.

I have entries within a section which could belong to category A, B, C, D. Any of these entries could also belong to a Featured category.

Each category has it's own page, and from an entry you can go to the next or previous entry (within that category).

I can't see how I can do this for the Featured entries as they also belong to another category.

I'm thinking I'll have to do something with the URLs so the entry knows its been clicked on from the 'Featured' category page rather than 'B' so the Previous and Next buttons stay within 'Featured'.

This is my Next and Previous buttons code on the entry template:

{% set params = craft.entries.section('galleries').relatedTo(categories.galleries) %}
{% set nextEntry = entry.getNext(params) %}
{% set prevEntry = entry.getPrev(params) %}

    {% if prevEntry %}Prev |{% endif %}

    {% if nextEntry %}Next
    {% else %}
        Next
    {% endif %}


texts: Craft Commerce: Upload File Field in Order?

texts:
I'm looking at Craft Commerce as a possible solution.

In the order process we want customers to be able to upload a file against their order which can then be accessed by the shop administrators. Is this possible and how would we go about that?

I have been looking through the documentation and seen nothing that clearly demonstrates this (yet!).


texts: Forms are triggering CSRF Protection. Why would CSRF Protection trigger false positives?

texts:
We've enabled CSRF Protection on a site.

When we do, it sometimes works, but most of the time it gets tripped and triggers false positives and doesn't allow our forms to be submitted.

Things we've observed:

Some forms work, others don't
Sometimes a browser doesn't place the CSRF cookie
Sometimes two different browsers will have the same CSRF cookie
Sometimes if I delete the CSRF Cookie and then refresh the browser, the cookie won't return
Clearing the Craft cache seems to get forms working again in one browser but not another

Why are we seeing this weird behavior?  What is happening?!


texts:
I have a field "menu card" in my globals' section "menuCard", so I could access my file in the template with menuCard.menuCard.first().url. That is fine, but when the editor changes the menu-card file and it has a different name, the url will be different:

first week:
menu-card-17-10-01.pdf

next week:
menu-card-17-10-08.pdf

As it is a menu-card for a restaurant which gets changed every week it would be awesome to always have the current menu-card pdf available through the same url/slug like myrestaurant.com/menu and also reference the menu within my templates with /menu;

Is there a way to do so in craftcms? For example an alias which points to my global field menuCard.menuCard.first() or something like that?

Thx


texts: I need to submit a form, using SproutForms, via AJAX, so i can get the response and then show some "gated" content on the page. The content (i.e. PDF link, etc) is tied to a particular entry page, so i'd like to stay on that page and not doing a normal POST to a generic success page. I can't find any info on the SproutForms plugin page on how to do this, just that it's supported (noted in the change log). Please help