texts:
I am having an issue with uploading assets to S3 from Craft.  So far I have taken the following steps:

Create permission policy and attached to group containing craft
user:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:ListAllMyBuckets"
            ],
            "Resource": "arn:aws:s3:::"
        },
        {
            "Effect": "Allow",
            "Action": [
                "s3:GetBucketLocation",
                "s3:ListBucket",
                "s3:PutObject",
                "s3:GetObject",
                "s3:DeleteObject",
                "s3:GetObjectAcl",
                "s3:PutObjectAcl"
            ],
            "Resource": [
                "arn:aws:s3:::<bucket_name>/*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "s3:GetBucketLocation",
                "s3:ListBucket"
            ],
            "Resource": [
                "arn:aws:s3:::<bucket_name>"
            ]
        }
    ] }

Create new asset source with type of Amazon S3 and input access and
secret key for craft user.  This allows me to select the available
bucket.
Save the asset source and go to the asset section to upload a file
to S3.  At this point the status bar fills up and the upload hangs
indefinitely.

Other notes:

These are very small images (<100KB)
I am able to bring images into Craft if I upload them directly to S3
and then update asset indexes in the setting.
I also noticed that the error logs print out the message:

  exception 'S3Exception' with message
  'S3::getObjectInfo([bucket_name], [file_name]): [52] Empty
  reply from server' in
  /Users/[user]/Sites/[project]/craft/app/lib/S3.php:777

I have also tried using the more broad 'AmazonS3FullAccess' policy
with the same results.

EDIT:
In continuing to explorer this issue I have found that a call is being made from the S3AssetSourceType file in the insertFileInFolder function to the S3 class getObjectInfo function.  It seems like this error is occurring because the code is trying to fetch information from amazon on an object that does not yet exist because this call occurs prior to the put object call.  I have yet to understand why the getObjectInfo is called within the insertFileInFolder call before a put object request is made to S3.

EDIT 2:
After more troubleshooting and testing this on a remote server it looks like the issue has to do with our company firewall not allowing receipt of the response object from the S3 request.  We had no issues uploading assets to S3 from the same codebase on a remote server and are now looking into a work-around with the firewall.


texts: Include public templates in a private template folder

texts:
I'm trying to include a public template from with a private one.
Files:

templates/_comments/comments.twig
templates/publicfolder/publicfile.twig

Within comments.twig:
{% include 'publicfolder/publicfile' %}

Pretty straightforward code, however when run I get: Twig Template Loading Error.
I can't find any documentation about this online besides the standard docs about privatized templating.
Is this a limitation of private templates?


texts: Can I accept file uploads using the Craft Guest Entries plugin? Using input type="file" doesn't seem to be working.


texts: How to check if a user's new email has been verified

texts:
Background
When the user setting Verify email addresses? is enabled, and the user's email is reset by a non-admin the address requires verification before being used  as explained here. This does not seem to show any sort of confirmation anywhere that the email reset has been made until the user verifies it. The account seems to stay live also, so checking pending users does not help.
Question
Is there an attribute or function I can call to find out if the email is verified?


texts: "Impossible to access an attribute on a NULL variable"

texts:
I am getting this error returned whilst in Debug mode:

  Template Error

  Impossible to access an attribute ("gatewayHandle") on a NULL variable ("")

Not sure why this is getting flagged up. It is a variable which is accessed through the Dukt Video plugin? Seems to work when not in debug mode, but I am getting slow initial response times when loading, not sure if this is related to that issue.

I have attached the relevant page code:

{# Video Link :: if entry is of video type #}

{% if entries.section == "Videos" %}

    {% set video = entries.video %}

    {% if video.gatewayHandle == 'youtube' %}
        <a
            data-target="flare"
            href="http://youtu.be/{{ video.id }}"
        >
    {% else %}
        <a
            data-target="flare"
            href="http://vimeo.com/{{ video.id }}"
        >
    {% endif %}

{% else %}

{# Entry link #}

<a href="{{ entries.url }}">

Any help would be appreciated.


texts: XMLHttpRequest Craft Commerce Cart Update Issues

texts:
When using XMLHttpRequest to update cart like the following, I get a 500 error for 'lineItems': {[lineitem]: {'qty': value}} (and also {[lineitem]: {'remove': true}}, any other submission works);

var url = document.querySelector('form#cart-form input[name="action"]').value;
var data = {
    'action': 'commerce/cart/update-cart',
    'lineItems': {[lineitem]: {'qty': value}}
}
data[csrfname] = csrfvalue;

atomic(url, {
    method: 'POST',
    data: data,
    headers: {
        "Content-Type": 'application/x-www-form-urlencoded',
        'X-Requested-With': 'XMLHttpRequest',
        'Accept': 'application/json'
    }
}).then(function(response) {
    console.log(response.data);
    console.log(response.xhr);
}).catch(function(error) {
    console.log(error.status);
    console.log(error.statusText);
});

(The code above uses atomic, which is just a small library to wrap XMLHttpRequest into a promise structure similar to using fetch).

The submitted data is (and looks) exactly the same as what I pass through JQuery Ajax, which works;

var url = document.querySelector('form#cart-form input[name="action"]').value;
var data = {
    'action': 'commerce/cart/update-cart',
    'lineItems': {[lineitem]: {'qty': value}}
}
data[csrfname] = csrfvalue;

$.ajax({
    type: "POST",
    dataType: 'json',
    url: '',
    data: data,
    success: function(response){
        console.log(response);
        }
    }
}).fail(function(error) {
    console.log('Error: ' + error);
});

I can't seem to figure out what the issue is, as the POST data being submitted looks EXACTLY the same. Changing the Content-Type to application/json doesn't work either. Anyone run into this issue?


texts: SEOmatic Errors in Debug - Can they be fixed?

texts:
SEOmatic throws up a lot of errors in the debug. Most of the errors seem to be with fields I haven't filled in as they are not required like Facebook App ID etc.

Is this an issue or do I just ignore? Disabling the plugin reduced the number of database requests to 50 instead of the 140 being shown and improved the speed slightly so just wondering if the errors are creating performance issues?


texts:
Can anyone recommend a hosting company that can handle running CraftCMS based out of Australia?

I've tried contacting http://www.digitalpacific.com.au/ but they came back to me with this:

"I have had this reviewed by our technicians to ensure we recommend the correct solution. I have been advised that due to the "crypt() with BLOWFISH_CRYPT" requirement, we are unable to host this on a Business hosting plan."


texts:
I'm trying to delete items through the frontend with ajax. It's working now but want to be sure if this is a safe method:

$(".delete-file").click(function(){
    var data = {
        entryId: $(this).attr("data-id"),
    };

    data[window.csrfTokenName] = window.csrfTokenValue; // Append CSRF Token

    $.ajax({
        context: this,
        type: "post",
        dataType: "json",
        data: data,
        url: "/actions/entries/deleteEntry",
        success: function(data, response){
            $(this).parents('.account-item').remove();
            console.log("success", response, data);
        }
    });
});


texts:
I'm building a site with loads of complex itineraries. Entries are in a channel for various reasons, but I want to split the data across subpages, with a URL structure like:

/itinerary/name-of-itinerary
/itinerary/name-of-itinerary/dates-prices
/itinerary/name-of-itinerary/gallery
/itinerary/name-of-itinerary/etc...

I want to route everything through my _views/itinerary/index template, and then just have a bunch of includes (dates-prices, gallery, etc...) in my index, something like:

{% include ( '_views/itinerary/' ~ craft.request.lastSegment ) %}

In my routes.php I've got:

'itinerary\/(?P<slug>[^\/]+)\/([^\/]+)'                 => '_views/itinerary',
'itinerary\/(?P<slug>[^\/]+)'                           => '_views/itinerary',

So everything is routing fine to _views/itinerary/index. Trouble is, I get a 404 for anything other than /itinerary/name-of-itinerary because Craft uses the last segment to resolve the entry, which is exactly what you'd want normally. But if the last segment is 'dates-prices' or 'gallery' I'm screwed.

Have I set this up right? Is there a more efficient and complete way? Any help much appreciated.


texts:
Trying to get the Postmaster plugin working for user activation emails, instead of the default Craft setup (had issue with Mandrill setup, Use SMTP authentication throws an error).

It doesn't seem that Postmaster disables the default Craft email setup, is there a way to do this within Craft?
Assuming (1), what is the correct {{ link }} variable as currently I'm seeing:

Template Error

Variable "link" does not exist

/Users/.../site/craft/templates/postmaster/user/activation.txt(5)

Hey {{user.friendlyName}},

Thanks for creating an account with the Postmaster {{siteName}}! To  activate your account, click the following link:

{{link}}

If you weren't expecting this email, just ignore it.

It doesn't seem there is currently a way to do this.


texts: Feed Me: Importing a relationship between elements

texts:
I want to import a bunch of films, which all have certain genres. The genres have already been set up as Categories in Craft, so each genre already has an Element ID (if that's relevant).

Here's a glance at my JSON feed...

{
    'title': "Epic Film",
    'genre': "action adventure"
},
{
    'title': "Sappy Love Story",
    'genre': "romance"
}

Unfortunately, that doesn't seem to work. I keep getting the following error:

  Genre cannot be blank.

How do I format data in a JSON field, to ensure that it's treated as a relationship between two elements?


texts: Is there a way to split the element-api.php file?

texts: Is there some way I can split the element-api.php file into separate files and import them all? It's getting quite long and unwieldy.


texts: How can I add custom validation rules to a new User registration?

texts: For example, how might we ensure that firstName is set.


texts: Render markdown as GFM (GitHub Flavored Markdown), therefore preserving line breaks?

texts:
In particular, I'm trying to render the text in markdown preserving the original line breaks, like in the GitHub Flavored Markdown specifications.

Using {{ something | md }} in a template the output contains a line break only if a line ends with two spaces, like in the original markdown implementation.

Some markdown processors (ie Blackfriday, written in Go) call this feature "hardLineBreak".


texts: Combine multi-tiered loop into a single query (via plugin)

texts:
I am very new to Craft so forgive me if I knacker how this is asked.

I have a set of IDs in an array.  I try sending that into a relatedTo statement (which yields a series of locations...see below code) and from that I loop through those locations, getting some subset descendents of those locations for display.

The issue is, this is a heavy load on the database and without caching takes forever to come back for rendering.   What I would like to do is essentially combine the queries for relatedCampIds, locationCats, and subCategories into a single query that's optimized.  I have tried using the BuildQuery example at https://github.com/tightenco/craft-build-query but I am like a fish out of water and just don't see how I can extend that to do what I'm looking to do.

    {# CREATE AN ARRAY OF THE CAMP IDS #}
{% entry = craft.entries.section('pages')}
{% set relatedCampsIds = [] %}
{% set relatedCampsIds = relatedCampsIds|merge(craft.entries.section('pages').descendantOf(entry).type('camp').limit(null).ids()) %}

{% set locationCats = craft.categories.relatedTo({ sourceElement: relatedCampsIds }).groupId(1).level(1).order('title').find() %}

{# get all camps related to the sport/sponsor and Area #}
{% for location in locationCats %}
    {# get all Cities of this Area where there are camps for the given sport/sponsor #}
    {% set subCategories = craft.categories.descendantOf(location).level(2).order('title').relatedTo({ sourceElement: relatedCampsIds}) %}
    {# loop over the subcategories #}
    {% for subCat in subCategories %}
        {# do some display stuff #}
    {% endfor %}
{% endfor %}

Help and understanding are appreciated.


texts: Order Confirmation Email in Craft Commerce

texts: I am having trouble with emails being sent by Commerce.  Checked my settings in Craft and sent test email.  Works.  Followed Commerce docs in setting up email.  Double checked, but still does not work.  My problem may be in my email file.  Not sure what to have here.  Anyone have an example of an email file I could look at to see what I need to do?


texts: Upload failed for filename. The path doesn't exist

texts:
I have an issue with uploading files. I got an error message:

  Upload failed for filename. Path directory structure
  "/public_html/assets/images /" set for this resource doesn't exist.

The Path should be good, because the public_html folder is directly in the root and the /assets/images folder is in it, permissions are 777.

It worked well on my local, it stopped working when I moved the site live. All pictures uploaded on my local are displaying on the live site...I just can't upload new


texts: How do you include an "Add element" button to the element selector modal

texts: In my plugin's field types I am extending the BaseRelationField.  How do you activate the "Add Element" button that shows in the Element Selector modal when the element is double clicked?


texts: Where can I download previous versions of Craft?

texts: Auto-updating is great and all, but sometimes you need to roll-back to a previous version or build of Craft for whatever reason.  Where can you download these?


texts: Choose custom email template for Contact Form plugin

texts:
I could've sworn I've read somewhere on here that the contact form plugin should use the same template as defined in the site's email settings, but it's not working for me.

Does anyone know if the Contact Form plugin supports this (and has it working)?


texts:
It's my first website using Craft.
I'm trying to figure out how to loop Matrix. I have created a field called bannerMatrix with a block type called banner that has 3 fields:

Image (assets)
Heading (plain text)
Subheading (plain text)

This is what I have so far:

{% for block in entry.bannerMatrix %}
    {% if block.type == "banner" %}

{{ block.heading }}

{{ block.subheading }}

    {% endif %}
{% endfor %}

Anything will be helpful.
Thanks!

UPDATE

@JamieWade, thanks a lot for the super fast answer!
Unfortunately, the code above still doesnt work for me :(

{% for block in entry.bannerMatrix %}

{{ block.heading }}

{{ block.subheading }}

{% endfor %}

I also tried this :

{% set image = block.image.first() %}
{% if image %}

{% endif %}

And I dont get anything as well :(

I wonder if my structure is correct. So I attached a screenshot.

@Alec, yes there is content in the entry(I attached a screenshot). Now I'm even more curious, what's missing here. I also added the path to subfolder in the Field Setting.


texts: How to write multiple operator condition in where statement of db query

texts:
$query = (new Query())
        ->select([])
        ->from(['{{%custom_table}}'])
        ->where(['<=','firstDate', now()])
        ->all();

In craft3, I want to add multiple conditions in the where statement of the above query so that it work as similar as following:

WHERE firstDate <= now() AND lastDate >= now() AND entryId=$entryId

Note: Please confirm that the function now() works in the query.


texts:
Is it possible to return an integer in it's text form?  I searched the Twig documentation and Stack Overflow and did not find a solution.

I could of course just set it up and create it based on the loop index,

{% if loop.index == '1' %}
{% set place = 'one' %}

but that breaks if the user creates entries above whatever number I set up to so it is not a real solution of any value. I am wondering if someone here might have a solution?

The return would be "one" in place of '1', "two" in place of '2', etc.

Thanks for any help!


texts: Charge plugin: custom actions on webhooks

texts:
I'm trying to integrate Charge with Craft Commerce.

Basically I need to

a) use Stripe to set up subscription for the amount based on what's in the cart (this seems to be possible out-of-the-box)

b) on successful charge - mark order as complete (I think I can use 'charge.onCharge' event here)

c) listen to webhooks - when the next recurring payment succeeds or fails, make change to order.

Is there a way to write custom action for (c) without hacking into Charge core?

I see there is Charge_Actions service fireing some events, but how do I reference/listen to those actions in a custom plugin that I create?


texts: How can I set an auto respond email based on drop-down?

texts:
We have a freeform form on a site's contact page. In that form there's a dynamic recipient drop-down field for Subject which emails a different person on the team depending on the subject (functionality built into freeform). We also need to send a auto response to the sender but only if they select a specific option for subject. Any ideas how to go about this? Example:

"Interested in working together" - emails person 1
"Business proposal" - emails person 2
"Careers enquiry" - emails person 1 AND sends an email to the person who submitted the form


texts: How to attach a plugin license to a CMS license?

texts: I have a Craft license that is not attached to a Craft CMS license and cannot figure out where/how to attach it to one in my Craft ID account so that I can use it in a Craft CMS installation.


texts: When using .limit on matrix blocks they don't show in live preview

texts:
I have a Matrix field setup and working perfectly except for one problem.

In my template I'm using .limit to only pull the first two items from the matrix field (I can't use max in the field settings as I'm using the same field on other pages that allow more than two blocks to show).

Using the following line to pull the Matrix blocks works fine in the live preview.

{% for serviceBlock in entry.serviceBlocks %}

But adding the limit stops Craft showing the blocks in the live preview. Though the rest of the template loads and updates perfectly.

{% for serviceBlock in entry.serviceBlocks.limit(2) %}

I'm not getting any errors, and if I save the page and reload the live preview it will render the blocks perfectly, but not update the content live.

Has anyone encountered this problem, or have an idea that might help?


texts: PHP warning with composer on MacOS High Sierra: Failed to open stream

texts:
We have multiple people working on a craft site using Vagrant and Virtual Box for our local server.

I am running MacOS Sierra, and everything works as expected. A couple of our other developers have updated to run High Sierra, and when they would pull down the git repo for the project this error shows up:

  include(/vagrant/app/craft/app/vendor/composer/../twig/twig/lib/Twig/Source.php): failed to open stream: No such file or directory

This happens when Vagrant is up and running successfully, gulp is watching, and all the user is trying to do is connect to localhost:3000 through their browser. These computers had successfully worked on the project in the past before updating their OS.

We tried doing a fresh pull down of the repo on a computer that had never worked on the project (but also using High Sierra) and we get the same exact error. So the only thing we know that is different between my computer (which works as expected) and the others is that mine is running Sierra and the others are running High Sierra.

We've tried searching online for this issue, but haven't found anybody posting similar enough problems. Also, I am posting this here since it is a Craft CMS project, so if I should switch this to a different stack exchange, let me know. Thank you!

SETUP INFO:

config.vm.box = "ubuntu/trusty32"
config.vm.box_url = "https://vagrantcloud.com/ubuntu/boxes/trusty32"

Tools:
Vagrant, Virtual Box, Gulp, rsync installed through homebrew

Let me know if there is anything specific about our setup that you'll need to see to be more helpful.


texts:
Solspace Calendar is a great calendar add-on, and the templates are great - as long as you are using Bootstrap.  However, we mainly use Zurb Foundation.

I'm just staring to dive in, but I'm curious if anyone has reconfigured for Foundation?


texts: List child categories which have entries based on the current categories

texts:
I am looking to output the child categories of a parent category.
I only need to show the categories which have entries related to them.

I have done this to show all categories using

{% set entryIds = craft.entries.section('stories').ids() %}
{% set categories = craft.categories.relatedTo({ sourceElement: entryIds }).groupId(2).orderBy('title').all() %}

What is the best way to do this for subcategories.


texts: Create Solspace Calendar Event on Commerce onOrderComplete

texts:
I'd like to create a Solspace Calendar Event on Commerce onOrderComplete. I've done this with Charge where on Charge Success an event was created however I know that I did that in a less than ideal way so hopefully the answer to this allows me to both achieve what this question is asking as well as fix my previous plugin (that works but just seems less than ideal).

I'd need to pass some of the fields from the Order Fields such as the Start Date, End Date, Products Purchased.

I know i need to create a plugin for this, i'm just not quite sure how to call the Solspace Calendar plugin onOrderComplete and send it the appropriate data to create said event. Any help (with examples if possible) would be greatly appreciated.

To clarify: I am not looking for someone to write a plugin for me. I am simply looking to be put on the right track in terms of connecting to Solspace Calendar and sending it the appropriate data on completion of a commerce order.  I can write the code myself once pointed in the right direction.


texts: Query to find users who are in more than one user group

texts:
I'm working with a site that has a few thousand user accounts. With the exception of core accounts with CP access, each user account exists for the purpose of access to event URLs which eventually expire.
But, although the vast majority of users belong to only one event-specific user group, a select few belong to more than one.
For the purposes of housekeeping, I'd like to be able to easily find such user accounts, so I can exclude them from a periodic account deletion process.
What query could serve this purpose for a report of multi-user-group users?


texts: Is it possible to change the title of "Quick Post" dashboard widgets?

texts: For this particular build the client will frequently be creating 3 similar, but unique, types of content all housed in the same section which differ by a Content Type. When creating "quick post" widgets for the dashboard, each widget is currently given the same name despite the corresponding Entry Type. I don't necessarily need granular control over the title, but a way to provide additional context to the administrators would be nice.


texts:
My site is working fine with dukt videos on local and staging but I am getting an error on any page with a dukt video field. Error is on the front end and the dashboard.

Internal Server Error
Argument 1 passed to Composer\Autoload\ClassLoader::addClassMap() must be of the type array, integer given, called in /homepages/15/d322782150/htdocs/nailcote-craft/craft/plugins/videos/vendor/composer/autoload_real.php on line 38 and defined

I've emailed support directly but in the meantime if anyone has come across this I would be glad of the help.


texts: Asset upload fails with progress bar at full, but images in tempuploads folder

texts:
I can’t for the life of me get images to upload. Neither on my local server or on the live server. The progress bar goes to the end, and then … nothing. From what I can see online, I’m not the only one, but I can’t find any remedy.

I’ve gotten Imagemagick installed (locally, at least), but no change (GD is installed in both environments)
I’ve tried several types of image formats (seems some people have problems with JPEG)
I’ve tried relative asset paths and set through environmental variables

Nothing seems to work.

In the error logs, the only error I can find is:
Undefined index: singleUploadLocationSource ([correct path]/craft/app/models/AssetFileModel.php:171)

I just realised that the files do get uploaded to the storage/runtime/assets/tempUploads folder. So seems it fails to completing the copy to the final assets folder. Permissions should be correct, from what I can understand (I'm no expert on these things).

Does anyone have any ideas what can be the cause? I’ve been scratching my head here for weeks, and it still itches like crazy.


texts: SEOmatic - Set the SEO tags based off of a category?

texts:
I was wondering if there was a way I could set the SEO tags based off of a category?

eg. If a entry is in the "Marketing" category, use marketing Meta data?

Any help would be greatly appreciated.

Thanks in advance!


texts:
I have a field defined in my plugin called video with AttributeType::Mixed where I store a video_id and a title of a video. I need to look up the entry by the video_id (I can't do it via the the entry ID).

$entry = craft()->elements->getCriteria(ElementType::Entry);
$entry->section = 'video';
$entry->search('video: video_id=' . $videoID);
return $entry->first();

This works, but there has to be a better solution?


texts:
I have two sections:
games
publishers

For example, a games entry title would be "Mario Brothers" and a publishers entry title would be "Nintendo"

On the entry page for Nintendo, I want to display all games (entries) they published.

The "_entry,html" page for publishers right now only has the following code:

{% extends "_layout" %}

{% block content %}

{{ entry.title }}

        {{ entry.body }}

{% endblock %}

So I know I need to add it after:

In the games section, I have a field called "GamePublishers" set to type Entries. So I assign the publisher of a game via the admin cp. Wasn't sure if I need to also setup a field type entries in GamePublishers to reference to Games section. (If that makes sense)

Thanks


texts:
Is it possible to include the entry position (Structure) via the Entry Type Title Format?

This is the current format:

published in {postDate|date('F')} {postDate|date('Y')}

which renders: published-in-april-2018

This is what we need it to render:

number-3-published-in-april-2018

I could create an actual Number field called “numberTitle”, attach it to the Entry Type, and set the Entry Type’s title to be dynamically generated using the template “{numberTitle}”, but why does this need to be done manually?
You would think that the entries in a Section have a natural order in sequence or maybe they don't?

If the EntryVersion Model cannot deliver could Twig offer a solution?


texts: Craft 2.6 Asset Upload 500 Error (on Heroku with Amazon S3)

texts:
I just upgraded a fully functional Craft website to Craft 2.6. The site is hosted on Heroku with assets uploading to S3. So all of that has been working really well for about 10 months. Now I can't upload any more assets. When I choose a file from my computer, the upload hangs.

I get a console error:

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

https://www.example.com/index.php?p=admin/actions/assets/uploadFile Failed to load resource: the server responded with a status of 500 (Internal Server Error)

Here is the response body of the 500 error:

PHP Error [500]

Trying to get property of non-object (/app/craft/app/services/AssetsService.php:707)

#0 /app/craft/app/etc/errors/ErrorHandler.php(184): Craft\ErrorHandler->handleError()
#1 /app/craft/app/framework/base/CErrorHandler.php(133): Craft\ErrorHandler->handleError()
#2 /app/craft/app/framework/base/CApplication.php(834): Craft\ErrorHandler->handle()
#3 /app/craft/app/etc/web/WebApp.php(688): Craft\WebApp->handleError()
#4 /app/craft/app/services/AssetsService.php(707): Craft\WebApp->handleError()
#5 /app/craft/app/controllers/AssetsController.php(52): Craft\AssetsService->uploadFile()
#6 /app/craft/app/framework/web/actions/CInlineAction.php(49): Craft\AssetsController->actionUploadFile()
#7 /app/craft/app/framework/web/CController.php(308): CInlineAction->runWithParams()
#8 /app/craft/app/framework/web/CController.php(286): Craft\AssetsController->runAction()
#9 /app/craft/app/framework/web/CController.php(265): Craft\AssetsController->runActionWithFilters()
#10 /app/craft/app/framework/web/CWebApplication.php(282): Craft\AssetsController->run()
#11 /app/craft/app/etc/web/WebApp.php(818): Craft\WebApp->runController()
#12 /app/craft/app/etc/web/WebApp.php(288): Craft\WebApp->_processActionRequest()
#13 /app/craft/app/framework/base/CApplication.php(185): Craft\WebApp->processRequest()
#14 /app/craft/app/index.php(62): Craft\WebApp->run()
#15 /app/public/index.php(19): require_once()

Any ideas? This happens when I try to upload an asset directly in the Assets section of Craft as well as uploading a new image to an Entry.

Thanks.


texts:
I have a localization problem where the routes are not showing up.
I have a tried a routes file with the following code.

return array(
    'menu' => '_menu'
)

And its working on the main language but when i put
website.com/ar/menu its giving me 404 as if the route doesnt exist.

I have a subfolder with the proper index.php and .htaccess

How can i fix this issue in the right way?


texts: Plugins with element criteria selection does not work for empty or zero values

texts:
I made a plugin which count the number of users per groups defined by the field accent which is a text field and can be empty or contain numbers from 0 to 12.

public function actionCountUsers() {

    // Delete all the entry caches
    craft()->templateCache->deleteCachesByElementType('User');

    // Now find the entry IDs
    $criteria = craft()->elements->getCriteria('User', array('group' => 'unepMembers', 'limit' => null, 'status' => null, 'localeEnabled' => null));
    $criteria->group = 'unepMembers';
    $criteria->limit = null;
    $criteria->status = null;
    $criteria->localeEnabled = null;

    //
    $totalEntries = $criteria->total();
    UnepPlugin::log($totalEntries.' USERS (no criteria)', LogLevel::Warning);

    //
    $criteria->accent = '';
    $totalEntries = $criteria->total();
    UnepPlugin::log($totalEntries.' USERS with empty accent', LogLevel::Warning);

    //
    $totalUsers = 0;
    for ($i = 0; $i <= 15; $i++) {
        $criteria->accent = $i;
        $totalEntries = $criteria->total();
        MigPlugin::log($totalEntries.' USERS with accent :'.$criteria->accent, LogLevel::Warning);

        $totalUsers = $totalUsers + $totalEntries;
    }
    MigPlugin::log($totalUsers.' USERS with accents', LogLevel::Warning);

}

As you can see the result here below there is a problem with a criteria values empty or 0 on the accent field: they just do not work and count the total number of users.

***********************
2015/10/11 07:09:48 [warning] [plugin] 3109 USERS (no criteria)
2015/10/11 07:09:48 [warning] [plugin] 3109 USERS with empty accent
2015/10/11 07:14:01 [warning] [plugin] 3109 USERS with accent :0
2015/10/11 07:09:48 [warning] [plugin] 1849 USERS with accent :1
2015/10/11 07:09:48 [warning] [plugin] 501 USERS with accent :2
2015/10/11 07:09:48 [warning] [plugin] 0 USERS with accent :3
2015/10/11 07:09:48 [warning] [plugin] 72 USERS with accent :4
2015/10/11 07:09:49 [warning] [plugin] 8 USERS with accent :5
2015/10/11 07:09:49 [warning] [plugin] 1 USERS with accent :6
2015/10/11 07:09:49 [warning] [plugin] 0 USERS with accent :7
2015/10/11 07:09:49 [warning] [plugin] 4 USERS with accent :8
2015/10/11 07:09:49 [warning] [plugin] 81 USERS with accent :9
2015/10/11 07:09:49 [warning] [plugin] 232 USERS with accent :10
2015/10/11 07:09:49 [warning] [plugin] 246 USERS with accent :11
2015/10/11 07:09:49 [warning] [plugin] 115 USERS with accent :12
2015/10/11 07:09:49 [warning] [plugin] 0 USERS with accent :13
2015/10/11 07:09:49 [warning] [plugin] 0 USERS with accent :14
2015/10/11 07:09:49 [warning] [plugin] 0 USERS with accent :15
2015/10/11 07:09:49 [warning] [plugin] 3109 USERS with accents

Craft bug or did I miss something in my code?


texts:
I have a large website that various users need to upload important documents (assets) to frequently.  I need to have the Craft asset cache clear every time a new asset is uploaded.  The other option I've been working through is setting a server side task to clear the cache through the command line every day at 3am.
Is there a way to set the Craft asset cache to clear every time a new asset is uploaded?


texts:
I'm new to php development, so I'm probably doing something silly...

I have setup Craft running in a Vagrant VM on Windows 8. I am using XDebug and Eclipse as my IDE. It all works beautifully! However I cannot debug any of my plugin code. I can step into the Craft code but it never breaks on any plugin actions. I suspect its something to do with the way the Craft code is calling the actions, it looks like it is using some sort of reflection to call the methods of the plugin class. Can anyone help? Is there a way to debug plugin code? Or perhaps a better IDE if it is Eclipse that has this limitation?


texts: Craft Commerce 2 — Remove Line Item (and other actions)

texts:
Knowing that all other actions besides update-cart has been deprecated I'm curious what needs to be passed with the action to remove a line item from the cart using a button as opposed to check a checkbox > update cart (essentially removing a click for the user).
The same would apply for +/- buttons/inputs for adding/removing from quantity.

I see in the example templates there's a checkbox input with name="lineItems[{{ item.id }}][remove]". Is it as simple as changing the input to a submit (or button submit) using the same name tag contents? Would this then also carry over to be posted via ajax in the same way as an update-cart action?

That's a long question. Trying to wrap my head around the changes as I'm just getting into Craft 3 and Commerce 2...


texts: How do I select a specific product variant by element/field/entry?

texts:
Excuse my new-ness, but I'm having an issue with product variants.

Scenario

I have a product with multiple variants (up to 30 in fact). Based on the URL, I want to choose a specific variant so that I can display fields from that variant on my product detail page. I also want a 'default variant' if there is no variant specified in the URL.

In my example, the variant should be selected by a custom field in that variant colour whose value match the 4th URL segment.

Code

{# Grab colour segment #}
{% set colourSlug = craft.request.getSegment(4) %}

{# If there is no colour, we grab the first variant colour #}
    {% if not colourSlug %}
        {# Grab first product variant #}
        {% set dressColour = product.defaultVariant %}
    {% else %}
        {# Set dress colour #}
        ??{% set dressColour = product.variants.find(colour.colourSlug) %}??
    {% endif %}


texts:
I am building a site where all the content (and users) are being managed using the front end. The site owner needs to invite customers to the site but would like to control the time when that customer receives his activation mail. Is that possible without having access to the control panel?

So ideal journey would be:

The site owner creates new customer via the front end (no activation
mail sent)
The site owner does stuff on the site (preparing content
for the customer)
The site owner pushes a button on the customer’s
profile which fires off the activation mail to the customer
Profit

I could just have my client send out a password reset mail (?) but that seems a bit hack-ish and raises security concerns since that form needs to be publicly available.

There are no methods available which are giving me access to the verification code so that route wasn’t successful either. Is there a way to grab that code and serve it to the template? That would do it for me.

Is there another way to make that happen? It might actually be easy to solve. I would be grateful if someone could push me in the right direction.


texts:
With a bit of looking around i've got the following code on my News landing page:

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

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

{{ year }}

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

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

        {% endfor %}

  {% endfor %}

Using
{{ month }}&nbsp;({{ entries|length }})
  I get the desired result (visually), see attached image.  If I use
{{ entry.getLink() }}
 I get the result shown on the right of the attached image.

In both instances I only get a link to the first segment (also shown in the attached image).

What I would like to do is have the Months link to a page that lists just the articles from that month (I don't need the year to link).

I assume I need to add a dynamic link into the href but how and what?

Many thanks in advance.

Martin


texts: Smart Map with linked SVG icons for markers

texts:
I have a smart map where I'm trying to use linked SVG files for the marker icons. In Safari, the files load at actual size, which in this case is fine, but in Chrome and Edge, they are scaled up, and in Firefox and IE, they don't show up at all.

I tried setting a size using marker options, but it looks like that doesn't support google.maps.MarkerLabel properties:

{% set options = {
    markerOptions: {
        scaledSize: 'new google.maps.Size(50,50)',
    },
} %}

If I replace the SVG icon with PNGs, they work fine in all browsers.
Is there a different way to specify the icon size/path for SVGs?


texts:
Not so much a technical question as a how-to/best practice one, here goes:

I'm building out a site that has 3 content-types (channels), a structure and a bunch of singles.

The site has 35 locales.

The pages & singles consist of normal translated content.

But the channels should be separate in each locale. Meaning, for example, that news items from en_UK should not be translatable to jp_JA. Content will be managed by a different user/group per locale and they should only see content published in their locale, not translatable entries from others.

The "best" solution we've come up with so far is to create a channel per locale. But that adds up quickly (3 x 35...), not to mention managing fields and permissions for each channel separately.

Is there a way to simplify this or are we going to have to bite the bullet?

Craft 3 and multisite sounds like a dream for this but sadly we can't wait for that


texts: What would it take to make Craft composer based?

texts: Since there is a free edition and the plugin architecture looks relatively simple, I'd like to know if anyone has an idea of how this could work. Are there any plans for it?


texts: Using Craft with CloudFront, and handling invalidation

texts:
I'm trying to get static assets set up to be served by CloudFront. I know how to get the S3 bucket working, and have CloudFront serving from that bucket, but what I can't wrap my head around is how to handle the invalidation. In non-Craft instances I know about hashing to trigger the invalidation, but not sure how to do that in Craft.

Specifically, if an editor uploads a photo named "photo.jpg", and then publishes, and decides to make a change and uploads the revised photo with the same name, how does CloudFront know that it has changed since the editors don't know about content hashing?

Hopefully this makes sense. While not at all new to Craft, I'm very new to running it with performance in mind and even newer to using a CDN. Any help is greatly appreciated!


texts: Add product to cart using checkbox and AJAX

texts:
As part of my checkout process, I have a list of five optional, add-on services shown as checkbox inputs. The list resides on a standalone page and each service can either be included in the purchase or not (i.e. quantity 1 or 0).

I've considered using the Multi-Add plugin, but I would like any checked services to remain in the cart if the user goes "Back" instead of submitting.

How do I add these services to the cart with AJAX when clicked, and remove when unclicked? I'm very new to Commerce so any and all references, suggestions, and hand-holding here is appreciated.


texts:
I'm about to start building out a site that requires a booking system to be setup within it. The site owner should be able to set availability (days and times with time-frames) and allow the visitors to book/reserve available services within the available time-frames and make a payment.

Any suggestions on how one might go about this? I know the request is pretty vague, just looking for some broad strokes to help me kick off in the right direction.


texts: How to support chained Element queries with Twig tags

texts:
The craft variable allows you to chain queries for your Elements. For example, you can query the first Entry in a section with either of the following syntaxes:

{% set entry = craft.entries({ section: 'news' }).one() %}
{% set entry = craft.entries.section('news').one() %}

How do we support both of these syntaxes in a Custom Element type?

The Craft Variable defines the entries tag like so:

public function entries(array $criteria = []): EntryQuery
{
  $query = Entry::find();
  Craft::configure($query, $criteria);

  return $query;
}

And, within the EntryQuery class, a public section method is defined:

public function section($value)
{
  if ($value instanceof Section) {
    $this->structureId = ($value->structureId ?: false);
    $this->sectionId = $value->id;
  } else if ($value !== null) {
    $this->sectionId = (new Query())
      ->select(['id'])
      ->from([Table::SECTIONS])
      ->where(Db::parseParam('handle', $value))
      ->column();
  } else {
    $this->sectionId = null;
  }

  return $this;
}

And there appears to be a __set method on the EntryQuery that also references the section method:

public function __set($name, $value)
{
  switch ($name) {
    case 'section':
      $this->section($value);
      break;
    case 'type':
      $this->type($value);
      break;
    case 'authorGroup':
      $this->authorGroup($value);
      break;
    default:
      parent::__set($name, $value);
  }
}

I've experimented with all of those and still only seem to be able to support the first syntax:

{% set entry = craft.entries({ section: 'news' }).one() %}

But can't seem to find a way to support the second syntax:

{% set entry = craft.entries.section('news').one() %}

What am I overlooking? What does a custom Element Type need to add to support the chained syntax for an Element Query via a Twig variable?


texts: live and pending entries together not working

texts:
Craft 3.0.37

I have the following code which I expect to output all entries (live and pending) but it doesn't

  {% for entry in craft.entries.section('podcast').status('live','pending').relatedTo(season).orderBy('postDate', 'asc').all() %}

{{ entry.episodeNumber }}  {{ entry.title }}

  {% endfor %}

If I change the status to only pending it outputs pending entries, if live, outputs live. However it will not output both pending and live.

Please advise.


texts: Responsive background images in carousel

texts:
I have a homepage carousel using http://flickity.metafizzy.co/ and the images are set as background images and lazyload.

What I need to do is to make them into responsive images, so that different images are served up for mobile, tablet and retina screens. But am struggling on how to do it in the code. Can anyone help?

{% if entry.carouselImage1.first() %}

{% endif %}

{% if entry.carouselImage2.first() %}

{% endif %}

{% if entry.carouselImage3.first() %}

{% endif %}


texts: Craft updater still spinning after at least half an hour--no error message

texts: I hadn't updated site in a while now. Checked Craft's control panel and something like 12 updates were available and i clicked update. "Updating Composer dependencies (this may take a minute)…" has been on display for over half an hour, maybe an hour, and the activity spinner just keeps spinning. No error report or any feedback. I'm reluctant to stop the process as the site is currently unavailable due to this situation.


texts: Is it possible to get a users most popular categories based on Craft products?

texts: So i wanna show the user the product categories that is most popular for that spesific user. Is that possible?


texts: Running garbage collection with commerce errors

texts:
Anybody know how to resolve the following when using Craft Commerce?
Running the command craft gc/run throws an error.
Next yii\db\Exception: SQLSTATE[HY000]: General error: 1093 You can't specify target table 'commerce_customers' for update in FROM clause
The SQL being executed was: DELETE FROM `commerce_customers` WHERE `id` IN (SELECT `customers`.`id` AS `id`
FROM `commerce_customers` `customers`
LEFT JOIN `commerce_orders` `orders` ON `customers`.`id` = `orders`.`customerId`
WHERE (`orders`.`customerId` IS NULL) AND (`customers`.`userId` IS NULL)) in /vendor/yiisoft/yii2/db/Schema.php:677
Stack trace:
#0 /vendor/yiisoft/yii2/db/Command.php(1298): yii\db\Schema->convertException(Object(PDOException), 'DELETE FROM `co...')
#1 /vendor/yiisoft/yii2/db/Command.php(1093): yii\db\Command->internalExecute('DELETE FROM `co...')
#2 /vendor/craftcms/commerce/src/services/Customers.php(383): yii\db\Command->execute()
#3 /vendor/craftcms/commerce/src/Plugin.php(670): craft\commerce\services\Customers->purgeOrphanedCustomers()
#4 [internal function]: craft\commerce\Plugin->craft\commerce\{closure}(Object(yii\base\Event))
#5 /vendor/yiisoft/yii2/base/Event.php(312): call_user_func(Object(Closure), Object(yii\base\Event))
#6 /vendor/yiisoft/yii2/base/Component.php(636): yii\base\Event::trigger('craft\\services\\...', 'run', Object(yii\base\Event))
#7 /vendor/craftcms/cms/src/services/Gc.php(74): yii\base\Component->trigger('run')
#8 /vendor/craftcms/cms/src/console/controllers/GcController.php(56): craft\services\Gc->run(true)
#9 [internal function]: craft\console\controllers\GcController->actionRun()
#10 /vendor/yiisoft/yii2/base/InlineAction.php(57): call_user_func_array(Array, Array)
#11 /vendor/yiisoft/yii2/base/Controller.php(180): yii\base\InlineAction->runWithParams(Array)
#12 /vendor/yiisoft/yii2/console/Controller.php(179): yii\base\Controller->runAction('run', Array)
#13 /vendor/craftcms/cms/src/console/Controller.php(188): yii\console\Controller->runAction('run', Array)
#14 /vendor/yiisoft/yii2/base/Module.php(528): craft\console\Controller->runAction('run', Array)
#15 /vendor/yiisoft/yii2/console/Application.php(180): yii\base\Module->runAction('gc/run', Array)
#16 /vendor/craftcms/cms/src/console/Application.php(88): yii\console\Application->runAction('gc/run', Array)
#17 /vendor/yiisoft/yii2/console/Application.php(147): craft\console\Application->runAction('gc/run', Array)
#18 /vendor/yiisoft/yii2/base/Application.php(386): yii\console\Application->handleRequest(Object(craft\console\Request))
#19 /craft(23): yii\base\Application->run()
#20 {main}
Additional Information:
Array
(
    [0] => HY000
    [1] => 1093
    [2] => You can't specify target table 'commerce_customers' for update in FROM clause


texts: Set Up Route to Template - then variable Entry is undefined

texts:
I've got a blog listing channel set up where I'm trying to filter entries listed by the entries field blogAuthors based on url segment.

/articles-and-excerpts/ loads the blog fine

added a route

but when I go to a page like this /articles-and-excperts/author/john-doe I see errors until I add this to the template

{% if entry is not defined %}
    {% set entry = craft.entries.section('blogListing').one() %}
{% endif %}

Then it works correctly. Why doesn't Craft recognize that this is the blogListing channel?

Also even though this works and displays the content SEOmatic doesn't recognize it now either.

Ultimately I need the following to load on this template:

/articles-and-excerpts/
/articles-and-excerpts/author/author.slug
/articles-and-excerpts/category/category.slug
/articles-and-excerpts/category/category.slug/author/author.slug

Currently I have categories using a separate template but haven't attempted to add in the author filtering.

Is there a better approach to this? I had started trying to combine url segments and a query string, but got stuck there as well Filtering entries by category and author channel


texts: Get Entries with a specified. Custom FieldType

texts:
I have created a Custom FieldType with AttributeType::Mixed The field actually saves the a Custom Model I created. I'm trying to retrieve all the entries that have my custom model as the field. I'm trying to do this:

-
$criteria = craft()->elements->getCriteria(ElementType::Entry);
// testOrPanel is the name of my custom fieldtype.
$criteria->testOrPanel = ModelHelper::packageAttributeValue($test);
$entry = $criteria->first();
-

I know for a fact that the entry exists and has that value. and I have logged the ModelHelper result and it is exactly what the field has on the db, but it is not working.
it is resulting in blank.


texts:
I have a rich text field which contains:

This is what is left when you delete all content of a redactor field.
This can't be deleted without the HTML view of Redactor.

Is it possible to write a conditional that checks for an empty field ignoring HTML markup?

{% if entry.poorText is not empty %}
   {{ entry.poorText }}
{% endif %}

Does not work in this case.


texts: How do I query for entries, based on a value inside a table?

texts:
I'm trying to query up some entries based on a value inside an editable table.

Here's two pictures on how it's set up:
http://i.imgur.com/lJFcO1C.png
http://i.imgur.com/Eqxg7Uh.png

My current template (stripped) looks like this:

{% set courses = craft.entries({
    section: 'course',
    search: 'participants:31'
}) %}

        Upcomming courses

    {% for course in courses %}
        {{course.title}}

    {% endfor %}

I've tried a couple of other parameters to the query, such as

participants['col4']: '31'

and

participants: '["col4"]:31'

but almost no dice. I get a result, but it matches with all the other values as well. I only want it to match with "userID" column, aka col4.

For example, I get the same results if I try '1' instead of '31'.


texts: onSaveUser event - cannot redirect or access errors

texts:
I've written a plugin which intercepts the user.onSaveUser event.

However if the save fails the user is still redirected to the page specified in the 'redirect' parameter/field of the form. How do I redirect them back to the form with errors and then access those errors?

I've tried craft()->urlManager->setRouteVariables() but still being returned to the page/URL specified in the original form. If I remove the redirect field from the front-end form I am redirected to the form on error but cannot access the errors sent in craft()->urlManager->setRouteVariables().

Any thoughts on how to specify the redirect destination depending on success/fail and also how to send/access the offending error messages in my original template?


texts: How to create a CMS editable channel section index page?

texts:
If I have a section called 'blog', and its handle is 'blog', and it's a Channel, all of the entries appear under http://mysite.com/blog/{slug} - which is great; but how would I create a page at mysite.dev/blog which is editable in the CMS, with its own fields? I'd like to do this so I can have a CMS editable introduction to the blog section, rather than having to hard-code an introduction into the template that would then list the latest X blog posts.

I can't create a Single called 'blog' because that handle is already taken by the Section itself, so how would I go about this? I'd considered using a Global, but that seems a bit off (it's not global content, it's a singular page's content) not to mention repetative/non-DRY if I had multiple sections to do similar things with, or if there were multiple fields I wanted applying on the overview/landing page. Is there a neater solution?


texts: Craft 3 plugin backwards compatibility and maintenance for 2.x

texts:
I've been updating a number of my plugins for Craft 3 lately; part of that process has been to create entirely separate repositories/projects to accommodate the differences between Craft 2.x & 3.

I'm curious to know how other developers maintain two plugins where the core functionality is essentially the same code.

Maybe having both plugins refer to the same dependancies via composer? (But still have two repos/projects)

Perhaps keep everything on one repo/project and simply have two versions of the plugin in there. Although that may conflict with Craft 3's plugin store; as half the files int he repo are redundant.

I'd love to know how others are dealing with their plugin upgrades and if there are any 'official' practices to resolve this.


texts: Impersonating a User from a plugin, with specific page redirect

texts:
Part of a plugin I am writing needs to handle impersonating a user, in the same way that Craft offers the built in "Log in as X" for admins in the back end.

I have that working by essentially copying the /app/controllers/UsersController actionImpersonate() function into my plugin.

However, when the action is run, the newly logged in user is always being redirected to the homepage - which makes sense as it's the default page that front-end logins go to. But, I want to override it. I want my plugin to take them to a page I dynamically set. I can't seem to get it to happen. Here's my code:

public function actionMyAction()
{

    // basic security precautions
    $this->requirePostRequest();
    $this->requireAdmin();

    ... some stuff not relevant to the question ...

    // get the user we want to impersonate
    $originalUserId = craft()->userSession->getId();
    $orderOwnerId = $order->customer->user->id;

    // impersonate the user
    craft()->httpSession->add(UserSessionService::USER_IMPERSONATE_KEY, $originalUserId);

    if (craft()->userSession->loginByUserId($orderOwnerId))
    {
        craft()->userSession->setNotice(Craft::t('Logged in.'));
        // $this->_handleSuccessfulLogin(true);
        $this->redirectToPostedUrl();
    }
    else
    {
        craft()->httpSession->remove(UserSessionService::USER_IMPERSONATE_KEY);
        craft()->userSession->setError(Craft::t('There was a problem impersonating this user.'));
        Craft::log(craft()->userSession->getUser()->username.' tried to impersonate userId: '.$userId.' but something went wrong.', LogLevel::Error);
        }
    }
}

I'm expecting that to redirect the newly logged in user to the page that the form was posted from - but it doesn't. Also, and I don't know if it's related, if I uncomment the $this->_handleSuccessfulLogin(true); line I get an error. That line is not commented out in the original function, and looking at the Craft docs to try and learn what it does, it says the function is deprecated ( https://craftcms.com/classreference/services/UsersService#handleSuccessfulLogin-detail )


texts:
What is the value in using a hidden actionInput vs an action attribute on a form?
<form method="post">
    {{ actionInput('path/to/controller-action') }}
</form>

vs
<form method="post" action="/actions/path/to/controller-action">
</form>

I understand you get the actionTrigger automatically added, but you could use the actionUrl function to generate that as well.


texts:
I saw a potentially similar question, but I'm wondering if mine is simpler.

I need to search for entries based on a match of a Multi-Select field. So, say if a user has a Tier of "TB" and an entry has a Muli-Select value of the options TB,B,P then the entry should be found. Likewise for an entry with the options G,A,P should not be found.

Here's my query at the moment

{% set query = 'eventRegion::"' ~ currentUser.userPabRegion ~ '" eventTier:"' ~ currentUser.userPabTier ~ '"' %}

{% paginate craft.entries.search( query ).sectionId( module.eventsModuleChannel ) as events %}


texts: How to re-generate titles for all entries in a section?

texts: Having changed the format of a Dynamic Entry Title, how do I get Craft to re-generate them all? I thought a background task would take care of it but nothing happens.


texts: How do I check if a product has stock in any of it's variants?

texts:
Basically, I'm trying to show "Out of stock" and disable a button for when none of the variants have stock, and unlimited stock is unchecked.

I've tried this, which isn't working:

{% if product.variants.stock <= 0 and product.variants.unlimitedStock == false %}
    {{ "Out of stock"|t }}
{% else %}
    {{ "Add to cart"|t }}
{% endif %}


texts: Error on homepage of local server no changes made since last working?

texts:
I have just gone back to a site I am working on locally to continue working on it. 2 days ago it was working fine and I have made no changes. I now have this error when I load the homepage.

unserialize(): Error at offset 0 of 24 bytes

C:\Websites\website\craft\app\framework\caching\CCache.php(108)

Anyone have any idea why this has happened and how to fix it as I say nothing had changed with the files or with the MAMP install.

Cheers


texts: Allowed memory size of 1610612736 bytes exhausted when updating via CLI on OS X

texts:
This one has been bugging me for months.

My development environment is running on MAMP on OS X. It's worked absolutely find for ages but for no reason that I can identify all my Craft sites now throw the following error when trying to apply updates via the craft cli:

./craft update craft

[snip]

Performing update with Composer ... PHP Fatal Error 'yii\base\ErrorException' with message 'Allowed memory size of 1610612736 bytes exhausted (tried to allocate 4096 bytes)'

Doesn't matter how much memory I give php, it will always eat it all up, exmaple of silly about of memory:

php -i | grep memory
memory_limit => 2048M => 2048

It will run for a good 2-3 minutes before throwing the error.

I assumed there was something odd with my local environment so held on as I was reloading the mac, but the issue has followed me to a fresh install.

I did notices the number of bytes it refers too is ~1.6GB, this figure doesn't change with php cli's memory limit, for example if I drop the limit to 512MB I get the same allowed memory size figure, which suggests to me there is another php binary in play here, but I don't know enough about how the craft cli works to troubleshoot that.

When this happens, in most cases I can complete the update using composer, but it's a hack that I don't want to continue with.

Versions are as follows:

Craft: All 3.1 and above, possibly 3.0 too but can't confirm
Mamp: 5.51
php cli: 7.2.21
Composer: 1.9.0
OS X: 10.14

Any ideas on how to troubleshoot this further?


texts: Matrix field input error from within the control panel

texts:
I have a matrix field with around 26 block types with between 2-6 fields on each. It seems like I've hit a limit and cannot add any more fields to any of the block types. I can add a field if i delete one.

I get the following error "Undefined index: type"

/var/www/dev/domain.co.uk/craft/app/fieldtypes/MatrixFieldType.php(118)

I'm running Craft Pro 2.1.2563

Matt


texts: Massive template cache cleaning tasks always get stuck

texts:
We have a site where we use lots of {% cache %} tags.

Now we almost constantly have a "cleaning template cache" task running, and they often get stuck.

Manual DB intervention and resetting the stuck task to status pending, will sometimes make it move again.

I've tried the various solution here, but nothing helps: DeleteStaleTemplateCaches job getting stuck

Also - there are no error entries in craft.log or phperrors.log when it gets stuck.

Looking at the craft_templatecaches table I find lots of duplicate looking entries:

select id,locale, cacheKey, expiryDate, path from craft_templatecaches;

...
| 685607 | nb     | zDzBdD8bc1y4pf9Sx2HFyL3i24YypSp2sAq5 | 2015-09-08 08:23:21 | site:kompetansetilbud/ny-i-hr-rollen-i-trondheim-10013                                   |
| 685610 | nb     | TMz4eh7FPiINSUixwkpXb0SlkHnZ3b5TSgXm | 2015-09-08 08:23:22 | site:kompetansetilbud/ny-i-hr-rollen-i-trondheim-10013                                   |
| 685611 | nb     | HgLIHHgf56nM1ggOdTmaLlaylu5JeOeM1dNm | 2015-09-08 08:23:23 | site:kompetansetilbud/ny-i-hr-rollen-i-trondheim-10013                                   |
| 685612 | nb     | SLHUKfUz2fF5Jmpy0kWPpvMxFBHH8PvlVJEt | 2015-09-08 08:23:25 | site:kompetansetilbud/ny-i-hr-rollen-i-trondheim-10013                                   |
| 685614 | nb     | oEU6fe1tGc7MdI8WSQIXsf2wZZd9qmXG8P9H | 2015-09-08 08:23:26 | site:kompetansetilbud/ny-i-hr-rollen-i-trondheim-10013                                   |
...

Is this normal?

Anything else I can do to debug why the task gets stuck?

Update:

Using keyed and global caching reduced the size of the craft_templatecaches table from ~20k rows to ~300. However, this did not stop the task getting stuck.


texts: Is it possible to reduce and increase prices on all products at one time by a specified amount or percentage without having to manually do every product. That must be visible to the customer and not just run as a promotion as this doesn't appear to display the cheaper price on the product tile.


texts:
I'm looking to see if there's a better way of querying multiple asset fields in one query, surely there is but I just can't seem to find it in the docs.

      {% for asset in entry.eventMediaTile.all() %}

      {% endfor %}
      {% for asset in entry.eventMediaTriplet1.all() %}

      {% endfor %}
      {% for asset in entry.eventMediaTriplet2.all() %}

      {% endfor %}
      {% for asset in entry.eventMediaTriplet3.all() %}

      {% endfor %}
      {% for asset in entry.eventMediaTriplet4.all() %}

      {% endfor %}
      {% for asset in entry.eventMediaTriplet5.all() %}

      {% endfor %}


texts: Frontend upload for images, mp3s and video?

texts:
I would like to allow users of our site to be able to upload images, mp3's and video from the front-end. Can I do this with the entry form template easily enough?

I was thinking maybe I could use Wistia for the video upload with their widget.


texts:
I have a simple and maybe a stupid question, it´s my first Craft Website...

I´m listing  a news section, the news can be categorized ( max two categories ), and i don´t know how to show the category name in the news list items, the category field name is "categoriaNot"

{% for blog in craft.entries.section('noticias').limit(10) %}

            {% set imagen = blog.imagenNot.first() %}

            {% if imagen %}

            {% endif %}

                **** CATEGORY NAME HERE ****

             {{ blog.title }}

             Publicado el: {{ blog.postDate.format('d.m.Y') }}

                {{ blog.resumenNot }}

{% endfor %}

Any help will be welcome!

thanks!

Sebastián.


texts: Preserve formatting when exporting from Wordpress

texts: I'm using the WP All Export plugin to get posts out of Wordpress, and Feed Me to import to Craft 3. Problem I'm having is I can get a great XML feed out of the WP All Export plugin, but post "Content" fields lose formatting so all comes out as one blob – no paragraph tags etc... Anyone lend a hand?


texts:
I have a Rich Text Field within a Matrix block. I need to add a div around a section of content but can't do this in the template because it's within multiple Matrix blocks.  Solution would be to add it directly into the Rich Text field in code view but it strips out the div and replaces with p tags on save?

I've tried this suggestion but it didn't work.


texts:
Its it possible to use the localization feature to create regional site versions.

Currently when I attempt to use this feature I can only view pages in my locale.

The Apple.com website shows a great example of what we're trying to achieve.

http://www.apple.com/au/
http://www.apple.com/nz/
http://www.apple.com/uk/

We'd like to create new entries and have a draft appear in all regional sub directories.

E.g.

http://www.acme.com/nz/news/news-release
http://www.acme.com/au/news/news-release
http://www.acme.com/uk/news/news-release

...

The main point is we want the entire site open to users from anywhere.

We're not yet concerned with translations either.


texts:
I am new to Craft CMS.  Please tell me about how can I save data into database in Craft?

I have searched a lot of results about my query but nothing give advantage to me.

Thanks in advance.


texts: No entries showing: Unknown error has occurred

texts:
I have recently uploaded our dev site to the live server so we can populate with correct assets and deploy once complete.

I've set all variables I can think of to reflect the new environment, but for some reason no entries are showing and 'Unknown error has occurred' is shown.

The site is now on a subdir of a domain whereas before it was at the root. Also we're now using a Craft personal license as for this site we don't need more.

Could anyone shine some light on what's happened please?!

Thanks in advance,
Tom


texts:
Does anyone know a nice way to get the last lineItem(s) added to a cart in craft commerce via twig template? Example use case, an 'added to cart' confirmation page. I know for this you could query param a product/variant id but multiple could be submitted.

I attempted {cart.lineItems | last} but they do not seem to be in date order. I also checked the class models but didn't find any helpful methods or attributes.

Perhaps some kind of db query, as sql has date fields?


texts:
I'm trying to figure out how I can print the month name i.e April in the below. Currently, it's printing the last three months that contain entries.

{% set year = craft.request.segment(4) %}
{% set month = craft.request.segment(5) %}

{% set entriesInYear = craft.entries.section('bulletinOnline').limit(null).after(year).before(year+1) %}
{% set groupedEntries =  entriesInYear | group("postDate|date('m')") %}

{% for year, entriesInYear in allEntries | group("postDate.year") %}
    {% set counter = ( counter | default(0) ) + 1 %}

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

            {% for monthWord, entries in entriesInYear|group("postDate|date('F')") %}
                {{ monthWord }}
            {% endfor %}
            &nbsp;({{ entries|length }})

    {% endfor %}
{% endfor %}

Example output:

MarchAprilMay(2)


texts: Dynamic Blitz Template not loading currentUser

texts:
I have a Dynamic Blitz template with a currentUser if statement within it. For some reason, it's not working and I can't figure out why.
It gets loaded in as follows:
{{ craft.blitz.getTemplate('brands/_followButton', { elementId: entry.id }) }}

The code on the page running it:
 {% if currentUser %}
  {% if craft.follow.check({ elementId: entry.id }) %}
    favoriteUnfollow
  {% else %}
    favorite_borderFollow
  {% endif %}

  {% else %}
    favorite_borderFollow
{% endif %}


texts:
With PHP 5.4+ we get a built-in webserver, http://php.net/manual/en/features.commandline.webserver.php

Has anyone had luck setting this up with Craft? It seems like it could be pretty straightforward, but I am not sure how to wire up a mysql database.

In particular I am hoping to run this with Gulp/BrowserSync so that I can just fire up a livereload instance of Craft quick and easily.

On a very basic pass-through I just did, it seems to kind of work - except it just has 404 pages and a "Craft can’t connect to the database" error.

Here is my gulpfile.js for reference:

gulp.task('php', function() {
    php.server({ base: 'public', port: 8010, keepalive: true});
});

gulp.task('serve', ['php'], function() {
    browserSync.init({
        notify: false,
        reloadOnRestart: true,
        open: false,
        proxy: '127.0.0.1:8010'
    });
    gulp.watch('*.js').on('change', reload);
    gulp.watch("*.html").on('change', reload);
    gulp.watch("*.php").on('change', reload);
});

gulp.task('default', ['serve']);

Edit: I connected to mysql without much problem (installed using Homebrew, and connecting with 127.0.0.1), but now I am getting:

  Your server doesn’t meet the following requirements to run Craft:

  Mcrypt is required.


texts: Prevent Activation Email on creation - Wait for Admin Approval

texts:
I would like to prevent the 'Activate Your Account' w/link from being sent when users first registers via a front-end public registration.

I need activation to happen manually via an Admin.

I have temporarily blocked this by commenting it out in /craft/app/controllers/UsersController.php
Obviously I do not want to go to production with this, so how can I disable via a plugin?

The code in question appears on line 1049:

//
        if ($verifyNewEmail)
        {
            // Temporarily set the unverified email on the UserModel so the verification email goes to the
            // right place
            $originalEmail = $user->email;
            $user->email = $user->unverifiedEmail;

            if ($isNewUser)
            {
                // Send the activation email
                // $emailSent = craft()->users->sendActivationEmail($user);
                $emailSent = true; // *** NOT TRUE, BUT HACKED ***
            }
            else
            {
                // Send the standard verification email
                $emailSent = craft()->users->sendNewEmailVerifyEmail($user);
            }

            if (!$emailSent)
            {
                craft()->userSession->setError(Craft::t('User saved, but couldn’t send verification email. Check your email settings.'));
            }

            // Put the original email back into place
            $user->email = $originalEmail;
        }


texts:
I am using the Import plugin. This question doesn't have to do with the Import plugin which seems to be working swell, but instead with my onBeforeSaveEntry logic which seems to have botched the import process.

public function init()
{
    parent::init();

    craft()->on('entries.onBeforeSaveEntry', function(Event $event)
    {

        if($params['isNewEntry']) {

            $entry = $event->params['entry'];

            $criteria = craft()->elements->getCriteria(ElementType::User);
            $criteria->groupId = 1;
            $criteria->AffiliateId = $entry['AffiliateId'];
            $criteria->limit = 1;
            $users = $criteria->find();

            if (!empty($users)) {
                $assignedCoach = $users[0]->id;
                $entry->authorId = $assignedCoach;
                $entry->getContent()->coachId = $assignedCoach;
            }
        }
    });

}

What am I doing wrong here? Also, any idea how I kill the import processes which seem to be hung at the moment?


texts: Need help with filtering entries by a custom field using ajax with pagination

texts:
I'm fairly new to CraftCMS and am stuck with a little filtering issue. I'm trying to filter a page of entries by a custom field. I'd like to use Ajax so there is no page reload. Here's how I have the filtering links setup:

Entry Date //postDate asc
Source Date //sourceDate asc
Scenario Date //scenarioDate asc

Both sourceDate and scenarioDate are text custom fields.

My current template is setup like this:

{% extends "_layout" %}
{% block content %}

{% paginate craft.entries.section('research').limit(12).order('sourceDate asc') as pageInfo, pageEntries %}
{% for entry in pageEntries %}

// post entry code

{% endfor %}

{% endblock %}

So my thinking is that when a user clicks on one of the filtering links, the order would change, and reload the paginated entries based off the new order (postDate asc, sourceDate asc, scenarioDate asc).

Since I'm really new to CraftCMS, I don't really know where to begin tackling this task. Any help is very appreciated.

Thanks!


texts: "Craft isn't installed yet" error after updating to Craft 3.1

texts:
I just updated to Craft 3.1 and logged into the admin to make the required updates to the database and this all worked fine. However, when I use the new ./craft update CLI feature, it responds with "Craft isn't installed yet", even though it's on a year old Craft project and just successfully updated to Craft 3.1?

There's not really any other messages to go on for this one. See below.


texts: In Craft 2, check if plugin is available for Craft 3?

texts:
I'm currently running a Craft 2 site.

I thought there was a quick place to check my plugins to tell if they are ready for 3.0?


texts: Counting included child blocks in the Neo plugin

texts:
In the Neo plugin, I've made a block that has the option to add 3 child blocks underneath it.

This is the code from the parent block:

{% extends 'neo/default' %}
{% block blockContent %}

{{ block.mainTitle }}

    {% if block.children %}
     {% for item in block.children %}
     {% if loop.first %}
     {% include "neo/children/" ~ item.type %}
     {% endif %}
    {% endfor %}
    {% endif %}

{% endblock %}

So the parent block can have up to 3 child blocks. You'll get 3 blocks on one row, each block has a 'col-sm-4' (Up to 12 fit on one row if aren't familiar with Bootstrap) class so it fits on one row.

But if a user only chooses to have 2 child blocks the classes 'col-sm-4' will remain the same. I'd like to change this class to 'col-sm-6' and when only one child block is selected, 'col-sm-12'.

Okay so this is the code for the child block:

{% block blockContent %}
{% for block in entry.body %}
{% switch block.type.handle %}
{% case 'serviceItem' %}

  {{ block.text }}
  LEARN MORE

{% endswitch %}
{% endfor %}
{% endblock %}

What I tried first is set the length of the child block. And with that number defined, with the help of if statements, change the layout like this:

{% set numberOfItems = block.serviceItem|length %}
 {% if numberOfItems == 1 %}

   {{ block.text }}
   LEARN MORE

 {% elseif numberOfItems == 2 %}

   {{ block.text }}
   LEARN MORE

Etc...

Unfortunately that method doesn't work since it won't count itself more than once since it is being looped outside of the code file.

I hope my explanation was sufficient of what I hope to achieve.
Does anyone perhaps know the solution?

Thank you for your time.


texts: I'm building a site with digital downloads of PDFs via the excellent Charge plugin and need to include some basic obfuscation of the path to files to prevent people from just being able to predict them. I was thinking maybe I can use the UID of the assets to identify it, is this possible? If not any suggestions are welcome.


texts: Is it possible to disable token expiration? Or prevent follow from bots?

texts:
So I have some gated content entries and need to prevent these from being indexed by search engines etc. Currently using draft pages but the tokens expire which then causes a 404 if someone is to land on that entry.

Anyway to prevent these tokens from expiring? Or does anyone have any suggestions on a field to prevent specific entries from being indexed by search engines. Or any options for saving as hidden entry, would be nice if this was built into craft as it seems like a pretty common feature.


texts: How to pull out entries related to multiple nested categories?

texts:
I have a category set up with nested categories so:

Level1
   -level2
       -level3

In my entries channel each entry can have multiple nested categories so we may have an entry with:

cat1
  -subcat1
      -level3

cat2
  -subcat1
      -level3

The second and third levels will have some categories with the same slug names. So how can I pull out entries with relatedTo that will look at the parents of each level and only pull out categories from the correct nest?

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

Ok I have come up with a solution that works but if anyone can suggest something better please feel free.

{% set sector = 'cat1' %}
{% set topic = 'subcat1' %}
{# set entries variable outside of for loop #}
{% set entries = '' %}
{% if topic is defined %}
{% set categories = craft.categories.group('theCategoryHandle').slug(sector).level(1).first() %}
{% set catChildren = categories.level(3).children %}
{% for childCat in catChildren %}
    {% if childCat.slug == topic %}
        {% set entries = craft.entries.section('mySection').relatedTo(childCat).find() %}
    {% endif %}
{% endfor %}
{% endif %}


texts: Freeform - file field, upload to subfolder with submission id

texts:
In field settings, we have "Upload Location Subfolder" setting, with "The subfolder path that files should be uploaded to. May contain {{ form.handle }} or {{ form.id }} variables as well." description.
Can i use submission data instead of form data? I tried using {{submission.id}}, but it did nothing.


texts: Can you use a different html template for each system message email?

texts:
Is it possible to use a different html template for each system message email?

Alternatively can you determine which system email is being sent from within the template that you can set in the Craft email settings?


texts:
I'm using Craft 3 and I would like to do the following thing:

There is a start date and an end date filed in entry, is it possible to get entries that are between these two dates in PHP?

Thank you!


texts: Return entries where custom field partially contains

texts:
My entries have a field containing a third-party product id and a price, separated by a hyphen, like so:

p666a-12.99

In the template, a plugin is returning me some product ids, and I want to return all entries containing those product ids. I know I can fetch all entries, reduce the custom field down to the product id and compare it to the product ids returned from the plugin, but that seems a bit tardy.

Can I filter my entries using the custom field directly?

{# pluginIds = 'p666a, p678a' #}
{% set entries = craft.entries.section('sectionName').customField(pluginIds) %}


texts: Craft Commerce - Different confirmation email address for different product types or category

texts:
On a website I will be setting up there will be different ranges/types of products.
Basically purchased from different departments within the organisation.

I can filter the products in different ways - either by a category or product type of whatever.
But is there any way to change where the confirmation email goes to.
E.g. All confirmation emails go to finance@domain.com

But if a item is purchased from Category A/Product Type A the confirmation email also goes to deptA@domain.com

An item purchased from Category B/Product Type B - the confirmation email goes to deptB@domain.com

Is this functionality easily achievable or will some sort of plugin be required?


texts:
I have created a module in modules/Core.php which works great and I can reference it using modules\Core::class. But I want to re-organise my modules.

I'm not super familiar with PSR-4 loading but I have taken a look at a bunch of modules to try and copy the file structure and composer file.

Here's the file structure I want:

modules
  └── wrux
    └── Core
      ├── README.md
      ├── composer.json
      └── src
        └── Core.php

Here's my modules/wrux/Core/composer.json file:

{
  "name": "wrux/Core",
  "require": {
    "craftcms/cms": "^3.2.0"
  },
  "autoload": {
    "psr-4": {
      "wrux\\Core\\": "src/"
    }
  }
}

After I run composer dump-autoload I was hoping that I can use the wrux\Core namespace but it's not working. My module is only accessible from then modules\wrux\Core\src namespace.

Any ideas here?


texts: What is the best way to exclude an array of entries?

texts:
I have done a "Is featured" switch on articles which works great. I can list the latest 4 featured articles but after that I would like to list the others (Of course they may be featured too). What is the best way to exclude an array of elements when getting elements? Or is there a better solution?
Update 1
{% set allArticles = craft.entries.section('articles').find() %}
{% set featuredArticles = craft.entries.section('articles').featured(1).limit(4).find() %}
{% set notFeaturedArticles = allArticles|without(featuredArticles) %}

This is the code and the notFeaturedArticles returns with the same entries as the allArticles.
Update 2
{% set featuredArticleIds = craft.entries.section('articles').featured(1).limit(4).ids() %}
{% set featuredArticlIdsString = featuredArticleIds | join(', ') %}
{% set notFeaturedArticles = craft.entries.section('articles').id('not '~featuredArticlIdsString) %}

In this case only the first entry is excluded from the not featured articles.


texts: Trouble getting entries after a certain date

texts:
I have a bunch of entries with field eventStartDate and eventEndDate.

First I set the date

    {% set fwd = entry.eventStartDate|date_modify('+30 min')|date('c') %}

When I output the value of fwd, it is 2017-04-21T08:30:00-05:00

So that's 4/21/2017 at 8:30 AM

Then I query the channel to get events after that date/time

{% set upcomingEvents = craft.entries
  .section('schedule')
  .order('eventStartDate asc')
  .eventStartDate('> ' ~ fwd )
  .limit(5)
  .status('live, pending')
%}

I get events on 4/21/17 starting at 8:00AM, not what I intended.

Is my syntax wrong?


texts:
I would like to rename new assets by PHP, but somehow it does not work.
In Craft 3, I suppose it is like;

Event::on(\craft\services\Elements::class, \craft\services\Elements::EVENT_AFTER_SAVE_ELEMENT, function(Event $event) {
    if ($event->params['isNewAsset']) {
        $asset = $event->params['asset'];
        $folder_id = $asset->folderId;

        if ($folder_id == "22")
        {
            $filename = $asset->filename . "_test";
            craft()->assets->renameFile($asset, $filename);
        }
    }
});

My code is like that, but this message appears;

Upload failed. The error message was: “Getting unknown property: craft\events\ElementEvent::params

Could you help me?


texts: How do I check for the presence of an asset before accessing an empty asset field?

texts:
I have a single asset field that handles two kinds of images:

1) Big Banner image
2) Small featured image

The problem is I want to check for the presence of the second image before I output it on the page. I am doing it like so:

   {% if entry.igBanner[1] | length %}
      {% set asset = entry.igBanner[1] %}
      <img src={{ asset.url }} class="img-responsive" alt={{entry.title}}>
    {% endif %}

But when I try to check the length of an empty index (where the image is not ), my template crashes saying I am trying to pull a method on a null variable. How do I check the presence of an image asset at index[1]?


texts: Writing a plugin that triggers on a Control Panel Template Hook?

texts:
I want to do something similar to this answer but for Craft 3 (eg. render some custom HTML in the Entry editing screen). I can't work out how to do this with the changed Craft 3 hooks.

Should this be registered as an event now? What class/event ID should I be using to add code to cp.entries.edit.details?

(I'm new to Craft plugin dev so a little unclear how to proceed here)


texts: How do I query multiple element types in one query

texts:
I have Craft Commerce installed, and I wanted to search title against both product title and variant title. I looked up in the database, I noticed that products and variants are of two element types, Commerce_Product and Commerce_Variant. As far as I know, with ElementCriteriaModel you can only query against one element type, like what I have now:

$criteria = craft()->elements->getCriteria('Commerce_Product');

Is it possible to query against multiple element types in one db call?


texts: Using Freeform's Composer for CRUD operations?

texts:
I'm using Freeform Pro's Composer to build front-end forms - seems to work great, including the association to an Element... creating entries from the form.

Is there any way to allow the author to do a little "Edit" of their entries? (such as sending an element type and ID to the function, so it loads that data in the form and allows us to save it?)

{{ craft.freeform.form("blogEntryForm").render() }}

Thanks for any suggestions!


texts: How can I check the progress of a large Assets indexing job?

texts: I just uploaded 48,000 photos to Amazon S3, added the bucket to Craft, and am now trying to add them to the Assets library. Where can I see the logs for this?


texts:
I have a custom generated sitemap which I'd like to append to my SEOmatic sitemap.xml file.

Is this possible?

I suppose the simple alternative would be to just add an extra sitemap to Google Search Console?


texts:
On the following screenshot the image on the right called Crown Wood - Plot 1 is disabled in the CMS, so I'd like it not to show up in the results.

Below is my code. I added .status('live') to the for loop as suggested elsewhere in the forum but the disabled posts are still showing up.

Can someone help, as I only want the section to show live entries.

{% set var = craft.entries.positionedAfter(entry).level('2') %}
{% for entry in var.limit('5').status('live') %}

      {% if entry.plotGallery.first() %}

      {% endif %}

{{ entry.parent ? entry.parent.title }} - {{ entry.title }}

{% endfor %}


texts: Maintaining order when getting by entries by ID

texts:
I'd like to get a certain set of entries in a specific order, but the element query comes back ordered by the default 'postDate desc'

{% set ids = ['4213','3200','4204','4212']
 %}

{% set orderedEntries = craft.entries().id(ids).order('id').all() %}

{{ dump(orderedEntries.ids) }} <- not the same order as the array!

It feels like there should be a relatively simple way of doing this in craft/twig, am I missing something? Or should I just resort to SuperSort?


texts: Get all fields within Matrix for position?

texts:
Just working with a Matrix field to create a flexible, 2 column layout. The user can choose to add either an Image or Rich Text field, and position them accordingly with the Position Select field.

To illustrate, one layout might be:

| image | image |
|       |       |
| text  | text  |

But another might be:

| image | text  |
|       |       |
| image | text  |

Now my solution is to first loop through the Matrix field for each possible position option and group fields depending on their position into arrays. ie: leftContent[], rightContent[], etc.

Printing them out is then simple:

    {% for row in leftContent %}
        {% if row.type == 'image' %}

        {% else %}
            {{ row.text }}
        {% endif %}
    {% endfor %}

It would certainly make things easier if you could grab fields for x position? I'm aware this is more of a HTML layout issue and should really be left to the template creator to figure out, but just wanted to see if people had come across this.

Hope that makes sense :)


texts: Accesing craft.categories.slug ids within a MatrixBlock for search query

texts:
I have a dropdown search query I have implemented using this blog (https://www.webstoemp.com/blog/combined-searches-and-filters-craft-cms)

This works excellent for searching my three categories and it's very fast.

{{% set searchContactFor = craft.request.getParam('contactFor') %}

{% if searchContactFor is not empty %}
    {% set searchContactForCat = craft.categories.slug(searchContactFor).ids() %}
    {% set categoriesArray = categoriesArray|merge([{
        targetElement: searchContactForCat,
    }]) %}
{% endif %}}

However, I have a category I need to search call 'institution', which is nested inside a MatrixBlock 'position'. When I attempted to use the same code for searching my other categories it is unable to retrieve the slug.ids(). I've been using the Kint debugger and I'm still unable to crack this one. I am assuming I need to reached into the Matrix block 'position' prior to grabbing the 'institution' slug.ids(). I have several hacks that work but are really terrible on query performance. Does anyone have a simple solution for this that I am missing? Here is an example of an expensive query. As you can see it's pulling back all the member.ids and then matching them to the intuition. Very Slow!

{% set searchInstitution = craft.request.getParam('institution')|lower %}
{% set searchInstitution = searchInstitution|split(',') %}
{% set memberIds = [] %}

{% if searchInstitution is not empty %}
    {% for entry in craft.entries.section('member').limit(null) %}

        {% set found = false %}

        {% for block in entry.position %}
            {% if block.institution.first()|lower in searchInstitution %}
                {% set found = true %}
            {% endif %}
        {% endfor %}

        {% if found %}
            {% set memberIds = memberIds|merge([entry.id]) %}
        {% endif %}
    {% endfor %}
{% endif %}

{% if memberIds|length %}
    {% set queryParams = queryParams|merge({
        id: memberIds
    })%}
{% endif %}


texts: Creating fields programmatically / with PlugIn

texts:
Anyone here who can provide a working sample of how to create several fields and groups using a plugin? It don't need to be fancy, nothing new, just re use the stuff thats built-in and it need to work somehow so I can extend it from there.

Is there something to consider if I create for example some profile fields for the Users Group? Or lets say I want a job portal and have field set name "job profile" which contains fields for job description, location, skills, ...

I feel a bit ashamed asking for such a comprehensive "task" but as I am not really a developer a lot things I am doing is hoping my try & error attempts succeed (sometime). Having said that, I am a real pro in destroying any environment to the ground and finding bugs but I am also very experienced in installing and configuring servers and apps - guess why this is...

This is the reason why I need to be able to create my playground as fast as possible and no, I don't want to copy/paste files, I want to learn extending the system.


texts:
Our malware scanner detected punycode as malware in /vendor/bower-asset/punycode/...

In light of punycode being used to mask some IDNs like wikipedia.org etc. I would like to know what the usage of punycode is in Craft installations.

I saw that punycode is listed under the devDependencies in /vendor/craftcms/cms/package.json however it was not installed on all of our Craft installations.

The file that's being marked as malware is:

/vendor/bower-asset/punycode/tests/data.js


texts:
Is it possible to use the saveUser method to import users with an existing ID?

craft()->users->saveUser($userModel)

I need to import 2000+ users and when doing so, I need to make sure that their old ID doesn't change after inserted, because I need to import other tables too and match them based on that.

The excellent import plugin tries to update the users instead of creating new ones when I tell it to import the ID as well. I'm not sure if that's intended behavior or a bug.


texts: Recipients as dropdown with Contact Form Plugin

texts:
I need to give users the ability to be able to choose which channel of the company their message goes to, i.e. General Inquiries, Estimates etc. using the P&T Contact Form Plugin and a select box. How would I be able to make that work?
Thanks!


texts: Targeting multiple countries with one locale

texts:
I'm new to Craft.  I've the following questions about locales for a international company.

Configuration could look like this:

'siteUrl' => array(
    'en' => 'domain.com/en',
    'en_us' => 'domain.com/us'
    'it' => 'domain.com/it',
    'de' => 'domain.com/de',
    'es_es' => 'domain.com/es',
    'es' => 'domain.com/es'
)

I want to have a generic international version, without any slug, in English. How am I supposed to configure that?
I want the same contents for Spain and other Latin countries but I want to distinguish locales, to target at least Spain specifically. Do I need to create a locale or just use the correct hreflang in HTML?


texts: Update form entry using the Guest Entries plugin

texts:
I am trying to create a form that anyone can submit regardless if they are logged in or not. I found the Pixel & Tonic Guest Entries plugin for this.
Now that I've installed and configured the plugin updating entries doesn't work. Whenever I want to update an entry a new one is created instead.

Here is the code I use:

<form method="post" accept-charset="UTF-8" id="loginForm">
    {{ getCsrfInput() }}

    <input type="hidden" name="entryId" value="88">

    <input type="hidden" name="action" value="guestEntries/saveEntry">
    <input type="hidden" name="redirect" value="entryform?hash={{ hash }}">
    <input type="hidden" name="sectionId" value="3">
    <input type="hidden" name="enabled" value="1">

    <input type="hidden" name="title" />

    Wat is de naam van uw organisatie/onderneming?
    <input type="text" id="text-naamSite" name="fields[naamSite]" />

    <button type="reset" style="float:left;">Reset</button>

    <button id="send-btn" type="submit">Opslaan</button>

</form>

Thanks!


texts: Implementing SimpleSAML PHP in Craft plugin

texts:
We have been trying to implement SimpleSAML PHP in a Craft plugin to facilitate a SAML login for one of our sites. The problem we are running into is that we always get the NOSTATE error.

The response that gets logged does seem to be correct and the login does succeed, only the way it gets handled in the ACS callback seems to be wrong. That is the moment we get the NOSTATE error. The ACS code is copied from the default SimpleSAML PHP implementation.

We think it has something to do with the session. Something weird seems also to be going regarding the session id that's generated, SimpleSAML PHP generates a new session id regardless of an existing session from Craft. After debugging we located where the session id was generated and forced this to use the Craft session id. However this doesn't have any effect at all.

We've been debugging a lot but can't seem to figure where the State should be fixed. Does anyone have any clue or any idea how to fix this problem.


texts: How to develop plugin/module to build landingpage upon fetched JSON-data

texts:
I've developed an app which fetches data from an API based on Laravel 5.5. The marketing landingpage of the app is based on Craft CMS Version 3. The marketing website and the API and the databases of both systems are running on the same server.

I want to generate landingpages for each row of table X of the Laravel database.

www.website.com/awesome-landingpage-about-{slug}

What is the best approach to realize this?

I don't want to fetch the data directly from Laravel's database
I don't want to synchronize the Craft CMS database with the Laravel (add/remove the rows from the laravel's database as entries to Craft)
It would be awesome to be able to have an entry-type "Landingpage" where we can optionally create a landingpage, referencing to an ID of the laravel table and add additional content for the landingpages.

Would be a JSON-API from Laravel to Craft CMS Plugin a good performant idea?

One option would be to use a Dynamic Route and just fetch the data from 127.0.0.1 (because same server) from the template file? Or is there a smarter way in Craft CMS?


texts: Hyperlinks in blog are not showing underlined

texts:
I'm brand new to Craft, having been a Wordpress user. I'm managing a site for a small charity.
Having done some new pages and a blog page without any problem, I did a blog yesterday in which the hyperlinks are live are not visible (ie not showing as underlined). I've tried various different routes for getting the text to use, and tried a new blog, but with no luck.
Can anyone help me? ...in as plain English as possible please, I'm not familiar yet with html or Craft language.
The blog post I've don that is fine is:
https://timetoshineleeds.org/blog/learning-lunches-and-breakfasts-and-teas
\the blog post that won't show the hyperlinks is:
https://timetoshineleeds.org/blog/free-training-opportunity-project-management

Thank you very much
Rob


texts: Is it possible to duplicate an entry as not enabled/live from the listing page?

texts: Is it possible to duplicate an entry as not enabled/live from the admin listing page? Just this means some user put pages live on the site that are just copies - they forget to quickly change it to disabled etc.


texts: How can I tell if a field exists in a block of a matrix?

texts:
I want to see if a certain field exists in a block of a matrix. Here is my code.

{% for block in entry.someStepContainer %}

    {% if block.type == "someStep" %}

{{loop.index}}

{{block.stepTitle}}

{{block.stepDescription}}

      <! -- this is part I'm trying to fix -->

      {% if block.stepAccordionContent %}

          {% for row in block.stepAccordionContent %}

{{row.accordionTitle}}

{{row.accordionContent}}

          {% endfor %}

      {% endif %}

    {% endif %}

{% endfor %}

I've tried using:

{% if block.stepAccordionContent | length %}

But this still yields an empty

stepAccordionContent is a table.


texts: Why does $entry['slug'] and $entry->slug return different values?

texts:
I'm writing a simple plugin for 'Craft 2' and It seems that a slug of an entry is returned if you reffer it like: $entry['slug'] but calling $entry->slug returns same value as entry title.

Is there an explanation of why it happens and what is the best practice of getting values of the entry fields with a homemade plugin?

Thanks!

God bless ya'll.