texts:
I am trying to do the following with craft.entries but I think it may not be possible without a plugin.

I have 9 categories with related entries on all of them. I would like to get the latest articles (postDate) for each one the categories and then group by category and only show only the seven latest articles, one for each category.

The following works but it fetches 100 articles each time (I can reduce it but still its not ideal)

{% set latestArticles = craft.entries.section('articles').relatedTo({element: selectedCategories, field: 'journalismMainCategory'}).order('postDate desc').find() %}
{% set groupedArticles = latestArticles|group('journalismMainCategory.first.id')|slice(0,7) %}

I've also tried the following but I cannot get it to sort by date or group the category properly. It retrieves the latest article for each category, but in the order of the category (and not by post date)

{% set selectedCategories = [98, 100, 2412, 2408, 2410, 2414, 2416, 55332, 55333] %}

{% for category in selectedCategories %}
       {% set stilesArticles = stilesArticles|merge([craft.entries.section('articles').relatedTo({element: selectedCategories[loop.index0], field: 'journalismMainCategory'}).limit(1).first]) %}
{% endfor %}

Any ideas on how something like this can be done without a plugin?

Cheers!


texts: Add active class and territory name to language switcher

texts:
I've worked up this code with big help from @carlcs.
I want to set up a class if current locale is turned on.

Firstly, I tried the easiest way by putting {{ current ? 'my-class' }} into li.
Secondly, I tried to set variable for current locale.

I've end up by struggling to answer my question, Why all locales are turned on?

{# Language switcher #}
{% set locale = craft.i18n.getCurrentLocale() %}

{# Configure site locales #}
{% set locales = ['en', 'en_gb'] %}

{# Check if locale equals the requested page locale #}
{% if locale == craft.locale %}
    {% set current = true %}
{% else %}
    {% set current = false %}
{% endif %}

{# Give locales class or text #}
{% if locale == 'en' %}
     {% set territoryCode = 'world' %}
     {% set active = 'uk-active' %}
{% endif %}

{% if locale == 'en_gb' %}
     {% set territoryCode = 'uk' %}
     {% set active = 'uk-active' %}
{% endif %}

{# This is the current locale #}
{{ territoryCode|upper }}

{% set locales = ['en_001', 'en_gb'] %}
{% for locale in locales %}
{% set subTags = locale|split('_') %}
{% set territory = subTags|length > 1 ?craft.i18n.getLocaleData(craft.locale).getTerritory(subTags|last) : '' %}
{% set language = craft.i18n.getLocaleById(locale).name %}
{% set language = language ?: craft.i18n.getLocaleById(subTags|first).name %}
{% set language = language|replace("/- #{territory}$/", '') %}

       {% if territory and language %}
            {{ territory }} ({{ language }})
       {% endif %}

{% endfor %}

Update

{% set locales = ['en_001', 'en_gb'] %}

 {% for locale in locales %}

 {# Check if locale equals the requested page locale #}
 {% if locale == craft.locale %}
      {% set current = true %}
 {% else %}
      {% set current = false %}
 {% endif %}

 {% set subTags = locale|split('_') %}
 {% set territory = subTags|length > 1 ? craft.i18n.getLocaleData(craft.locale).getTerritory(subTags|last) : '' %}
 {% set language = craft.i18n.getLocaleById(locale).name %}
 {% set language = language ?: craft.i18n.getLocaleById(subTags|first).name %}
 {% set language = language|replace("/- #{territory}$/", '') %}

        {% if territory and language %}
            {{ territory }} ({{ language }})
        {% endif %}

 {% endfor %}


texts: Update a variant by searching for a custom field value

texts:
I've written a stock import routine that takes data from a CSV, the column I need to match on is a custom field supplierSku. I can't find an easy way to search variants for this specifically so am using SQL at the moment, which may be faster but not very elegant. Any suggestions?

foreach($stock as $item) {
    craft()->db->createCommand('UPDATE craft_commerce_variants v JOIN craft_content c ON c.elementId=v.id SET stock=:stock WHERE c.field_supplierSku=:sku')
        ->bindParam(":stock",$item[1])
        ->bindParam(":sku",$item[0])
        ->query();
}


texts: What's the simplest way of automatically activating/verifying user accounts?

texts:
I'd like to have my users automatically verified/activated so they can immediately login after registration. Normally this would be done through the automatic emailer, but I'd like to skip that.

Are there any easy changes to do this, or will I have to write a plugin?


texts: Enable single line item mode on Commerce Pro

texts: Is there a config option or something that would enable the 1 line item limit in cart. That means once customer adds second line item to cart first one would be removed so that only one would be left. I believe that's how Commerce Lite works. I need similar functionality on Pro licence.


texts:
My problem is that I can't update the specific $userId. have the values I've selected. I also get an error:

  Call to a member function where() on integer

I just started to learn Craft. It can be simple for you but not for me.

public function updateUserName($userId, $updateUser)
{

    $update = craft()->db->createCommand()->update('contest_user', array(
        'name' => $updateUser))->where('id', $userId);

    return $update;
}


texts: High volume category list causes slow load

texts:
My customer has 3500 categories in a 3 level hierarchy. This is causing some significant pain when adding categories to an entry. The server delivers the categories via ajax in 9sec, but the browser then takes 3-5 minutes to push the html segment into the modal dialog.

Is there any way to handle this a little more efficiently? I need to be able to select from any of the 3500 categories, but would love to limit the initial display to only the top one or two levels of the hierarchy.


texts: onBeforeSaveEntry listener to add/modify data of some fields

texts:
I'm trying to build my first, very simple, one file plugin.  I'm having difficulty with a basic task and I can't find any documentation to help me out. Keep in mind that there is no validation whatsoever, I'm just trying to get it to work first.

public function init()
{
    parent::init();
    craft()->on('entries.onBeforeSaveEntry', function(Event $event)
    {
        $entry = $event->params['entry'];
        $section = craft()->sections->getSectionById($entry['sectionId']);
        if ($section['handle'] == 'institutions')
        {
            $full_address = urlencode(rtrim($entry['adresse'].','.$entry['ville'].','.$entry['province'].','.$entry['codePostal']));
            $json = json_decode(file_get_contents("https://maps.googleapis.com/maps/api/geocode/json?address={$full_address}&sensor=false&region=ca&key=AIzaSyDhPYj9UwwUYNZYSz9Fo-j75gCJKWVdFeY"));
            $entry->setRawPostContent('latitude' ,$json->results[0]->geometry->location->lat);
            $entry->setRawPostContent('longitude', $json->results[0]->geometry->location->lng);
        }
    });
}

I have a listener on entries.onBeforeSaveEntry and it works well.  I check if the section handle is what I need and then I look into the entry data to grab the address fields and query Google map.  All of that is working like a charm.

I can't figure out how to put the data back into the entry for the lat and long filed that exists in my entry type.

$entry['latitude'] = $json->results[0]->geometry->location->lat;

That gives me an error saying latitude is not defined, which is false because I can output the value from it.

Also tried:

$entry->setRawPostContent('latitude' ,$json->results[0]->geometry->location->lat);

Any idea?  I can't find any documentation or google search that can help me out.


texts: How to get Current Entry ID in Plugin Variable?

texts:
I need to get the current entry ID in plugin's variable file without submitting any form. I tried this but it gave an error Undefined property: Craft\PluginNameVariable::$element

namespace Craft;

class PluginNameVariable
{
/**
 */
public function totalitemsForElements($elements = array())
{
    $criteria = craft()->elements->getCriteria('MyElementType');

    $criteria->elementId = $this->element->id;

    $items = $criteria->find();

    return $criteria->find();
}
}

I was accessing this variable through

{% set itemElementType =  craft.pluginName.totalitemsForElements %}
{{ itemElementType|length }}

Please Help. Thanks in advance !!


texts: Commerce Custom Shipping Methods via Plugin

texts:
I'm looking to add additional shipping methods through a plugin, using the documentation here: https://craftcommerce.com/docs/shipping-methods

I'm a little bit lost about how to hook things up, according to the docs I'm supposed to do:

public function commerce_registerShippingMethods()
{
    return [new CustomShipper_CourierDeliveryMethod()];
}

The docs don't really cover where and how to do this, other than to include it in the base plugin file. That part I can follow. Could someone help me understand what file to create, the basics of what it should include and how to connect it (referring to new CustomShipper_CourierDeliveryMethod())?

This is new to me for Craft Plugin development - I'm used to connecting to files using something like:

return [craft()->pluginHandle_serviceName->function_name()];

Which obviously is very differently than the above. Any help would be HUGELY appreciated.. thanks!


texts:
Usually the effects work fine for me, are there are server requirements to get them working that I have missed? or is the template code below incorrect?

{% for block in entry.clientLogos %}
    {% for image in block.clientLogo %}
        {% set logoImages = craft.imager.transformImage(image,
        { width: 210, height: 90, mode: 'crop', position: 'center-center', jpegQuality: 90, effects: { grayscale: true, gamma: 1.5 } }
        ) %}
        <img src="{{ image.url(logoImages) }}" alt="{{ block.clientTitle }}" title="{{ block.clientTitle }}"/>
    {% endfor %}
{% endfor %}


texts:
I did at some point believe that the CSRF token my plugin requests was using expired in the middle of a request, but it turns out that they were never included in the first place.

Still curious, I wonder how long a CSRF token lasts?


texts: How can I use the Courier plugin to notify a user when an entry is enabled?

texts:
Moderation scenario:

Registered user publishes an entry using a front-end form that sets the entry to disabled.
Moderator receives email re new entry and changes status from disabled to enabled in the CP.
User receives email informing them that the entry has been enabled.

I’ve got steps 2 & 3 working using both the Courier & Postmaster plugins independently. However, when the user edits their entry via another front-end-form, they also receive an email notification.

How can the user be notified only when the entry has been edited and the entry's status has been changed from disabled to enabled?

Courier blueprints:

Step 2: Triggers: entries.onSaveEntry and Conditions: {{ entry.sectionId == '3' and isNewEntry ? 'true' : 'false' }}

Step 3: Triggers: entries.onSaveEntry and Conditions: {{ entry.sectionId == '3' ? 'true' : 'false' }}


texts: How do I set up event listing & detail pages with entry post dates that are in the future?

texts: I'm struggling to set up a listing template and a detail template which will display "event" entries with post date set in the future. I keep getting a 404 error on the detail page. How do I set up Craft & templates to show future dated entries on a listing and detail page?


texts:
I wasn't to allow a user to enter html into the Rich Text field.

The html in question is:

I can save the entry and on the front end the content displays ok - but when I go back in to edit the entry it is no longer there - the div and script tags have been removed.

I tried adding this

replaceDivs: false,

to the config but it doesn't make any difference


texts: Commerce - how to display order address in email to customer?

texts:
I'm new to commerce but almost I've cracked all I need to my project but one piece still left.
I can't display order shipping address. I've tried
{{ order.shippingAddressId(shippingAddress) }}
but it giving me order referance number.

From documentation:
shippingAddressId #
The id of the linked shipping address. You can get the shipping address model with the shippingAddress attribute.
shippingAddress #
This returns the address model from the database for the current shippingAddressId OR the caches address if the order is complete.

Please help...


texts: "Missing" assets from large S3 asset source

texts:
We have an S3 asset source with ~33k images. In the admin, quite a few aren’t completely loaded (see image below). Users are able to add these to entries but they don’t display on the front end. Sometimes, a few hours later, they will start displaying. These images are accessible and not corrupt on S3 itself.

I’m wondering if there’s something specific causing this: PHP memory limits? Some kind of config setting? Server specs? I’ve updated the asset indexes and the task appears to complete with no errors in the log, but there's no change in the asset experience in the admin.

Note that you're able to view and download the asset just fine from within the admin. Just no thumbnail and no display when added to an entry.

Our client is just noticing this issue now that they're adding backdated content, but I suspect that it has existed since we set up this asset source.

Any insight would be greatly appreciated!

Update: I've discovered (thanks to Andris via Craft support) that if I re-upload these "ghost assets", their attributes are correctly populated, so I've been doing that, albeit slowly as they're not sequential. I also noticed that these assets are missing width, height, and size in the craft_assetfiles table.


texts:
I'm seeing a lot of goodies among the v3 infos, but not much about how licensing will work.

So if my client has a paid license will they get v3 for free or as a paid upgrade. If paid will it be a full price or a discounted?


texts:
I attempted to install the newest version of Craft and received this error in my logs:

PHP Fatal error:  Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\craft-cms\vendor\yiisoft\yii2\db\Command.php on line 1292

I'm unsure of the cause of this error, but the the lines around 1292 in the command.php file seem to be an exception handler for database transactions.

I don't achieve a different result after lengthening the execution time. I've tried setting very lenient firewalls and administrator rights. I've also tried uninstalling and reinstalling all of the files. I still receive the same error every time.

Any ideas to fix this issue? I haven't found another post about this issue online, so any help would be very much appreciated.


texts: Can I run one Craft install on multiple domains and/or subdomains?

texts:
Is it possible to have one Craft install running multiple domains and/or subdomains?

For example having the same Craft install running a blog Channel at blog.example.com and also an about Single at example.com/about.


texts: How can I know the discounts available to a product before adding it to the cart?

texts: How do I show possible discounts available to the current product?


texts:
I have a custom fieldtype that I have built in a plugin. I want to validate these fields inside of field settings when data is added. I saw there was a getErrors method in the model however I am unsure on how to post errors to this field settings page. Can anyone point me in the right direction for what method I should be doing this in so that you cant save unless these fields validate?

Thanks


texts: When is the order email sent out in Craft Commerce?

texts:
I'm updating a custom field within a product to contain a discount code. The code is generated and the custom field updated using the onBeforeOrderComplete event. All works well, apart from the order email:

The order email doesn't contain the discount code (the field is just blank).
Checking the product immediately after in the backend, the code is in the field.
Switching the order status back to processing sends the email with the code in it.

Which makes me think the email is going out before onBeforeOrderComplete is triggered. Is this right?

Here is how I set the custom field:

public function updateProductWithDiscountCode($productId, $discountCode)
{

    // GET THE PRODUCT, UPDATE IT AND SAVE
    $product = craft()->commerce_products->getProductById($productId);
    $product->setContentFromPost(array('discountCode' => $discountCode ));
    if (craft()->commerce_products->saveProduct($product)) {
        GiftVouchersPlugin::log("Product #$product->id updated with coupon code $discountCode", LogLevel::Info);
    }
    return TRUE;

}

The plugin work in progress is here: https://github.com/cliveportman/giftVouchers

What should be happening:

gift voucher product is created and added to the cart
payment takes place
when onBeforeOrderComplete is called, if the order contains a gift voucher product, we create a promo and add the discount code to a field within the product
the order email is sent, containing the discount code

What I think is happening:

gift voucher product is created and added to the cart
payment takes place
the order email is sent, without the discount code
when onBeforeOrderComplete is called, if the order contains a gift voucher product, we create a promo and add the discount code to a field within the product

Here is a sample of the email template:

  {% for item in order.lineItems %}
    {% if item.purchasable | length %}
      {% set product = item.purchasable.product %}

{{ item.price | currency(order.currency) }} {{ product.title }}

              // THIS IS POPULATED WHEN THE PRODUCT IS CREATED SO DISPLAYS FINE
              {% if product.recipientName | length %}for {{ product.recipientName }}
{% endif %}

              // THIS IS EMPTY WHEN THE ORDER EMAIL IS SENT OUT THE FIRST TIME
              // BUT IS POPULATED IF SENT OUT THROUGH A LATER STATUS CHANGE
              {% if product.discountCode | length %}code {{ product.discountCode }}
{% else %}

                // THIS IS EMPTY AS WELL
                {{ product.content.discountCode }}

              // THIS IS MY FALLBACK AT THE MOMENT - SENDING PEOPLE TO THE VIEW ORDER PAGE WHERE I CAN SHOW THEM THE DISCOUNT CODE USING {{ product.discountCode }}
              {#Click here to view your gift voucher code#}
{% endif %}

    {% endif %}
  {% endfor %}


texts: Craft 3 / Commerce 2 + Multisite & COMMERCE_PAYMENT_CURRENCY

texts:
I've just done a Craft 2 > Craft 3 upgrade, and it previously used different locales to change the default currency, depending on the locale.

In Craft 2, I would set COMMERCE_PAYMENT_CURRENCY in my index.php file (https://docs.craftcms.com/commerce/v2/payment-currencies.html#switching-currencies) so that it would set the currency for that specific site.

But in Commerce 2 this doesn't seem to be working at all.

My current setup is:

/web
   index.php
   /europe
      index.php

And in the /europe/index.php I've got:

<?php
/**
 * Craft web bootstrap file
 */

// Set path constants
define('CRAFT_BASE_PATH', dirname(__DIR__, 2));
define('CRAFT_VENDOR_PATH', CRAFT_BASE_PATH.'/vendor');

define('CRAFT_SITE', 'en_eur');

define('COMMERCE_PAYMENT_CURRENCY', 'EUR');

// Load Composer's autoloader
require_once CRAFT_VENDOR_PATH.'/autoload.php';

// Load dotenv?
if (class_exists('Dotenv\Dotenv') && file_exists(CRAFT_BASE_PATH.'/.env')) {
    Dotenv\Dotenv::create(CRAFT_BASE_PATH)->load();
}

// Load and run Craft
define('CRAFT_ENVIRONMENT', getenv('ENVIRONMENT') ?: 'production');
$app = require CRAFT_VENDOR_PATH.'/craftcms/cms/bootstrap/web.php';
$app->run();

I know this  file is being picked up when I go to http://website.local/europe, because if I delete the contents, or change the CRAFT_SITE it reacts correctly.

Just not working for Commerce 2.


texts: How to use twig parent function on nested blocks

texts:
I'm not sure if it is appropriate to post twig questions on this forum? I have a question about nested blocks and using the twig "parent" function. I'm running into unexpected behaviour on a craft site i'm building.

My parent and child template layouts.

{# Parent Template #}
{% block breadcrumbs %}
    {% block crumb %}

    {% endblock %}
{% endblock %}

{# Child Template #}
{% block breadcrumbs %}
    {{ parent() }}
    {% block crumb %}
        My custom content
    {% endblock %}
{% endblock %}

What I'm trying to achieve

On my child template, I'm trying to retain the content in block breadcrumbs but override the content in block crumb.
However when I use the parent function in my child template, it does not respect "my custom content" and uses the block crumb content defined in the parent template.


texts:
Does craft save a temporary ID for an asset transform? If so, how do you access it. The ID would be used in a plugin on form submit.

{% for entry in imageLibrary %}
    <form method="post">
        {%- set image = entry.asset.first() -%}
        <input name="file" value="{{ image.getUrl(param).id }}" >
        <input type="submit">
    </form>
{% endfor %}


texts: Assets Directory Usability When Editing An Image

texts:
I would like the CRAFT CMS to return to the current directory after I edit an image.

Let's say I'm viewing a list of images in "assets > images > misc"

I edit an image from that directory and then "save".

The assets tool does not return to "assets > images > misc" - instead, it returns to "assets > images".

This forces the user to re-navigate to "assets > images > misc" to edit another image.

Further, when editing an image out of that directory, the current directory shown at the top of the page is incorrect. It shows "assets > images" when I'm technically editing an image out of "assets > images > misc" (picture attached).

Can this be fixed to save the user countless unnecessary clicks?


texts: How to submit custom fields that are added in the right pane to your plugin?

texts:
I'm making my first Craft plugin.

I have added custom fields to the right of an entry form with the cp.entries.edit.right-pane hook ("Share on..").

But I can't seem to find how to 'transfer' these values to my own plugin and to save them in my own table. The return value of several events I tried (ex. entries.saveEntry) are most of the time an EntryModel which do not include my custom fields.

And I guess making a custom fieldtype is a little overkill?

Thank you!


texts: How can I server Craft transform assets statically (not through Craft/PHP)

texts:
I’m using Craft as a backend for an iOS app and theres thousands of asset requests.

Having to go through php instead of straight through Apache is causing too much of a bottleneck.

I want to use Craft's transforms, but I want the resulting URL to be statically accessible (directly through apache), and not have to go through Craft at all.

Possible?


texts: Can scripts loaded as ES Modules work with Live Preview?

texts:
How can a script loaded as an ES module be reinitiated after changes are made in Live Preview? In my experience a script loaded as a module is  executed the first time Live Preview is opened, but then isn’t executed on subsequent loads as the page refreshes with edited content.

According to this article, modules will only execute once per page. I’m including a function that is executed on the window’s load event and it is fired each time Live Preview is updated — which makes me think the script should be loaded and executed each time Live Preview updates.

Here's a simplified case. Include a script that alerts some text when the script is loaded and on the window’s load event.

alert('Script Loaded')

window.addEventListener('load', () => {
    alert('Window Loaded')
})

Include it in the page as a module:

<script type="module" src="app.js"></script>

Open Live Preview and the alerts fire. Make a change, page refreshes, content is updated — no alerts.

Include it as a regular script

<script src="app.js"></script>

Open Live Preview and the alerts fire. Make a change, page refreshes, content is updated — alerts fire again.

I’m working around it by loading a legacy nomodule version of the script  in Live Preview, but curious if there is another solution or event to listen for to trigger the JS to execute again when Live Preview is updated.

{#
 # Load legacy JS in Live Preview because modules
 # aren’t executed after the page reloads
/#}
{% if craft.app.request.isLivePreview %}
    <script src="app.js"></script>
{% else %}
    <script type="module" src="app.js"></script>
{% endif %}


texts: Getting Template Errors When Using Cache Tag in some environments but not in others

texts:
I'm having an issue where I am getting template errors related to my craft cache tags in some environments but not others. I have my site set up on a production server that is a Linode/Forge setup. The site works fine there.

Locally I am using a Homestead/Vagrant setup and I am getting template errors on any pages that use the cache tag.

Here's the code that is having the error:

{% extends "_layout" %}

{% block pageStyles %}

{% for entry in craft.entries.section('juices') %}
    .color-nameplate.btn-{{entry.slug}} {
        background-color: {{entry.productColorCode}};
    }
{% endfor %}

{% endblock %}

{% block bodyClass %}home-page{% endblock %}

{% block content %}

{% cache if craft.config.cache %}

{% for row in entry.bodyBuilder.level(1) %}
    {% include 'bodyblocks/' ~ row.type.handle with {row: row} %}
{% endfor %}

{% endcache %}

{% endblock %}

This code works in the production environment but not on local. On local it is showing the following template error:

  Unexpected token "name" of value "craft" ("end of statement block" expected).

If I remove the cache tags then the template displays, but this won't work for my production environment so I need to work out what the issue is.

Thanks,

Brian


texts: Javascript issue when setting an expiry date for entry

texts:
If I set an expiry date for an entry I get an error on one of the last lines:

$timePicker.timepicker('setTime', Name of edit section as shown to the user*3600 + 00*60 + 00);

I've traced this back to craft/app/templates/_includes/forms/time.hml:39:

$timePicker.timepicker('setTime', {{ value|date('G') }}*3600 + {{ value|date('i') }}*60 + {{ value|date('s') }});

But I don't understand why value|date('G') returns Name of edit section as shown to the user instead of an integer.

Might also mention that this site uses Norwegian locale.


texts: Including two category slugs in entries’ URLs

texts:
I have a section with two Categories fields, and I would like the entries’ URLs to include the slugs of the categories selected in each of those fields.

The Category Groups are:

mySection

Employees
Employers
Executives

myCategory

Vitality
Health
Safety
Career

So an entry that has “Employees” selected in the first Categories field, ad “Health” selected in the second Categories field should end up with the URL:

mywebsite.nl/employees/health/entrypage

How do I do this?


texts: Import body field into a matrix text block

texts:
I'm working on importing a database and I was looking at some of the available import plugins. However I am unable to figure out how to import a body field (just a string) into a Matrix block.

Old database entry structure (non-Crafty)

title
description
body

New database entry structure (Crafty)

title
description
matrix [body, image, gallery, etc]

Does anyone have experience with this? Any advice?


texts:
I want to be able to access a plugin page without having to login (for a cron job).

I have added this to the plugin's controller:

protected $allowAnonymous = true;

However, this url still requires login:

/admin/[plugin]

(If I login to admin, the above url works.)

If I try the url without /admin:

/[plugin]

The page doesn't work at all (logged in or not):

  Page Not Found
  The requested URL was not found on this server.

How do I make it so I can access my plugin page without login?

BTW, I also have this in the [plugin]Plugin.php file:

public function registerCpRoutes()
{
  return array(
    '[plugin]' => array('action' => '[Plugin]/[Action]'),
  );
}


texts: Sprout forms internal server error after migration

texts:
We migrated our dev-Website to the new server for launching the project. Everything works fine except Sprout Forms. We can't access the Plugins settings page in the control panel.

Error says internal server error, the template „sproutforms/settings/general“ can't be found.

After we call craft.sproutForms.someFunction() in the template our front-end stops rendering. Any ideas?


texts: Visitor array has empty values with Smart Map plugin (using MaxMind)

texts:
I'm receiving an array with empty values when trying to get visitor info using the Smart Map plugin and its Visitor Geolocation feature. I'm using MaxMind's free trial ($5 worth of queries) since FreeGeoIp.net is not recommended and I've double checked the plugin settings and cleared all caches. Looking at the MaxMind account there are no queries logged and my map/debug output has empty location values via PHP (screenshot). Working locally on a .dev domain, running Craft 3 RC and tried FreeGeoIp.net as well but to no avail.
Twig:
{% set visitor = craft.smartMap.visitor %}
{% if visitor %}
  <pre>{{ dump(visitor) }}</pre>
{% endif %}

Output:
 array(8) {
  ["ip"]=>
  bool(false)
  ["city"]=>
  bool(false)
  ["state"]=>
  bool(false)
  ["zipcode"]=>
  bool(false)
  ["country"]=>
  bool(false)
  ["latitude"]=>
  bool(false)
  ["longitude"]=>
  bool(false)
  ["coords"]=>
  bool(false)
}


texts: Empty relation field validation failed with Guest Entries plugin

texts:
I am trying to save a entry with the Guest Entries plugin.

The entry has a custom field 'office' thats set to 'entry' a relation to section 'offices'.

<fieldset class="form-fieldset row-spacing-2">
    <select class="form-input form-select" name="fields[office][]">
        <option>Select office</option>
        {% for office in craft.entries.section('offices') %}
            <option value="{{ office.id }}">{{ office.title }}</option>
        {% endfor %}
    </select>
</fieldset>

The field is set to required in the CP. When I save it with the field set it works, but when empty it throws this error:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails

Can this error be caught or am i doing something wrong here?

Thanks in advance!


texts: public vs public_html for git workflow deployment in apache?

texts:
I have a website setup in Craft multi-environment config for git workflow with a development branch automatically deploying via deploybot from a bitbucket repository.   I want to add an additional live server for manual deployment via deploybot, but I'm concerned about the folder structure.  I know the public folder in Craft is just a stand in for web_root, but if I allow git to deploy to the server root, won't it try to make a new public folder by default?

Staging setup
/home/user/public_html/staging/public/index.php

Live site
/home/user/public_html/index.php instead of
/home/user/public/index.php

I have seen where I can add a symlink to point one folder to another, but I don't think I can point public_html to a new public folder as I have other subdomains stored in public_html.   Should I just rename public in my Craft files to public_html in the local and staging files, or can I symlink public to public_html without abandoning my existing files?


texts: How can I order each product variant in my templates?

texts:
In Craft Commerce is it possible to order each product variant in the template, I would like to order by price ascending, I've tried the below but nothing is returned?

{% for purchasable in product.variants.order('price asc') %}

Below works but displays in order they were added:

{% for purchasable in product.variants %}


texts: How do I pull the last level of a category?

texts:
This allows me to pull the related categories from a second category group for a given category.

{% set entries = craft.entries.relatedTo(category).find() %}
{% set tags = craft.tags.relatedTo(entries).find() %}
{% set markets = craft.categories.group('markets').relatedTo(entries).find() %}

BUT, it pulls both the parent and descendant categories from markets.  And, some markets do not have descendants - so adding `.level(2) would not capture those that only have a level(1) assigned.

I want to list only the last level assigned whether it is level(1) or level(2).

I tried adding .last() but that generates a CException error.

{% set markets = craft.categories.group('markets').last().relatedTo(entries).find() %}

What am I missing?

Thanks


texts: How can I return data from a Matrix field in random order?

texts: I have a slideshow with slide data managed in a Matrix field. How would I go about randomizing the data returned in the template so the slides show in a different order on each page load?


texts: Is it possible to set a new route for a plug-in CP section in Craft 3?

texts: Is it possible to use a custom route for your plugin's CP section, instead of cpTrigger/plugin-handle, or to direct cpTrigger/plugin-handle to a different template other than plugin-handle/index.twig?


texts:
In my Controller I created a script to add a user to the database, is there a way I can automatically:

1) Log them in and
2) Set a permanent session cookie or similar?

I basically don't want the user to have to ever log in and we will be creating the accounts for them.


texts:
I use the code "Link to the Tag URLs" from the following article:
https://craftcms.com/support/tag-urls

{% if entry.tags | length %}

This entry is tagged with:

    {% for tag in entry.tags %}

{{ tag.title }}

    {% endfor %}

{% endif %}

One thing is that the "url_encode" doesnt really apply as if I expected. The URL looks like this:
http://domain.dev/tags/My%20Tag%20Name

But when I click on it, there are still spaces in the address line.

So my question is: is that ok like this?

I was also thinking about using the kebab filter. There I receive this url:
http://domain.dev/tags/my-tag-name

which looks prettier. But I now I get an error with the routing when I want fetch the tag:

{% set tag = craft.tags.title(tag).first() %}


texts: Dynamic Subfolder Paths - folder does not exist even after updating asset directories in settings

texts:
I have an asset directory which is set to

{basePath}assets/images/products/

I know my basePath is right as it works on other asset sources.

My entry upload location for products is set to:

{slug}/static/studio

However I get the following error when uploading assets:

upload failed. error uploading the file: The folder "/var/www/html/assets/images/products/carambola-earrings/static/studio/" does not exist

I have tried 'updating asset indexes'. But no luck. I have also double checked that the assets/images/products/ directory exists.

I am also checked the permissions are set to '775' for '/var/www/html'

Any help greatly appreciated :)


texts: Undefined index: siteSettings when updating entry types

texts:
I'm receiving an Undefined index: siteSettings when trying to save changes to entry types (both new and existing). Of course, this is only occurring on a production server - local server with up-to-date copies of the DB is working as expected. Also, we're not using project config.

yii\base\ErrorException: Undefined index: siteSettings in /chroot/home/sitename/vendor/craftcms/cms/src/services/Sections.php:608
Stack trace:
#0 /chroot/home/sitename/vendor/craftcms/cms/src/web/ErrorHandler.php(80): yii\base\ErrorHandler->handleError(8, 'Undefined index...', '/chroot/home/ly...', 608)
#1 /chroot/home/sitename/vendor/craftcms/cms/src/services/Sections.php(608): craft\web\ErrorHandler->handleError(8, 'Undefined index...', '/chroot/home/ly...', 608, Array)
#2 /chroot/home/sitename/vendor/craftcms/cms/src/services/ProjectConfig.php(872): craft\services\Sections->handleChangedSection(Object(craft\events\ConfigEvent))
#3 [internal function]: craft\services\ProjectConfig->craft\services\{closure}(Object(craft\events\ConfigEvent))
#4 /chroot/home/sitename/vendor/yiisoft/yii2/base/Component.php(627): call_user_func(Object(Closure), Object(craft\events\ConfigEvent))
#5 /chroot/home/sitename/vendor/craftcms/cms/src/services/ProjectConfig.php(551): yii\base\Component->trigger('addItem', Object(craft\events\ConfigEvent))
#6 /chroot/home/sitename/vendor/craftcms/cms/src/services/ProjectConfig.php(866): craft\services\ProjectConfig->processConfigChanges('sections.0ad0be...')
#7 [internal function]: craft\services\ProjectConfig->craft\services\{closure}(Object(craft\events\ConfigEvent))
#8 /chroot/home/sitename/vendor/yiisoft/yii2/base/Component.php(627): call_user_func(Object(Closure), Object(craft\events\ConfigEvent))
#9 /chroot/home/sitename/vendor/craftcms/cms/src/services/ProjectConfig.php(551): yii\base\Component->trigger('addItem', Object(craft\events\ConfigEvent))
#10 /chroot/home/sitename/vendor/craftcms/cms/src/services/ProjectConfig.php(395): craft\services\ProjectConfig->processConfigChanges('sections.0ad0be...', true)
#11 /chroot/home/sitename/vendor/craftcms/cms/src/services/Sections.php(1174): craft\services\ProjectConfig->set('sections.0ad0be...', Array)
#12 /chroot/home/sitename/vendor/craftcms/cms/src/controllers/SectionsController.php(374): craft\services\Sections->saveEntryType(Object(craft\models\EntryType))
#13 [internal function]: craft\controllers\SectionsController->actionSaveEntryType()
#14 /chroot/home/sitename/vendor/yiisoft/yii2/base/InlineAction.php(57): call_user_func_array(Array, Array)
#15 /chroot/home/sitename/vendor/yiisoft/yii2/base/Controller.php(157): yii\base\InlineAction->runWithParams(Array)
#16 /chroot/home/sitename/vendor/craftcms/cms/src/web/Controller.php(187): yii\base\Controller->runAction('save-entry-type', Array)
#17 /chroot/home/sitename/vendor/yiisoft/yii2/base/Module.php(528): craft\web\Controller->runAction('save-entry-type', Array)
#18 /chroot/home/sitename/vendor/craftcms/cms/src/web/Application.php(299): yii\base\Module->runAction('sections/save-e...', Array)
#19 /chroot/home/sitename/vendor/craftcms/cms/src/web/Application.php(565): craft\web\Application->runAction('sections/save-e...', Array)
#20 /chroot/home/sitename/vendor/craftcms/cms/src/web/Application.php(278): craft\web\Application->_processActionRequest(Object(craft\web\Request))
#21 /chroot/home/sitename/vendor/yiisoft/yii2/base/Application.php(386): craft\web\Application->handleRequest(Object(craft\web\Request))
#22 /chroot/home/sitename/html/index.php(23): yii\base\Application->run()
#23 {main}

Application Info

PHP version: 7.1.33
OS version: Linux 2.6.32-754.18.2.el6.x86_64
Database driver & version: MySQL 5.6.43
Image driver & version: Imagick 3.4.3RC1 (ImageMagick 6.7.2-7)
Craft edition & version: Craft Pro 3.3.19
Yii version: 2.0.31
Twig version: 2.12.3
Guzzle version: 6.5.1
Imagine version: 1.2.3-dev


texts: How to edit interactive "properties for sale" map

texts:
I'm trying to edit a section on the following webpage:
https://edengardensepping.com.au/now-selling
I am new to Craft and this has been a website handed to us to be updated after being built by someone else,
In the second section of this webpage there is an interactive map which I am wanting to edit (see image attached if you are unsure of what I mean):
Does anyone know how they have built this, is it a plugin?
Within Craft they have been using a plugin called Field Manager,
Below is what I need to edit on the map:

I need to edit the background part that is not interactive and upload a new file to replace the one in there with updated information
I need to change the background colour of the sold lots which currently have a red dot on them
I need to remove the text that says "High Park Release" and also the background


texts: How to make PNGs crisp using Imager + Optipng and Craft 3?

texts:
I've installed Imager in a Craft 3 site and everything looks fine except my PNGs are fuzzy. I've set 'pngCompressionLevel' => 0, because I'm using Optipng and the docs say to do this. The PNGs have transparency. Here's a screenshot of the two (left is the normal asset, right is the asset after sent through Imager).

My template code mostly looks like this (a lot of it is originally refactored in a reusable macro):

{%- set logos = entry.partners.all() -%}
{% for logo in logos -%}
   {%- set sizes = craft.imager.transformImage(logo, [{ width: 150 }], {
      format: 'png',
      mode: 'crop',
      allowUpscale: false,
      interlace: true,
      pngCompressionLevel: 0
   }) -%}

{%- endfor %}

The HTML it produces is below. I'm only using one resize width for these logos since they are small, but my macro is setup to accommodate other images with larger srcsets.

I've tried taking out the different config settings like mode, allowUpscale, and interlace but they have no effect.

Any help would be appreciated!


texts: Can I select the latest draft of a given entry?

texts:
I've built a help site for a client that pre-releases articles to a select group of beta users. The updated articles (Craft entries) are published as drafts until features make it out of beta and into the main release.

The client has gone and done the clever thing of using the Live Preview URL (with token) to share with the limited group of beta users who should only have read-only access to the article:

http://cagedwisdom.com/articles/bloopers?token=3p~rKL53nTcTrO_q1XcWsaBNla5VpzTF

Since the token is temporary, this link works for a little while and eventually expires and people can no longer review the draft content.

Is there a way to an entry's latest draft?

Let's pretend that I have a the query parameter &draft=true appended to an article URL, and I use that to selectively get the latest draft:

{% if craft.request.getParam('draft') == true %}
    {% set draftEntry = entry.drafts().order('date desc').first() %}
{% endif %}

Is there a not-imaginary way to do this?

If not, my best ideas are...

To create a plugin that'd allow the editor to create a persistent but removable hash for that specific entry that'd allow access to said draft. (So if the article URL is http://cagedwisdom.com/articles/bloopers, the secret draft share URL would be http://cagedwisdom.com/articles/bloopers&draft=Ag4For3Wom8Ot5eeDd9yAf2g.)
Mess with Craft's token expiration values so the shared links last longer.


texts: How can I set a persistent template variable to use across multiple pages in one site visit?

texts:
I'm working on a site where the site background is chosen randomly from among the entries in an "artwork" channel. I'm using the following code in my _layout.html template to get the url for the chosen image:

{# choose a random entry for the site background #}
{% set randomArtwork = craft.entries.section('artwork').order('RAND()').first() %}

{# set the url for the background image #}
{% set backgroundImageUrl = randomArtwork.artImageBkg.first().url %}

The chosen image is then displayed by adding an inline style to the body tag like this:

<body{% if backgroundImage is defined %} style="background-image: url({{ backgroundImageUrl }});"{% endif %}>

Right now, this code runs on every page request and a different image is displayed on every page load on the site.

However, I'd like to be able to run this code only once per user, per site visit so that the background image will change on repeat visits to the site, but on a single visit, the user will see one persistent image.

How can I go about doing this in Craft?

As an alternative, I also thought to use Craft's {% cache %} tags to set my template variables on a timed basis so that visitors in a particular hour would only see one persistent image, but I couldn't figure out how to get this to work.

When I tried to use the {% cache %} tags on individual templates, I got a warning that a template that extends another (in this case, my _layout.html template) can't have a body.

And adding the {% cache %} tags to my _layout.html template wasn't affecting the persistence of the background image.

Any ideas?


texts:
I am working with a contact form plugin, written by an external developer several years ago. I want to trigger a file download upon successful completion of the form.

As it stands, I have an onPost event listener in a separate plugin which fires if the form data is valid and stored in the database correctly:

craft()->on('capture_submissions.onPost', array($this, 'triggerDownload'));

I have tried several things such as redirecting to a controller action:

$url = UrlHelper::getActionUrl('myplugin/whitepaper/download', array('id' => $id));
craft()->request->redirect($url);

Also tried to use sendFile:

craft()->request->sendFile($filepath, $file_contents);

This works, however I would like the page to refresh first, displaying a confirmation message and then to trigger the download. As it stands, the download is triggered but the page isn't reloaded so no success message and the form data is still displayed.


texts: Craft 3: Possible to merge checkbox and text values from a frontend form and put into a plaintext Craft field?

texts:
Is it possible to submit checkbox array and text values on a front end form into a plaintext Craft field in Craft 3?

My solution worked in Craft 2 but it broke in Craft 3 due to some under the hood changes.

I don't know if this matters, but I'm using Matrix entries to build the actual form in the template.  So the checkboxes and text form fields are being generated from the Matrix entries.

In Craft 2:

I'm using fieldnames with brackets like fields[logGeneral_logInputIndications][] to collect all of the values so they are appended and not overwritten (like it would be if I made it a single line text field.)

Here's an example of what is submitted to the Craft plaintext field:

["Cardiac Activity","Normal","Effusion","Small","No LV Function Assessment Performed","No RV Diameter Assessment Performed","No IVC Diameter Assessment Performed"]

All of the items you see above like "Cardiac Activity", "Normal", etc. are all checkboxes or text form fields on the front end.

I'm using fieldnames with brackets like fields[logGeneral_logInputIndications][] to collect all of the values so they are appended and not overwritten (like it would be if I made it a single line text field.)

In Craft 3:

When I submit the form in Craft 3, I get trim() expects parameter 1 to be string, array given error because the form field I'm submitting like fields[logGeneral_logInputIndications][] is an array but the Craft field the values are writing to is plaintext.

Is it possible to merge the values without building a module?


texts:
I'm trying to setup a bilingual site and I'm having some issues with setting up the URI.

'siteUrl' => array(
    'en' => 'http://localhost/mysite',
    'fr' => 'http://localhost/mysite/fr',
),
'environmentVariables' => array(
    'baseUrl'  => 'http://localhost/mysite/',
)

In my single settings:
URI for french: {baseUrl}fr/nouvelles
URI for english: {baseUrl}news

Not sure how to set this up to have it setup the way I want it.  Removing the baseURL part just doesn't print the mysite subfolder.

Thanks!

EDIT:  Here's the real problematic after investigation.

The URI should not include anything more than the name so:
In my single settings:
URI for french: nouvelles (http://localhost/mysite/fr/nouvelles)
URI for english: news (http://localhost/mysite/news)

Now, those 2 pages work like expected.

But, if I assign those pages to a Entries field, to create my menu, when I pull the url, it never inclues the /fr portion.  Even the default template doesn't render the correct link, dropping the /fr part in the url too:

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

{{ entry.title }}

{% endfor %}


texts: What are the options for taking membership subscriptions via Craft?

texts:
In addition to ‘What is the current landscape regarding e-commerce plugins for Craft?’, I’m looking for current options for setting up membership subscriptions.

I have a site in development that was using the ‘Commerce’ and ‘Membership’ plugins from Dukt (private beta) but unfortunately they no longer appear to be available.

The basic requirements would be for a user to signup, pay for membership (ideally through Stripe in this case), which then automatically assigns users to different membership groups depending on their subscription level/status when appropriate (e.g. full, trial, expired, etc).


texts:
When users enter http://www.example.com I would like to redirect them to the http://www.example.com/news template.

How could I achieve this?


texts: Is there a way to limit the Asset upload directory in Redactor?

texts:
I am looking to control what asset directories are available from the image upload button in a rich text field. Is this possible?

Also, does anyone know the Redactor setting to set the default size of the editor? I can't seem to track it down.

Thanks!


texts: An unknown error occurred - no log entry

texts:
After copying files from a web server to my local devbox I am unable to open any 'Entries'. I keep getting two of the following error: "An unknown error occured."

The assets section does open and I am able to see the various loaded assets.. This also does not display, same error pop-up.

The strangest part is there are no logs to speak of... I tried clearing all the logs just in case, but they're still empty.

I'm using Laragon with PHP 7.2.11 Apache 2.4.35 and two different sites give me the same error.

EDIT: I have tried ignore_user_abort = On in my php.ini file as per a similar issue

EDIT: The only php error is recurring on every page load, but I thought it was a compatibility thing:

[24-Apr-2019 08:08:02 UTC] PHP Warning:  Use of undefined constant auto - assumed 'auto' (this will throw an Error in a future version of PHP) in D:\laragon\www\cannon-kitchens\craft\config\general.php on line 13

EDIT: I am now seeing some logs, but this appears to be normal operation:

2019-04-24 10:13:58
Level   profile
Category    system.db.CDbCommand.query
Message     end:system.db.CDbCommand.query(SELECT `t`.`id` AS `t0_c0`, `t`.`structureId` AS `t0_c1`, `t`.`fieldLayoutId` AS `t0_c2`, `t`.`name` AS `t0_c3`, `t`.`handle` AS `t0_c4`, `t`.`hasUrls` AS `t0_c5`, `t`.`template` AS `t0_c6`, `t`.`dateCreated` AS `t0_c7`, `t`.`dateUpdated` AS `t0_c8`, `t`.`uid` AS `t0_c9`, `structure`.`id` AS `t1_c0`, `structure`.`maxLevels` AS `t1_c1`, `structure`.`dateCreated` AS `t1_c2`, `structure`.`dateUpdated` AS `t1_c3`, `structure`.`uid` AS `t1_c4` FROM `craft_categorygroups` `t` LEFT OUTER JOIN `craft_structures` `structure` ON (`t`.`structureId`=`structure`.`id`) ORDER BY name)
2019-04-24 10:13:58
Level   profile
Category    system.db.CDbCommand.query
Message     begin:system.db.CDbCommand.query(SELECT `t`.`id` AS `t0_c0`, `t`.`structureId` AS `t0_c1`, `t`.`fieldLayoutId` AS `t0_c2`, `t`.`name` AS `t0_c3`, `t`.`handle` AS `t0_c4`, `t`.`hasUrls` AS `t0_c5`, `t`.`template` AS `t0_c6`, `t`.`dateCreated` AS `t0_c7`, `t`.`dateUpdated` AS `t0_c8`, `t`.`uid` AS `t0_c9`, `structure`.`id` AS `t1_c0`, `structure`.`maxLevels` AS `t1_c1`, `structure`.`dateCreated` AS `t1_c2`, `structure`.`dateUpdated` AS `t1_c3`, `structure`.`uid` AS `t1_c4` FROM `craft_categorygroups` `t` LEFT OUTER JOIN `craft_structures` `structure` ON (`t`.`structureId`=`structure`.`id`) ORDER BY name)
2019-04-24 10:13:58
Level   trace
Category    system.db.CDbCommand
Message     Querying SQL: SELECT `t`.`id` AS `t0_c0`, `t`.`structureId` AS `t0_c1`, `t`.`fieldLayoutId` AS `t0_c2`, `t`.`name` AS `t0_c3`, `t`.`handle` AS `t0_c4`, `t`.`hasUrls` AS `t0_c5`, `t`.`template` AS `t0_c6`, `t`.`dateCreated` AS `t0_c7`, `t`.`dateUpdated` AS `t0_c8`, `t`.`uid` AS `t0_c9`, `structure`.`id` AS `t1_c0`, `structure`.`maxLevels` AS `t1_c1`, `structure`.`dateCreated` AS `t1_c2`, `structure`.`dateUpdated` AS `t1_c3`, `structure`.`uid` AS `t1_c4` FROM `craft_categorygroups` `t` LEFT OUTER JOIN `craft_structures` `structure` ON (`t`.`structureId`=`structure`.`id`) ORDER BY name
2019-04-24 10:13:58
Level   profile
Category    system.db.CDbCommand.query
Message     end:system.db.CDbCommand.query(SHOW CREATE TABLE `craft_structures`)


texts: Getting error in template: Impossible to access an attribute ("getUrl") on a NULL variable ("")

texts:
This was working fine previously and not sure what triggered the error. Any idea how to resolve issue?

{% for block in entry.servicesItems.type('images') %}

        {# grab the first image #}
        {% set image = block.image.first() %}

        {# link to the full sized version #}

        {# generated the transformed thumbnail version #}

{{ block.imageTitle }}

{{ block.imageContent }}

{% endfor %}


texts: Adding multiple slashes after the site URL breaks the current entry, but still loads the template

texts:
I've come across an issue where typing the URL e.g www.sitename.com///about will still load the about template, but not fill the page with the content. Is this an issue for google finding the appropriate pages in google searches? And how can I get these pages to no longer exist or result in a redirect to the correct URL www.sitename.com/about?

Thanks for any assistance


texts: Before saving Guest Entries, redirect to an entry review page?

texts:
With guest entries, am I able to redirect before actually saving the entry to say a review page for the user to see the entry?

I figure I could use the guestEntries.beforeSave hook, but not sure how I'd show the information on the page... or pass to a template.

Any suggestions?


texts: Eager-Loading child elements in a multi-level structure section

texts:
I have a structure that looks like this:

Experiment ( Level 1)

Cages (Level 2)
Animals (Level 3)
Measurement (Level 4)

I am outputting this information into some inline JSON like so:

{% set mice = craft.entries({
    'section' : 'experiments',
    'level' : 3,
    'descendantOf' : entry.id,
}) %}

<script>
  var data = [
    {% for mouse in mice %}
    {
      "Cage": "{{ mouse.parent.title }}",
      "Mouse": "{{ mouse.title }}",
      "measurements": [
        {% for data in mouse.children.order('postDate') %}
        {
          "Date": "{{ data.postDate| date("d-M") }}",
          "Weight(g)": "{{ data.weight }}",
          "Length": "{{ data.length }}",
          "Depth": "{{ data.depth }}",
          "Tumor Volume": {{ data.tumourVolume }}
        }{% if not loop.last %}, {% endif %}
        {% endfor %}
      ]
    }{% if not loop.last %}, {% endif %}
    {% endfor %}
  ];
</script>

This is ok until entries start to increase, the TTFB begins to add up significantly - I am wondering if there is a way to eager load this sort of structure? The entries are very dynamic so caching isn't an option.

Thanks!


texts: I recently updated to Craft v3.6, which appears to have changed the publishing workflow to require first publishing the draft, then saving the file in order to get back to the entries list. Is there any way to revert to the previous workflow of being able to just press a single button to create a new entry, publish it, and get back to the entries list?


texts: Two domains with two different templates

texts:
I'm trying to build a website for a client that has actually two websites for different locations and we need to merge both of them in a new one.

The only thing is that he wants to keep the domains separate, which means that when you visit website1.com you will see templates for that website and the url address will display website1.com/.../ etc. And when you visit website2.com while you browse the site you will retain this url.

Is this possible with Craft? Because we will have one database and install but 2 domains with one parked over the other. Can this be done with the Multi-environment technique described here?

https://craftcms.com/docs/multi-environment-configs


texts: Element API: List entries related by tag

texts:
How can I pull out other entries related by tag using the Element API?

In this particular case I'm using the Similar plugin to pull out related entries by tag in the templates. I'm not sure if this would help to provide an easier way or not...?


texts: Can we define routes (non-CP) in plugins?

texts:
I don't suspect it's currently possible but  I would be pleasantly surprised to find that it is.

I'm going to use an example from Django because I've seen it used there and a similar implementation would be handy to have in Craft. Annnnd it would be helpful for what we're trying to achieve with my current project.

Example:
In Django you have your project-wide urls.py (think of this as routes.php in Craft). Additionally you can have app-specific URLs (an App might be a Blog or a Portfolio). You can define the app-specific paths in the app-specific urls.py file and then you can include those URLs in the project-wide URL file. That might look like this (example from the Django docs):

urlpatterns = [
    # ... snip ...
    url(r'^community/', include('django_website.aggregator.urls')),
    url(r'^contact/', include('django_website.contact.urls')),
    # ... snip ...
]

So a use-case:

We're developing a REST API and right now all of our routes are defined in routes.php. That's an ok solution, but we have a lot of plugin-specific routes. It would be nice to be able to define a base such as /api/ and pass the rest of the request to a plugin-specific routes file.

An idea of what this might look like:

return array(
    'api'   => array('pluginRoutes' => 'apiPluginName'),
);

And then in craft/plugins/apiPluginName/routes.php would be a routes file similar to the project-wide routes.php file in craft/config


texts:
Is there a way to differentiate the number field value empty and 0?

I would like to display this field only when there's a value in the field even though the value is 0.

But when I input 0 into the field, it seems that Craft thinks the value is empty... so doesn't still display the field.

Thanks.


texts: Upload assets manually: replace existing files

texts:
Context: For a redesign and port to CraftCMS, I need to import the content from a blog hosted on another platform with a lot of content (over 500 posts and over 3000 images).

Strategy: To import the images from external URLS, I have written a simple "dedicated" plugin which uses the technique described here and relies on craft()->assets->insertFileByLocalPath().

Issue: To make sure each import uploads the latest version of the images, I pass AssetConflictResolution::Replace as fourth argument to the method. This works perfectly the first time I run the import, but dies when files were uploaded before and there is a filename conflict:

Trying to get property of non-object
[...] $source = craft()->assetSources->getSourceTypeById($theNewFile->sourceId);

I am not sure why this error occurs, but I suspect it is because newly imported files are not uploaded yet at the time Craft tries to resolve the conflict.

Possible solutions: I tried to handle conflicts manually, by first deleting the existing file with craft()->assets->deleteFiles($response->getDataItem('fileId'), true), and then re-uploading the new file with insertFileByLocalPath but no success...

Since the target assets source is reserved for the imported images, I also thought about dumping all files in the target assets source before the import starts. But that would cause problems if I want to import only a subset of all the post images (very likely since the import needs time to execute).

Question: How can I work around this error?

The solution should make sure:

newly uploaded files always replaces existing files with the same filename.
partial imports don't remove unrelated files that were uploaded before.


texts: Printmaker fails to render images under SSL

texts:
I am using the Printmaker plugin to print a pdf. Everything seems to be working well when the site is not being forced to use SSL.

I am getting the message "Failed to load PDF document."

If I remove the SSL, the pdf renders correctly. I would really like to have my site be under https - is there any way to help printmaker work?

I don't see anything obvious in the craft.log that would indicate an error, is there a configuration setting I'm missing?

Thank you for any suggestions!

EDIT

It is the actual image(s) in the pdf that are causing the error.

The full path to the S3 bucket is https, and I'm able to access the image just straight through the browser. I've copied/paste into the url bar and the image will render.

If I set the S3 path to http, and set the browser to http - all is well.
If I set the S3 path to https, and the browser to http - all is well.
If I set the S3 path to https and the browser to https - pdf fails to render.

UPDATE

To further test and and attempt to get some kind of error message/log to help trouble shoot, I've moved my image directory to a local path. I now the error "Image not found or type unknown". It looks like this could be a DOMPDF issue. I will continue to update this thread as I uncover more.

UPDATE

It does seem to be something related to forcing requests to SSL. If I remove https, the pdf renders every single time, every browser. If the request is made to the pdf using https, it fails every time.


texts:
How can I get the top level ancestor of an entry within a structure? I've tried:

{% set rootEntry = null %}
{% for ancestor in entry.getAncestors() %}
    {% set rootEntry = ancestor %}
{% endfor %}

But that only returns the most recent ancestor back and doesn't go all the way up the chain.


texts: Filtering on related entries (with an array query param)

texts:
I'm getting myself into a potential pickle here and wanting to know the best way to get apply filters on the current scenario:

I have a central business section which is getting populated via an API (just a little background info) and I have a second section drugs which has a Entries field that contains a link to business.

I've designed a table that pulls in all this info that looks a little something like this:

I've built out the table like this:

{# DEFAULTS #}
{% set queryParams = {
    section: 'business',
    order: 'title asc',
    limit: 30
} %}
{% for entry in craft.entries(queryParams) %}

{{entry.title}} {{entry.business_name}}

        {{entry.business_price}}
        {% if "+" in entry.business_change %}
            {{entry.business_change}} {{entry.business_percentChange}}
        {% else %}
            {{entry.business_change}} {{entry.business_percentChange}}
        {% endif %}

${{entry.business_market_cap}}

{{entry.business_number_of_shares|number}}

{{entry.business_shortRatio}}

{{entry.dateUpdated}}

                    Drug
                    Indication
                    Stage
                    News

            {% set relatedDrugs = craft.entries.section('drug').relatedTo(entry) %}
            {% for drug in relatedDrugs %}

                {{ drug.title }}
                {{ drug.drug_indication}}
                {{ drug.drug_stage.label}}
                {{ drug.drug_note}}

            {% endfor %}

{% endfor %}

Now – the pickle is the filtering side of things: I'm wanting to filter on the drug stage, AND to make matters even more exciting this is a multi-select filter which I've done like this:

<fieldset>
    <legend>Stage</legend>
    {% set stage = craft.fields.getFieldByHandle('drug_stage') %}
    {% for stage in stage.settings.options %}
        {% if loop.first %}<select name="stage[]" multiple>{% endif %}
          <option value="{{stage.value}}">{{stage.label}}</option>
        {% if loop.last %}</select>{% endif %}
    {% endfor %}
</fieldset>

I'm not really sure how to enable multiple params of the same name so I've called it stage[] which handily returns an array. The problem I'm having now is building that new param filter query... I got as far as this and stared blankly at the screen for 10 minutes (I'm no programmer...)

{% set stage = craft.request.getParam('stage') %}
{% if stage is not empty %}
    {# NO IDEA #}
{% endif %}

I really have no idea where to start. Any pointers or help would be fantastic!


texts:
I'm building my first Craft 3 site, and having problems getting email to send. I've set it to use Sendmail but when I click the Test button in the CP, I get "There was an error testing your email settings".

I know Sendmail isn't the best option but I need something for now until we get something more robust in place. My client doesn't yet have any email set up for this domain, but I assume Sendmail should still be able to create email?

I've tried using Sendmail from the command line and that seems to work fine. For each attempt to test from the control panel, I get this error in web.log:

2018-08-20 10:02:55 [86.167.235.31][1][-][error][application] Error sending email: Expected response code 220 but got code "", with message ""

I'm on Craft 3.0.19. Any ideas what might be going wrong?


texts: autoLoginAfterAccountActivation doesn't seem to be working

texts:
In the midst of an upgrade from 2 > 3 (Commerce on top of that too).
When a user creates an account, it fires an 'Activate your account' email
That email goes through to account/activation-success and the account is verified and all is well. Almost.
On that template, we have {{ currentUser }} but in v3 - it's null because auto-login doesn't look to be functioning.
In general.php we've got:
'activateAccountSuccessPath' => 'account/activation-success',
'autoLoginAfterAccountActivation' => true,

Has something changed? We're on Craft 3.5.16 and Commerce 3.2.12


texts: Problems translating the default "Name" field on tags

texts:
I'm building a multi-lingual site (english and spanish) and I have a news section with entries that have a "tags" field attached.

I've marked this field as "translatable" in the CP.

But, when I've added a tag to an entry, double clicking it reveals the pop-up field editor where I can switch between locales as expected (see screenshot). But I can't enter different values for "Name" in each locale. It behaves like a  non-translatable field where changing the value in one locale changes it for all the others.

Setting my "tags" field as translatable in the CP seems to allow me to assign different tags to the entry for each locale, but that's not what I want. What I want is to have an entry's tags persist across locales, but be translated into their appropriate language.

Is the default "Name" field for tags translatable? How should I be setting this up to get the behavior I want?

Thanks for the help.


texts: How to keep staging install synced with member registration

texts:
What is the best way to keep live and staging environments synced with member registrations?
I can export/import the database from the live to staging environment to keep it in sync - and have a content freeze on the live version during development on the staging version.
But the live website will continue to allow new member accounts to be created, meaning the staging environment will be out of sync.


texts:
I need to automatically set the expire date of a new entry (only) from a specific section.

I know that it's possible to do this via the frontend twig templates, however I need the user to have the flexibility to change the date from the default that's set if they want to.

So when they create a new entry it'll have an expiration date of today + 3 months, but if they wanted they could change this date to next Wednesday or whatever they wanted.

Thanks for your help


texts: Importing tables and Tablepress like plugin functionality

texts:
Is there a plugin or something equivalent to Tablepress (WordPress) for Craft?

I have some large Excel table containing product pricings amongst other things, that I would like to import into Craft and manage there.


texts:
I'm outputting a Sprout form on my site so that users can request an update to their profile using the short code

{{ craft.sproutForms.displayForm('updateStoreDetails') }}

I would like to pre-populate the form with information from the current entry object in the template. I tried to do something like this...

{{ craft.sproutForms.displayForm('updateStoreDetails', {
    "fields": {
        "memberId": {
            "value": 12345
        },
        "name": {
            "value": "Michael"
        }
    }
}) }}

but it doesn't seem to do the trick. Is there a way of doing this?


texts:
We have 2 clients that want to have an online shop website. One with 100 products, with 10,000 products.

We've built 100's of websites, but no e-commerce sites yet. We're in the stage of writing the proposals/estimates, but because the clients have been long-time clients, they have confidence that we propose them the right platform. Or, read: they will go with our proposals.

My question is: why would anyone choose Craft Commerce over Magento?
(I'm not even considering any WP based solutions).


texts: Exclude output of entries/users/products if category relation has particular field value

texts:
So basically what i have is a big set of categories (about 86 total, multi-level). Within my category fields i have a lightswitch with the handle 'private'. I would like to know how i would write a set/query to exclude any products/entries/users from appearing in a for loop if that item is in a category where the field 'private' is set to '1' meaning 'yes'.

Meaning if Product 'T-Shirt' is in category 'Awesome' and category 'Tubular' and category 'Ugly'. Assuming the category 'Ugly' has that field set to '1/yes'. When i run a for-loop for all products inside 'Awesome', how do i prevent 'T-Shirt' from appearing because it is ALSO inside of the category 'Ugly' which has the 'Private' set to yes?

The first instance of where i need this, my code is as follows:

{% for category in craft.categories.group('productCategory').level(1) %}

 1 %} hidden{% endif %}' id='content-{{ loop.index }}'>

{{ category.description }}

                    {% include '_components/featured_products' %}
                    See Full Range »

        {% endfor %}

And then the _components/featured_products template looks like this:

{% set products = craft.commerce.products.relatedTo(category).order('RAND()').limit(4) %}
{% for entry in products %}
    {% set image = entry.keyImage.first() %}
    {% set prodSize = { mode: 'crop', width: 200, height: 200, position: 'center-center' } %}

            {{ entry.title }}

{% endfor %}


texts: Best way to effect part word searching by default

texts:
I want to use the standard site search but much prefer that (first) part word search is in place by default. By this I mean if a user searches for dog they will also find dogs, so the term Craft uses would then be dog*.

My strategy would then be to take the search string (e.g. 'dog fee') and remove any commas or fullstops unless the string is in quotes ("dog fee"). I would then split the string using spaces and throw away any empty strings ('dog', 'fee'), and then append the * to each word and send 'dog* fee*' to the search system.

Is this the best approach to get what I want, or have I missed a glaringly obvious and easy way of doing it?


texts:
Is it possible to stay on the same page after logging out from the frontend, assuming that guests can still view that page?
By default, when logging out we are redirected to the homepage or some specific page set with postLogoutRedirect config setting.


texts: Does Craft do joined calls or multiple ones when fetching the related items? [Element API]

texts:
I'm checking Element API's performance to decide if it's a good idea to replace my own custom API with Element API. Right now, when fetching the related items (Via fields or matrix elements), my API creates a unique joined query with all the right criteria and executes it at the end.

As Element API is able to use all the nice methods from Craft, maybe the question is related to Craft structure itself.

I've tried using MySQL´s SHOW STATUS LIKE 'Com_Select' but it was not really useful.


texts: Advanced routing descriptive URLs to certain pages/posts

texts:
This is a general SEO question.

In Wordpress you can create a page and define the permalink URL.

In Craft I want to do something similar. I want to build the backend with a common sense structure, but then define friendly URLs after. Eg: a page could exist somewhere like:

domain.com/holidays/french-river-cruises

Is it possible to define custom routing, so I could make the same page/post accessible on a more descriptive URL (for SEO reasons) to load the same page.

domain.com/summer-cruises-in-france

I know you can play with routes, but in this case I don't see how it would work that was as the slug doesn't match the post. But could this be hardcoded somehow in the advanced routes file?


texts: Craft folder deployment outside public folder

texts:
I would like to commit my craft project to bitbucket en deploy it with the help of Deploybot.

The plan is to put the templates (in craft folder) and public assets (public folder) under version control and deploy it with Deploybot. But how do i get the files published into the right directories on the live/staging server.

My craft folder is outside the public root and the public files/assets are inside the public root. So i have two source directories and two destination directories, and this isn't an option with Deploybot. Is there someone with the same setup and a solution?

Thnx in advance!


texts:
Here is my query:

{% set resources = craft.entries({
    section: 'resources',
    type: 'not caseStudyLanding'
    relatedTo: filterParams,
    orderBy: 'postDate desc'
}) %}

I would like to exclude two entry types (caseStudyLanding and webinarsLanding) but I have been struggling with the syntax.


texts: How to add tags to an entry per site basis. And then only get the tags for that site in the frontend

texts:
I have craft pro and have one tagGroup called Tags
Then I created a Tag field called newsTag like this:

When I add a tag for german, the tag is also created in the database for dutch and english, so when I get a list of used tags like this:
{% set tagsEntries = craft.entries
    .section('news')
    .limit(null)
    .all() %}

{% for atag in craft.tags.relatedTo(tagsEntries) %}

{{ atag.title }}

{% endfor %}

Now I get all tags used in all sites. when I use it like this:
{% set tags = craft.tags.relatedTo({
      sourceElement: tagsEntries,
      sourceLocale: craft.site
    }) %}

Then I still get all tags, because when I look at the database the tag for German is also created for Dutch and English:
In the content table:

When I remove the entry for site 1 and 3 (the dutch and english site) the it works, but will be added again on entry save...
Is it somehow possible to only save a tag for one site? That way I can get all the tags only used in that site and not all.
ps, this only happens with tags in entries that are used/enabled for 2 or more sites.
Thanks for the help,
Dimitri


texts:
I have a channel where I need each entry's Title include a sequential number, like this: 10003 - Entry Title
Is there a way to prepend a sequential number to the entry title?


texts: How to prevent cache busting (preferably on a single section)?

texts:
I have a template that displays 1,100 entries as dots on a zoomable/searchable map. The query is cached and it performs beautifully. As expected, if I edit any of those entries the cache is busted and the next page load lags.

What I prefer to do is have the cache rebuilt once per day via a cron job or some other method.

For starters, I added

'cacheElementQueries' => false,

to my general config. I thought this prevents automatic cache busting, but it does not seem to. If I edit an entry, the cache is still being rebuilt (or so I assume by the page load time).

Any help on what I'm not understanding? Thanks in advance.


texts: Updating `{{ forms.dateField }}` value from GET variable

texts:
I want to use the built-in Craft field macros to show a date field in a plugin template for filtering.

I can retrieve the submitted value on any submission (via GET) but how do I then prepopulate said date field with the previously submitted value?
When I try to simply pass the submission into the value property I get an Array to string conversion error.

My plugin template code …

{% set start = craft.request.getParam('start') %}
{{ dump(start) }}
{{ forms.dateField({
    label: 'Start date',
    id: 'start',
    name: 'start',
    value: start }) }}

So my question is; is there anyway I can pass a value into the dateField that has been submitted via a POST or GET variable?


texts:
I'm trying to embed the sidebar and define which blocks to display.

{% embed "_partials/sidebar" %}
    {% block instagram %}{% endblock %}
    {% block subscribe %}{% endblock %}
{% endembed %}

sidebar.html is

{% block subscribe %}
    block content
{% endblock %}

But it doesn't show anything and no errors as well (dev mode enabled).

The idea is make a dynamic sidebar and define which widgets I'd like to see in each template.

This is what I use right now.

        {% set widgets = {
            'about'     : true,
            'instagram' : true,
            'menu'      : false,
            'recipes'   : true,
            'subscribe' : true
        } %}

        {% include "_partials/sidebar" with {
            widgets: widgets
        } %}

sidebar.html

       {% if widgets.menu == 'true' %}
           content
       {% endif %}

is there any other more flexible approaches for this?


texts:
I have a field called "assetId" from Entry "A" with Field Type "Entries" and Source "B". How can I build a form so that a relation between these two entries will be established.

In the craft backend I can add a new entry in Entry "A" and can use the Button "Add an entry" to select the suitable Entry from "B". This works fine. A record is written in the Table craft_relations.

How can I build a user form in the frontend to get this. I tried following form with a hidden field "fields[assetId]" which is set to the id of the suitable content:

<form method="post" accept-charset="UTF-8" enctype="multipart/form-data" class="send-form" id="send-form">
    <input type="hidden" name="action" value="entries/saveEntry"/>
    <input type="hidden" name="sectionId" value="34">
    <input type="hidden" name="enabled" value="1">
    <input type="hidden" name="fields[assetId]" value="1478" id="hidden-assetID">
    [... some more fields ...]
     <input class="btn-vote" type="submit" value="send">

</form>

The entry is saved correctly, but without the assetId. There is no relation between targetId 1478 and the new entry in the Table craft_relations established. What am I doing wrong?


texts: How to correctly format API requests for Mandrill using Fetch plugin? Getting error "you must specify a key value"

texts:
I want to use the Fetch plugin (v 1.2.0; Craft Pro 3.3.13) to send messages from a Twig template in some circumstances.

To test the setup, I'm just trying to ping Mandrill, according to the /users/ping.json call: https://mandrillapp.com/api/docs/users.JSON.html#method=ping.

I've tried a bunch of variations, but I keep getting this error:

1 - Server error:
`GET https://mandrillapp.com/api/1.0/users/ping.json`
resulted in a `500 Internal Server Error` response:
{
  "status":"error",
  "code":-1,
  "name":"ValidationError",
  "message":"You must specify a key value"
}

According to this answer (admittedly from 2013), "This particular error is common if the JSON is invalid for some reason."

I've looked at Jalen's excellent answer on another Fetch question, but that's for a different API and I'm not sure what to do.

Here's my current code:

      {% set client = {
          base_uri : 'https://mandrillapp.com/api/1.0/',
          timeout : 10
        } %}

        {% set options = {
          key: 'REDACTED',
        } %}

        {% set destination = 'users/ping.json' %}

        {% set request = fetch(client, 'GET', destination, options) %}

I've also tried it with POST, and with various permutations of quotes around the key and api key; same error.


texts:
I've been using Craft CMS for a while, but haven't seen any way to get the following done:

Looking to create a page with a large image on it. The image would be overlayed with buttons that pop-out a text box or overlaid image. I'd like to place the pop-out boxes/graphics all over the image in specific places, but the creation interfaces I've seen only let me put one image after another in a list, or rectilinear fashion.
I'm hoping to create a map of a neighborhood where clicking on different buildings/elements pops out another window with more information regarding that area/element.

I hope this is understandable, if more clarity is needed please let me know.

Any insight would be greatly appreciated.

Thanks


texts: How do you manage master db across multiple environments?

texts:
I've just started my first Craft site locally and it's all good so far.. a little further down the road, I'll need to then deploy regularly to integration/test/stage and production environments.

I'm just wondering how people manage DB syncing across these different environments?


texts: I’m trying to update Craft Pro 2.0.2543 to the latest build but the site’s database is in excess of 2Gb. When hitting ‘Finish up’ in the CP after a manual update, by the time the database has backed up I’m logged out, or the process has timed out. Is there a way I can ‘Finish up’ without the backup running first?


texts: I would like to implement the remarketing tag into my website

texts: I was wondering if anybody can help me with the implementation of the remarketing tag into my site. I have the codes and I just don't know where to enter them.


texts:
I am setting up 2 node cluster with GlusterFS for shared file system. I have mounted the shared mount on each of the nodes but when I try to access login page I get this

/data/websites/websiteapp/craft/storage/ doesn't exist or isn't writable by PHP. Please fix that.

The folder permissions are lrwxrwxrwrx. Is there anything I need to do make it work?


texts: Complex custom SQL query with multiple relationships (Craft DB)

texts:
For the Sprout Reports plugin I need to write a custom SQL query to get some Craft data. (We use this plugin so our client can easily generate CSV exports at any time from the CP).

As there are multiple relations with both Entries and Users, the query becomes quite tricky.. Any help in the right direction would be awesome!

-

This is the case:

We have subscriptions, which have subscription data and a relationship to a course (Entry) and a school (User). The course has a relationship to a sportsclub (User). We need a single SQL query that pulls all this data from the Craft database.

-

We have the following tables:

craft_sections

id|name
--|-------------
 1|subscriptions
 2|courses

craft_entries

 id|sectionId
---|---------
 50|        1       (subscriptions)
 51|        1       (subscriptions)
 52|        1       (subscriptions)
100|        2       (courses)
102|        2       (courses)
104|        2       (courses)

craft_content

id|elementId|name      |gender|city      |course_name     |school_name|club_name
--|---------|----------|------|----------|----------------|-----------|-----------
 1|       50|John Doe  |Male  |New York  |                |           |
 2|       51|Lisa Smith|Female|New Jersey|                |           |
 3|       52|Brad Bell |Male  |Washington|                |           |
 4|      100|          |      |          |Basketballcourse|           |
 5|      101|          |      |          |                |School 1   |
 6|      102|          |      |          |Volleybalcourse |           |
 7|      103|          |      |          |                |School 2   |
 8|      104|          |      |          |Swimmingcourse  |           |
 9|      105|          |      |          |                |School 3   |
10|      150|          |      |          |                |           |Sportsclub 1
11|      151|          |      |          |                |           |Sportsclub 2
12|      152|          |      |          |                |           |Sportsclub 3

craft_content elementId = craft_entries id and craft_elements id

craft_relations

id|sourceId|targetId
--|--------|--------
 1|      50|     100       (subscription -> course)
 2|      50|     101       (subscription -> school)
 3|      51|     102       (subscription -> course)
 4|      51|     103       (subscription -> school)
 5|      52|     104       (subscription -> course)
 6|      52|     105       (subscription -> school)
 7|     100|     150       (course -> sportsclub)
 8|     102|     151       (course -> sportsclub)
 9|     104|     152       (course -> sportsclub)

sourceId and targetId relate to the craft_elements table, where you can get the type of the element. The Ids also relate to the elemendId in the craft_content table.

craft_elements

id |type
---|-----
 50|Entry       (subscription)
 51|Entry       (subscription)
 52|Entry       (subscription)
100|Entry       (course)
101|User        (school)
102|Entry       (course)
103|User        (school)
104|Entry       (course)
105|User        (school)
150|User        (sportsclub)
151|User        (sportsclub)
152|User        (sportsclub)

craft_users

id|username
--|--------
 1|school_1
 2|school_2
 3|school_3
 4|sportsclub_1
 5|sportsclub_2
 6|sportsclub_3

craft_usergroups

id|name
--|-----------
 1|Schools
 2|Sportsclubs

craft_usergroups_users

id|groupId|userId
--|-------|------
 1|      1|     1
 2|      1|     2
 3|      1|     3
 4|      2|     4
 5|      2|     5
 6|      2|     6

-

The desired result from the query:

id|name      |gender|city      |course_name     |school_name|club_name
--|----------|------|----------|----------------|-----------|------------
 1|John Doe  |Male  |New York  |Basketballcourse|School 1   |Sportsclub 1
 2|Lisa Smith|Female|New Jersey|Volleybalcourse |School 2   |Sportsclub 2
 3|Brad Bell |Male  |Washington|Swimmingcourse  |School 3   |Sportclubs 3


texts:
I have an entry form in home page which the home page already using the entry object.

And I am placing the entry form in home page when i call

  {%- if entry is defined %} value="{{ entry.title }}"{% endif -%}

and this will grab the home page title, and this is not the result i want.
I need when the form submit and error return with value.

By the way, any source to learn about entry form? I don't see much tutorial about entry form. Thanks.


texts: Generating responsive images from cropped source file

texts:
I've been trying to adapt this helpful post to work with Image Transforms, so that the starting point for generating the responsive images is a cropped high resolution original.

I've defined a Transform called 'fullWidth' in the CMS, and have tried calling:

{% do image.setTransform('fullWidth') %}

Tearing my hair out, would someone be kind enough to assist?

Original code:

{% macro srcset(image, maxCssWidth, includeDimensions) %}
{%- spaceless %}
    {# Is this a 2X image? #}
    {% set is2x = image.filename matches '/@2x\\.\\w+$/' %}

    {# Determine the CSS width for the image, if it were output at 100% #}
    {% set cssWidth = (is2x ? round(image.width / 2) : image.width) %}

    {# Determine the image size that 1X screens should get #}
    {% set width = (cssWidth > maxCssWidth ? maxCssWidth : cssWidth) %}

    {# Determine the image size that 2X screens should get #}
    {% set width2x = (width * 2) > image.width ? image.width : (width * 2) %}

    {# Output the srcset= attribute value #}
    srcset="{{ image.getUrl(image.width != width ? { width: width }) }}, {{ image.getUrl(image.width != width2x ? { width: width2x }) }} 2x"

    {#- Output the width= and height= attributes if needed #}
    {%- if includeDimensions %} width="{{ width }}" height="{{ image.getHeight({ width: width }) }}"{% endif %}
{% endspaceless -%}
{% endmacro %}


texts: I could not find any documentation on the 'Webhook Signing Secret' used in Commerce Settings > Gateway > Stripe Gateway. Can someone tell me what this is, what it's used for and typically what I should be entering as a value? Not sure if this is even required? References or insight most appreciated.


texts: How can I best troubleshoot a 404 error loading a template from a previous iteration of my site?

texts:
I had a Craft Site, which I'll refer to here as the old site. I replaced it with a new site on the same server. To do this I overwrote the old site's database and files. I kept the old site's public web root folder intact, and assigned a different web root folder to my new site via my hosting control panel.
Long story short, my new site launched and everything looks great. Except... when Craft loads my 404 template it shows the one from my old site. That template, to the best of my knowledge, doesn't exist on this server anymore (see update below). It's a new database. I have a 404 template for my new site that works fine on my local dev machine, but in production it will only show me the old site's 404.
Anybody know how I can troubleshoot this? I renamed the old site's web root folder (which, again, I'm not even sure is part of the problem) and that didn't change anything. I've cleared my caches. I've tested on multiple devices.
I'm hosted at FortRabbit, if that helps.
UPDATE: I found a copy of the old site's 404 template in a file in the compiled_templates folder. I tried renaming that file with no luck (Craft just generates a new one). But it all certainly feels related. Any ideas?


texts: Best location for Craft development? Local or Server? Subfolder of production?

texts:
What's the best practice for development Craft installations? I think I would like to work on the production web server but in a hidden folder either upstream from my public HTML or as a subfolder.

Does it matter where I install and develop my Craft site? Looking for easy migration when I want to go live.


texts:
I've added a field to an asset which in my case is a fallback image for a video asset.

When uploading a video the field for the fallback image isn't visible so the chances of forgetting to set one is bigger.

To set the fallback image I need to edit my video asset and set the fallback image in there.

In my case I'd rather set the fallback image in the entrytype so it won't get forgotten.

When does it make sense to add the field directly to the asset instead of defining a field in a entrytype?

Fieldlayout entrytype version:

Video (asset)
Video Thumbnail (asset)


texts: Landing Page with Same URL Structure as Category

texts:
I have a category group called "Resource Categories" and categories within it have their own urls.

Category Url Formats:

top-level categories: resources/{slug}
nested categories: {parent.uri}/{slug}

Category Template:
resources/_category

There's also a category template which is here:
resources/_entry

What I want to do is add a Landing page at /resources.

This would be a standard entry page ideally created within my Pages channel using the pages/_entry template.

Failing that I could also create an index page inside the resources folder.

But I keep getting 403 forbidden when visiting site.com/resources.

I've tried creating a route but that doesn't help the issue.

'resources' => 'pages/_entry'


texts: How do I display data from an entry field related to each user in a user listing page?

texts:
I am displaying a list of users with entries in the Design section using a Route. I am using this code for that and it seems to be working to display the correct users:

{# Grab all the Design Entries #}
{% set designs = craft.entries.section('designs').find() %}

{# Group by the authorId #}
{% set entriesByAuthor = designs|group('authorId') %}

{# Grab all of the users with the userIds in entriesByAuthor #}
{% set designers = craft.users.id(entriesByAuthor|keys).group('members') %}

Although the issues I am having is trying to display data from fields from the entries by these users. For example, entries in the Design section also have images associated with them. I am trying to display the first image from the 'screenshots' field from the Designs section:

{% for assets in designers %}
    {% for image in assets.screenshots %}

        {% if image %}

        {% endif %}

    {% endfor %}
{% endfor %}

This does not give an error, but does not display anything for the image. I also tried adding .first() to this to get the first image from each entry, but that resulted in an error.

Any help will be appreciated! I have searched thoroughly for information about displaying entry fields from a user list (instead of just user fields) and I have not been able to find this information. (I also tried several other methods, such as relatedTo.)

Thanks!


texts: Unknown error occurs on every AJAX call in CP

texts:
I was working on a plugin with a hook on onBeforeSaveEntry in my dev environment (which is configured exactly like my live environment).

I had a var_dump with an exit in the hook to check output of some variables on save.

After deleting the var_dump and exit from the code the control panel now gives a unknown error on top of every page (which has an AJAX request).

I've deleted any entry I've made today since the code changes but still no effect.

After inspecting the logs the exception seems to be thrown in the BaseController class:

/**
 * Throws a 400 error if this isn’t an Ajax request.
 *
 * @throws HttpException
 * @return null
 */
public function requireAjaxRequest()
{
    if (!craft()->request->isAjaxRequest())
    {
        throw new HttpException(400);
    }
}

Log output:

2016/08/15 21:05:16 [error] [exception.Craft\HttpException.400] exception 'Craft\HttpException' in /...myserverpath.../craft/app/controllers/BaseController.php:217
Stack trace:
#0 /...myserverpath.../craft/app/controllers/BaseElementsController.php(30): Craft\BaseController->requireAjaxRequest()
#1 /...myserverpath.../craft/app/controllers/ElementIndexController.php(66): Craft\BaseElementsController->init()
#2 /...myserverpath.../craft/app/framework/web/CWebApplication.php(281): Craft\ElementIndexController->init()
#3 /...myserverpath.../craft/app/etc/web/WebApp.php(815): CWebApplication->runController('elementIndex/ge...')
#4 /...myserverpath.../craft/app/etc/web/WebApp.php(285): Craft\WebApp->_processActionRequest()
#5 /...myserverpath.../craft/app/framework/base/CApplication.php(185): Craft\WebApp->processRequest()
#6 /...myserverpath.../craft/app/index.php(58): CApplication->run()

When I comment out the line:

throw new HttpException(400);

Everything is working fine.
Because it seems to be an AJAX error, I tried another browser as well but the same error occurs.

Anybody got any ideas?


texts:
I'm trying to set up having the first entry pull in and then later down the page pull in the remaining posts (as I need to break the loop with other content). I'm a little unsure how to set up pulling in the 'Not firstEntry' for the second part. This is what I'm working with:
{% paginate craft.entries.section('blog').limit(1) as entriesOnPage %}
{% for entry in entriesOnPage %}
{% set firstEntry = craft.entries.section('blog').order('postDate desc').one() %}

{% if entry.id == firstEntry.id and craft.request.getPageNum() == 1 %}
//output first entry
{% endif %}
{% endfor %}

// DO OTHER STUFF

{% paginate craft.entries.section('blog').limit(12) as entriesOnPage %}
{% for entry in entriesOnPage %}

//OUTPUT 12 Entries not including the first

{% endfor %}


texts: How can I set the "activateAccountSuccessPath" for users with Control Panel access?

texts:
I have a site that allows public registration, and I want to be able to control where users are redirected to after activating their account. However the default user group has access to the Control Panel, so as explained in “activateAccountSuccessPath doesn't work as expected”, users are taken to the Control Panel login page after activation, rather than the path defined by the activateAccountSuccessPath config setting.

Is there any way to change that behavior, so even users with access to the Control Panel will get redirected to the activateAccountSuccessPath after account activation?


texts: Group by Date Field in Element API Query

texts:
I have a custom field called releaseDate in one of my entry types. I would like to use Element API to get all the distinct years assigned to those entries. I dump all the years for all entries just fine like this:

'endpoints' => [
    'api/v1/release_years' => function () {
    return [
        'class' => EntryResource::class,
        'elementType' => Entry::class,
        'criteria' => [
            'section' => 'products',
            'orderBy' => 'field_releaseDate',
            'where' => 'field_releaseDate IS NOT NULL',
//          'groupBy' => '????????'
        ],
        'transformer' => function (Entry $entry) {
            return [$entry->releaseDate->format('Y')];
        },
        'pretty' => true
    ];
}

But the minute I add a group clause to the criteria section, it fails. I've tried the following:

'groupBy' => 'YEAR(field_relaseDate)'

'groupBy' => 'YEAR(relaseDate)'

'groupBy' => 'field_releaseDate.year'

'groupBy' => 'releaseDate.year'

'group' => 'YEAR(field_relaseDate)'

'group' => 'YEAR(relaseDate)'

'group' => 'field_releaseDate.year'

'group' => 'releaseDate.year'

Any ideas if this is even possible? Also does anyone know if you can return a single array from Element API instead of a multi-level array? This output seems a bit inefficient:

'data' = [
    [2010],
    [2011],
    [2012],
    [2013],
    [2014],
    [2015],
    [2016],
    [2017],
    [2018],
    [2019],
]

I would much prefer:

'data' = [
    2011,
    2012,
    2013,
    2014,
    2015,
    2016,
    2017,
    2018,
    2019
]


texts: Get HTML of rendered template inside module

texts:
I'm getting started with plugin/module development. I want to get the template file, pass some variables to it, and get rendered HTML of that template into a string variable.

How do I do that?


texts:
I am looking for a plugin or simple method that can add some stats to the User Admin. We have a membership site running for a client and it would be good to add either a count to the sidebar User Groups filters (eg "Users (11)") or a dashboard widget of basic stats.

Has anyone added this already, or used something suitable?