texts: Multiple image transforms of same image in template

texts:
I'm getting odd results when trying to apply multiple image transforms to the same image. Here's my code:

{% for photo in photos %}
    {% set thumb = photo.image.first().setTransform({ mode: 'crop', width: 300, height: 300 }) %}
    {% set large = photo.image.first().setTransform({ width: 600 }) %}

{% endfor %}

The above code renders an image that is 600px wide for BOTH "thumb" and "large" even though the criteria for each is different and I'm setting unique variables.

Is it possible to have multiple transforms on the same image? Is there another approach I should try?

EDIT

Same results with these two code variations:

{% set photos = craft.entries.section('photo').find() %}
{% set thumbTransform = { mode: 'crop', width: 300, height: 300 } %}
{% set largeTransform = { width: 600 } %}
{% for photo in photos %}
    {% set p = photo.image.first() %}
    {% set thumb = p.setTransform(thumbTransform) %}
    {% set large = p.setTransform(largeTransform) %}

{% endfor %}

AND

{% set photos = craft.entries.section('photo').find() %}
{% for photo in photos %}
    {% set thumbImage = photo.image.first() %}
    {% set largeImage = photo.image.first() %}
    {% set thumb = thumbImage.setTransform({ mode: 'crop', position: 'center-center', width: 300, height: 300 }) %}
    {% set large = largeImage.setTransform({ width: 600 }) %}

{% endfor %}


texts:
Is it possible to display the number of variants a product has?

This would be in order to achieve the following:

  This product is available in 3 colors


texts:
We have a site deployed in Norway, and people have uploaded PDF-assets with Norwegian non-ascii characters in the filenames.

Normally this works fine, the URLs are encoded like this and it works:

http://[oursite].no/assets/files/downloads/%C3%85rsberetning-2014_kladd.pdf

("Årsberetning" - annual report)

But one file didn't want to download, it only gave me 404. However, checking on the server the file was there, and the filename appeared correct. Also, re-scanning asset folders didn't remove it.

BUT - I was not able to rename the file from within craft, nor download it.

After much hair-pulling I established that the file on disk had the Å encoded as '\x41\xcc\x8a' whereas craft looked for a "pre-composed" Å ('\xc3\x85').

NOW the question - where did this break? :)

Does Craft unicode-normalise filenames?
Does MySQL normalise the unicode it stores?

The file has moved around various developer machines and staging servers before making it into production, it could be some other part of the tool-chain that broke it.


texts: How do I upload an asset in Craft 3, via PHP

texts:
I've found various answers on how to upload assets via PHP for Craft 2, however nothing for Craft 3.

All answers use the method:

craft()->assets->insertFileByLocalPath()

E.g: How to upload an asset from a front-end form

I was wondering what the equivalent is for Craft 3.

Thanks


texts:
Trying to get Placid working but I can't get Twitter to Connect. The keys are all set correctly, but when I click 'Connect', I get this error:

Craft\OauthService and its behaviors do not have a method or closure named "encodeToken".

On line 266 of /home/rizen/sites/rizencreative.com/craft/app/framework/base/CComponent.php(266)

throw new CException(Yii::t('yii','{class} and its behaviors do not have a method or closure named "{name}".',
    array('{class}'=>get_class($this), '{name}'=>$name)));


texts:
Is there a way to parse a line of Markdown within Twig – without the surrounding
<p> tags?

I see there is a StringHelper method called ParseMarkdownLine that does exactly what I'd like, but I haven't found a way to invoke it in my templates.


texts: Blog/_entry breaking all assets globals like header & footer logos

texts:
When templating my Craft site, I have run into an issue with on both my Local & Server environments on the latest version of Craft. I am running a LAMP stack and I think I have been able to narrow down the issue to being a file directory issue or section config mistake.
My Blog/Index page functions perfectly and will include all asset fields without issue, yet when I click on a blog post to navigate to a blog/_entry, all assets stop functioning. Below is the twig code that I use. I have only one volume titled "images" sitting within the web/ folder.

{% for image in entry.featureImage %}
  <img src="{{ image.url }}" alt="{{ image.title }}" data-holder-rendered="true"/>
{% endfor %}

So the funky thing is that the {{ image.title }} entry seems to work perfectly and will call the image, but will not display it. Maybe this could be an issue with file organization? The same problem occurs with my global assets (logos).
Here's a screenshot of what this looks like in action.
Any direction is much appreciated! New to development & not the brightest crayon in the shed so I'm having difficulty  figuring out how to approach this problem, although I didn't seem to locate any issues among the config/ files.


texts: wp-login.php bloating log files every 20-30 seconds

texts: Hi has anyone come across this before. It seems like a hack attempt on the site from a bot trying to access it as a wordpress site. This is obviously causing loads of errors in the log files bloating them and making it hard to find any real logs. Is there anything we can do in craft or on the server to block these attempts?


texts: Share: Getting 'Forbidden' message when sharing externally

texts:
I've run into an odd issue and I can't seem to figure out what is going on.

Normal Process:

I click the Share arrow on a disabled entry.
I copy the tokenized link and send it out.
Folks without accounts are able to preview the page.

What is happening now:

I click the Share arrow on a disabled entry.
I copy the tokenized link and send it out.
Folks without accounts are given a 'Forbidden' warning. If I refresh my preview page, I also get the same warning.

NOTES: There is no authentication required to access the template itself.

I checked the latest updates to Craft but did not see anything obvious that might affect that. I double-checked that the token time extension that we added in general.php and it's still set to a week.

Any ideas?


texts: Multiple Queries with differing CSS in Paginated output

texts:
{% set query = craft.entries.businessAddress(params).orderBy('Premium desc, distance').limit(12) %}

{% paginate query as pageInfo, pageEntries %}

    {% for entry in pageEntries %}

    {% endfor %}

{% include 'includes/_sect-pagination' %}

I have the above code, which outputs paginated results of a section ordered by whether they are a STANDARD or PREMIUM entry, then by a distance calculation.
Within the entry output an IF statement adds more CSS to the output depending if STANDARD or PREMIUM, all of this works fine, however, id like to add more CSS to the results.
I would like to have the PREMIUM entries output in a separate ROW to the STANDARD entries so the ROWS can have different CSS applied, but still remain part of the total pagnination.
For example, if there are 3 premium and 14 standard,
The first page would be:-

<did class="col-lg-4">PREM ENTRY 1

<did class="col-lg-4">PREM ENTRY 2

<did class="col-lg-4">PREM ENTRY 3

<did class="col-lg-4">STANDARD ENTRY 1

<did class="col-lg-4">STANDARD ENTRY 2

<did class="col-lg-4">STANDARD ENTRY 3

<did class="col-lg-4">STANDARD ENTRY 4

<did class="col-lg-4">STANDARD ENTRY 5

<did class="col-lg-4">STANDARD ENTRY 6

<did class="col-lg-4">STANDARD ENTRY 7

<did class="col-lg-4">STANDARD ENTRY 8

<did class="col-lg-4">STANDARD ENTRY 9

Second page would be:-

<did class="col-lg-4">STANDARD ENTRY 1

<did class="col-lg-4">STANDARD ENTRY 2

Can anyone say if that is possible within paginated results, if so how?
Any help would be greatly appreciated.


texts:
Is it possible to execute a custom function on the entry crud methods? Basically what I want to achieve is that a CP user with certain field value cannot read or save an entry that doesn't have the same field value. (in this case company) Are there any hooks/events available on that level? On group permission level I just want all permissions set to allow on that section.

Thanks in advance


texts:
I want to create product groups and save some data in themselves. but I only could add field to individual product, not product type itself.
Or it is nice if product could have hierarchal structures.

Is there any way to achieve?


texts:
Consider a site with a very flat hierarchy that has a lot of basic pages. Most pages on the site are extremely similar, so they can all share the same entry type (and thus, fields) without problems.

The problem is, there are a few pages that have wildly unique content layouts. There's special content that will only ever be used on these pages.

From my understanding, there's a few solutions to this:

Use a Matrix field in the Page entry type and add a block for each special page you need. This lets you build the unique pages, but for the dozens of other "normal" pages it becomes very weird and unnatural (plus there's nothing stopping the client from erroneously adding the 'special page' Matrix blocks on non special pages).
Using multiple entry types, but this is also a bit clunky and would mean have to using a Channel or Structure.
Use Global sets (one for each special page). Also a bit of a dirty workaround.

Is there a cleaner way to achieve "one-off" fields that are used only by a specific entry?

Another CMS - Bolt - has a solid solution to this: Template Specific Fields. As another example: using WordPress with ACF, you can assign field layouts on a per-entry basis if required.

I was hoping something similar could be achieved in Craft.


texts: How to transfer Craft configuration changes separate from web conent

texts:
I am busy reworking a reasonably large website that is already in Craft. The production site is updated with new content several times a day. My current work is an interface redesign. I have a local machine environment, and then a dev environment on the same server set up at the ISP alongside the live production one. The dev will function more as a test server - I can refresh from the production server a few times to test my update process.

My rework on the local dev environments starts with an exact site copy, and will involve mostly template changes. However I suspect I might need to do some database tweaks. In the meantime the live site will undergo a number of content changes.

I am wondering how best to deploy those database tweaks to the live dev and then production servers. My current strategy is to write down what changes I made in local dev and then manually make them on the main dev or live server. These seems a bit dumb unless it is just one or two. I can't copy the whole database because then I would overwrite content changes and I can't put a hold on content changes because my work is likely to take a week or three.


texts: Querying Global fields using CraftQL and Gatsby JS

texts:
I am using Craft in headless mode with the CraftQL plugin. My front end is built using Gatsby JS.

I am able to query entries and output the data to my templates, however Global fields are not available. Here is my code:

// gatsby-config.js
plugins: [
  {
        resolve: `gatsby-source-craftcms`,
        options: {
            endpoint: `http://cms.local/api`,
            token: `REDACTED`,
            query: `{
                globals: globals {
                    contact {
                        address
                    }
                },
                home: entries(section:[home]) {
                    id
                    title
                    ... on Home {
                        subHeading
                        intro
                        ctaButton {
                            ... on CtaButtonButton {
                                __typename
                                text
                                linkUrl
                            }
                        }
                    }
                },
// etc

And then in my template:

export const query = graphql`
  query {
    home {
        title
        subHeading
        intro
        ctaButton {
            text
            linkUrl
        }
    }
    globals {
        contact {
            address
        }
    }
  }
`

In my console I get:

error  Cannot query field "globals" on type "Query"

If I remove the globals from the query I can successfully build and output data.home.title.

I've tried using the CraftQL browser in the CMS and I can successfully query globals:

I'm confident I'm missing something but can find nothing in the docs for Gatsby-Source-Craft or CraftQL.

Anyone have any idea what I'm doing wrong here??


texts: Build Query relatedTo multiple categories

texts:
Trying to build a complex query and I'm sure there is bound to be a better way of doing it that the multiple if statements I currently have.
URL for the page is /products/(category1)/(category2)/(category3)

if any of the categorys in the url is selected it will display that slug other wise it will be all e.g.
/products/inks/glass/all
/products/all/glass/catname

I have been doing this:

{# get categories #}
  {% set catTypeSlug = craft.request.getSegment(2) %}
  {% if catTypeSlug != 'all' %}
  {% set catType = craft.categories.slug(catTypeSlug).first() %}
  {% endif %}

  {% set catSurfaceSlug = craft.request.getSegment(3) %}
  {% if catSurfaceSlug != 'all' %}
  {% set catSurface = craft.categories.slug(catSurfaceSlug).first() %}
  {% endif %}

  {% set catUseSlug = craft.request.getSegment(4) %}
  {% if catUseSlug != 'all' %}
  {% set catUse = craft.categories.slug(catUseSlug).first() %}
  {% endif %}

  {# set parameters #}
  {% if catType is defined and catSurface is defined and catUse is defined %}
    {% set params = { section: 'productsServices', relatedTo: catType, relatedTo: catSurface, relatedTo: catUse } %}

  {% else %}
    {# multiple if statements checking if categories defined #}

  {% endif %}

What's the best way to build my parameters instead of multiple if statements?


texts:
Seems like I can't get the base install URL to work. To get Craft to show posts I have to format the URL as,

/public/index.php?p=news/2015/we-just-installed-craft

Instead of just the /news/2015/we-just-installed-craft

I think the .htaccess is getting read because after putting in garbage the server did error out when I used the /public/ URL but not sure what else I'm doing wrong or how I could troubleshoot this.


texts: ERR_EMPTY_RESPONSE when accessing order data (MAMP)

texts:
I've got a local installation of Craft 3.0.37 and Craft Commerce 2.0.0-beta.15 running on MAMP. When completing an order, an empty response is given by the browser. The same thing happens when trying to look at that error from the admin area.

When I look into the MYSQL logs, I see the following error for both situations:

2019-01-13T13:32:43.718637Z 300 [Note] Aborted connection 300 to db: 'DBNAME' user: 'root' host: 'localhost' (Got an error reading communication packets)

I've tried upping the limits of the MYSQL setup, but to no avail.


texts: Updating the cart with a different variant after a variant is in the cart

texts:
This would seem straightfoward but I can't figure it out. The situation:

I have a product with two colour variants (yellow, orange).
On the product page, the customer adds the default variant (yellow)
to the cart.
On the cart page, the customer should have the option of changing the
colour. But if I select a new colour from the drop-down and update
the cart, a new item is placed in the cart rather than the existing
item being replaced.

I could have them select the colour before they add it to the cart but that seems a little messy since I'd be bringing part of the transaction onto the product page. And they would not be able to update the colour if they changed their mind.

I suspect that I need to use an event to somehow delete the existing item and replace it with the new one. But I have no idea how to accomplish that.


texts: Search for the entry Id with the search form

texts:
A customer of mine has printed references of the entry Ids of their product. Now they want to have a search form on their website where it's possible to search either by the name or by entry Ids.

How can you search for an entry id and other fields at the same time in a search form?


texts:
I try to pass a variable from to a macro:

{% set syName = {
   x: { name: "Schön"},
   y: { name: "Leicht bewölkt"},
   z: { name: "Stark Bewölkt"},
    }
%}

{% macro prognose(symbol, syName) %}
   <img src="test/{{ symbol }}.png">
   {% for alt in syName %}
      {{ alt.name }}
   {% endfor %}
{% endmacro %}

{{ _self.prognose(  '1' , syName ) }}

So far so good. But this passes all the content from the variable into the macro. I want to trigger x, y, z individually.

So I tried to write it like this: {{ _self.prognose(  '1' , syName.x ) }}

This gives the error:

  Impossible to access an attribute ("name") on a string variable
  ("Schön")

How do I have to write this?


texts: Conditional variables within a certain matrix block type

texts:
So I have a matrix field with 3 different block types. The first two block types have markup contained within their scope. The last type, has opening and closing tags for the first of type and last of type (basically creating a row with two columns). I was able to successfully get the markup, but wanted to see if there is a better way to to this write this.

{% for block in entry.homeContentBlocks %}
    {% if block.type == "leadGeneration" %}
        ...
    {% elseif block.type == "banner" %}
        ...
    {% else %}
        {% if block.next() %}
            {% if block.next().type == "contentBlock" %}
{% endif %}
        {% endif %}

            {% if block.next() %}
                {% if block.next().type == "contentBlock" %}

                {% endif %}
            {% endif %}
            {% if block.prev() %}
                {% if block.prev().type == "contentBlock" %}

                {% endif %}
            {% endif %}

{{ block.heading }}

                {{ block.body }}
                {% if block.btnLink | length %}
                    {% set link = block.btnLink.first().url %}
                    {{ block.btnLabel }}
                {% endif %}

        {% if block.prev() %}
            {% if block.prev().type == "contentBlock" %}
{% endif %}
        {% endif %}
    {% endif %}
{% endfor %}

So this works, but let's say the blocks out of sequence. I thought maybe a increment variable could work, but wasn't sure how to implement it.


texts: How to save entry to the current site from the front end?

texts:
I have a multi site setup and a front facing entry form, which saves entries always to the same site (and not the current one which is weird).

Is there a way to define to which site the current entry should be saved? Something in the lines of:

{{ csrfInput() }}
<input type="hidden" name="action" value="entries/save-entry">
<input type="hidden" name="sectionId" value="1">
<input type="hidden" name="site" value="{{ currentSite.id }}"


texts:
I have a site set up that uses Craft as a CMS only, not used to display templates, as this is handled by React JS separately.

My site is set up so that Craft responds on /api.

I cannot for the life of me figure out how to POST data into a section!

I have a route set up, so my routes file is like:

return array(
    'post-message' => array(
        'action' => 'entries/saveEntry',
        'sectionId' => 13,
    ),
);

I am trying to test this using Rested app, posting a couple of fields into my section, but it doesn't do anything.

Rested is pointing to /api/post-message using a POST request.

I can't find any documentation that tutors a developer on how to post data into a section, so I'm completely stuck here.


texts:
I'm using Craft Pro 2.3.2625

I'm trying to write a command-line called script which can call Craft's functions (to create new entries with assets).

Based on Brandon's updated answer here:

Bootstrap Craft from another app

Using:

$craft = require 'craft/app/bootstrap.php';

in a standalone script should just work after Craft 2.2 - but doing so gives me the following errors (paths tweaked to remove project name):

PHP Notice:  Undefined index: SERVER_NAME in craft/app/bootstrap.php on line 105

Notice: Undefined index: SERVER_NAME in craft/app/bootstrap.php on line 105

Notice: Undefined property: Craft\WebApp::$request in craft/app/controllers/TemplatesController.php on line 156

Fatal error: Call to a member function isSiteRequest() on a non-object in craft/app/controllers/TemplatesController.php on line 156


texts: How to create an element query in PHP with custom field names in variables?

texts:
I'm trying to dynamically create an element query in PHP where the custom field criteria come from an array of strings. Something like this...?

$users = User::find();
$users->group($groupList);

foreach ($criteria as $key => $value) {
    // Each key value is the handle for a custom field and the
    // field value used as criteria
    $users->$key($value);
}

$users->all();

How can I use a custom field name in a string as a parameter?

Edit If I don't chain the criteria, I also get a deprecation error when I iterate over $users...Is there a better way to do that, too?


texts: Redactor ImagePosition - no custom styles

texts:
I have ImagePosition within Redactor set up, but ideally, I'd like custom settings rather than the default "none, left, right, center"

Redactor file reads:

{
  "buttons": ["html","formatting", "bold", "italic", "unorderedlist",
  "orderedlist", "link", "image", "video"],
  "plugins": ["fullscreen", "video"],
  "toolbarFixed": true,
  "imagePosition": {
    "left": "image-left",
    "right": "image-right"
  }
}

The above activates the ImagePosition within the Edit screen of the image but no custom styles. Cleared CP cache, no luck. Thanks.


texts: Is there any way to add javascript in craft


texts: Not finding template when adding "tag" view

texts: Not trying to do anything fancy here, just trying to have a "tag" view similar to my category view (which uses the same template), however, when I add my link, /blog/{{ tag|slugify}} (I'm using Slugify to generate a slug out of the tag name.), it returns the "Unable to find the template â€œ_layoutâ€" error. This should load the /blog/index.html template but it is not. My category view is working as well as the main load. (I am getting the same error when trying to do an author /blog/{{ entry.author.username }}) What am I missing?


texts: Element API calling Module that integrates with third-party plugin

texts:
This is probably a bit niche but anyone especially au fait with the element api here?

On project X I have a custom module within which I am referencing a service from another plugin (bolden/google-maps-api). If I access the module directly (eg via a controller or variable belonging to my module) then all works fine.

However - if I try and access my module service from within an element api endpoint, then the service doesn't work (or rather returns null when trying to access the third-party plugin/service).

For example, in my endpoint I am calling the service ($location is a string):

$data = MyModule::getInstance()->ServiceName->ServiceMethod( $location );

But this returns the following Response: Call to a member function placeFromText() on null (the stack trace highlights the corresponding line within my module/service), eg:

$googleMaps = GoogleMapsApi::getInstance();
$result = $googleMaps->googleMapsApiService->placeFromText( $place, 'geometry' );

The same query, when accessed within my module (eg a controller or variable), works fine and returns a data object from the Google Maps API (as expected).

Bit confused - anyone have any thoughts on why this service isn't accessible from my module when accessed via the element API?

Any thoughts on this issue would be much appreciated!

Cole


texts: Good practice to "Clear Caches" before you "Backup Database"?

texts:
Every time I create a database backup, I find myself instinctively clearing the cache first. My gut tells me that any cached data would be unnecessarily included in the export.

Is this helpful, or am I just being OCD?


texts: How can I display a "pending" entry in my "_entry" template?

texts:
I have an event site with dates in the future and past.

I know how to display future entries as a listing:

{% set entries = craft.entries.section('mySection').status('pending') %}

But how do you display an entry with status "pending" on the "_entry" template?
In my case nothing displays?


texts: Where can I find the robots.txt file in Craft 3?

texts: I can't find it in the web folder or anywhere else, but its there when I visit the file in the browser.


texts: Getting error "Your session has ended. Enter your password to log back in." every 30 seconds or so

texts:
This is happening for all users and only on production environment.

"Your session has ended. Enter your password to log back in."

Entering your password does not allow you to actually see the admin panel again.

Things we have tried:

Deleting the contents of craft/storage/runtime
Removing all rows from craft_sessions in db
Setting 'overridePhpSessionLocation' => false
Setting 'requireMatchingUserAgentForSession' => false
Setting 'userSessionDuration' => false
Setting craft/app/, craft/storage and craft/config as CHMOD 774
Changing craft/ folders to be owned by www-data
Setting session.auto_start = 0

Our environment is PHP 7 with Ubuntu 16.04 running Apache 2.4.18

Something to consider is we run with an Akamai CDN cache that is set to ignore our entire /admin directory, but my suspicion is that something elsewhere is getting cached. Thoughts about that? Is there another directory we should be ignoring?

Also as a point of info, our /craft folder is above the docroot so not publicly accessible and therefore unlikely to be cached.

Finally, what's very strange is if I remove the modal containing the error message from the DOM in Chrome Inspect, I am able to still navigate the panel fine, without having to re-authenticate. Error also happens in both Chrome and Firefox.


texts: Found cool example of Header Globals what field type is used for this?

texts:
So I was reading an article on craft, and found an example of something I am trying to do. Creating a global for header/footer links etc so they can be managed dynamically.

Here is a screenshot of what they did.

I setup a Header global and Header goup for a matrix field. Any idea what field type they used to Add a row for the links?

I can't think of any field options in this matrix block to allow this kind of option. Seems like maybe this would be a custom plugin field type or something that creates this kind of option. Clicking Add a row could popup a modal to choose an entry, then inserts the url and label with the label being editable.

Anyone have any idea how they did this?

Update

I ended up finding a Craft menus plugin which is great and is now what I am going to use for my menus. You can find it here if anyone is looking for a menu system:

  https://github.com/familiar-studio/craft-menus


texts:
I’m trying to show only entries for the created in the last month. I’ve taken this from the example in the docs but it ends up showing nothing. There’s 100% entries with a postDate in the last month.
What am I missing?
{% set start = now|date_modify("-1 month")|date('Y-m-d') %}
{% set end = now|date('Y-m-d') %}

{% set newsQuery = craft.entries({
    section: 'news',
    postDate: ['and', ">= #{start}", "< #{end}"],
}) %}

Thanks!


texts:
I just need to return the latitude and longitude of my Google Maps marker.  I do not want to make a request to Google, nor do I need to display a map with javascript.  I need to create markers inside of blog entries and only return the coordinates.

Can the Google Maps plugin do this?  Can I pass the lat and lng to text fields when i save the entry?


texts: Posting front-end form to plugin controller route results in 404

texts:
I'm working on a plugin and need a front-end (non CP) form that submits to one of the plugin controllers. Here's my setup:

- plugins
  - portal
    -- PortalPlugin.php
    - controller
      -- Portal_AccessController.php

Portal_AccessController.php

<?php
namespace Craft;

class Portal_AccessController extends BaseController {

    protected $allowAnonymous = true;

    public function actionLogin() {

        echo 'Here';

    }

}

I then created a front-end form by adding a new template directory in /craft/templates:

- pro-portal
  -- index.html

With index.html containing:

<form method="post" action="" accept-charset="UTF-8">
    <input type="hidden" name="action" value="portal/access/login">

        <input type="text" maxlength="4">
        <input type="text" maxlength="4">
        <input type="text" maxlength="4">
        <input type="text" maxlength="4">

    Test me
    <input class="btn submit" type="submit" value="Submit">
</form>

Hitting mydomain.com/pro-portal displays the form. On submit it returns to /pro-portal but with a 404 error.

I also tried creating an action link but that also results in a 404 at /index.php/actions/portal/access/login.

I've looked through answers on similar questions and tried all the solutions but no luck. Am I overlooking something? Missing something?


texts:
I have a Product entry type that contains a field for Components (which are also products) and a field for Related Products (again, also Products). I want to be able to find a parent product from a Component, but using a relatedTo() gives me all the Products on which it is a Related Product as well.

Is there a way to specify which field you want to use with the relatedTo() method?

$product = Entry::find()->section('products')->relatedTo($component)->one();

Expected result = The parent product.

Actual result = A random product on which the component is a related item.

Of course, this was all working great until I just recently added the Related Products field.


texts:
I'm using Craft 3 and have created a section (channel type) for my project entries. At the bottom of each project page I have my Prev and Next Project buttons. How do I target the first and last project entry based upon the post date? I want to add some space between the buttons when they're together, but dispense with it on the first and last entries because.

Below is my current code from my project _entry template for the buttons:

{% set params = {section: 'projectEntries', order: 'postDate desc', limit: null} %}
{% set entry_prev = entry.getPrev(params) %}
{% set entry_next = entry.getNext(params) %}

Then on the buttons I'm using an if statement to show the next or prev URLs.

To target the first entry I've tried using :

{% if craft.entries.section('projectEntries').order('postDate desc').one() %}
    show alt button code
{% else %}
    show regular button code
{% endif %}

Which shows my alt button code, but shows it on every project page, instead of just on the first entry.

What do I need to do?

Thanks,

Richard


texts: Is it possible to create a plugin using Python in Craft 2?

texts:
I've been searching and trying things for a few days now, but I feel like I'm spinning my wheels. I've got a Python script that reads in a .pptx file, and returns a Dictionary of slides. I've also tried returning different things from the Python script, even as simple as a Hello World string.

For simplicity's sake, I just have this code in my onAfterInstall() method:

$output = shell_exec("import_ppt.py 'original.pptx' ");
    var_dump($output);
var_dump($output);

For the filepath, I've also tried ".realpath(dirname(__FILE__))."/ as well, to no avail. I always get a NULL return and a PHP warning about not being able to modify headers.

Then, in my Python file, I have:

if __name__ == '__main__':
import sys
buildSlideshow(sys.argv[1])

buildSlideshow takes one argument, which is the filepath of the powerpoint file, and eventually returns the dictionary of slides and slide content.

I know that the error isn't in my Python code, as if I run it in shell I don't have any problems with it and get the result I want. So, my overall question is this:

Is what I'm trying to do a pipe dream, or am I just missing something major? I can't find any docs about CraftxPython, simply searching the word "Python" on this very site brought up no results, and when I tried looking up how to incorporate Python into a Craft 2 plugin, all I got was information on how to create a plugin for Python.


texts: Display entries filtered by one or two related entry fields ordered by "dateUpdated"

texts:
I think I have been staring at this one too long because conceptually it seems fairly straightforward but I can't seem to pull it off. I am pretty sure I am going nowhere due to how complicated I am making my twig code

Here is what I have:

"News" channel that holds news entries that can be optionally related to either a Program 1 entry or Program 2 entry.
Program Type 1 channel.
Program Type 2 channel.
In the news entry there are two fields, one to relate Program 1 entries to the news item and another to relate Program 2 entries to the news item. They are being used similarly to categories in this case.
News entries can have one or both of the related entries fields populated
This is in a module that is shared throughout the site so I am not on a "news entry" page (if that makes sense), it will be an include that is included where needed.

Here is what I need to do

I need to be able to display a list of:

the four most recently updated Program 1 or Program 2 NEWS items (combined list order by dateUpdated)

Thinking out loud it looks like I can grab a listing of each and then merge them together but I would love to see how smarter folks would handle this in the most efficient way.


texts: Only show items related to the lowest category level

texts:
I have a category group (CG).
I have a channel of entries with a matrix field (MF).
Every block in that matrix field has a category field linked to the CG.

I want to list all the MF blocks in an ordered list grouped by their category.
So for example:

Category A

MF block 1
MF block 2
Category AB

MF block 3

I'm looping over all categories within CG (with a recursive macro) and for each category I show a MF block that has that category related.
The problem is that when a block is related to Category AB, it is also related to its parent Category A, so the block is shown in Category A as well as in Category AB.

I want it to be only shown in the lowest level category, being AB in this case.

It gets even trickier because I cannot limit the amount of categories selected to just 1, because than Craft automatically selects only the top parent. So now (even if I don't need it) I have to take care of the possibility that the matrix block has multiple categories selected (and their children).

I was thinking about grouping the matrix blocks by their category with the groupBy filter plugin but I haven't found the time yet to try this out. And I'm afraid I might loose the hierarchy of the CG.

I could use a section for the categories (where you can limit it to a single item and it'll select the correct child) but than the client has a hard time to see what the parent category is in the CP. So that's a downer.

Why I need this:

The client needs to be able to upload a ton of files related to an entry or add links related to an entry. That's why I created a matrix with 3 block types: external link, internal link and file.
The file block has a table field where they can upload an asset and select a locale. Because all files can have multiple translations. But the locales these files can be translated in do not match the locales that the site is available in. So that's why I can't just use a translatable asset field. That also why I can't use a front-end asset browser (because of the links and the translated files and because I have no control over the created folder structure).

I could live without them being able to add links if that would make it simpler. Alternative solutions are more than welcome!


texts: Craft 3 - Searching by date field - Calling unknown method: craft\behaviors\ElementQueryBehavior

texts:
On a website upgraded to Craft 3 - having issues pulling events by date.

Error Is:

Calling unknown method: craft\behaviors\ElementQueryBehavior::eventDate()

The Error occurs on the last line of my code below.
I'm done alot of searching but unable to find the correct method I should be using now.

    {% if (category is defined) and (category is not empty) %}
    {% set params = { section: 'events', orderBy: 'eventDate', relatedTo: category } %}
    {% else %}
    {% set params = { section: 'events', orderBy: 'eventDate' } %}
    {% endif %}
    {% set j = 0 %}
    {# Retrieve all of the events for the month, and group them by day #}
    {% set groupedEvents = craft.entries(params).eventDate('and', '>= ' ~ startdate, '<= ' ~ enddate) | group('eventDate|date("Y-m-d")') %}

UPDATE
Ok think found the issue - needed square brackets.

{% set groupedEvents = craft.entries(params).eventDate(['and', '>= ' ~ startdate, '<= ' ~ enddate]) | group('eventDate|date("Y-m-d")') %}


texts: How/Can does Craft handle ancestor/grandparent relationships?

texts:
I spent a fair amount of time yesterday searching for any other questions that may have been answered that are similar to this one, but haven't had much luck.

Essentially what I want to do is to daisy chain some Entry relationship fields. I'm not entirely sure if this is possible in Craft, as I haven't seen any documentation or commentary on it.

Here is how I would like to have my content organized. The site will have a few channels: States, Regions, Counties, Towns and Inductees. As you can tell, the relationships basically drill-down in an obvious way: States have Regions; Regions have Counties; while Counties have both Towns and Inductees. I like the idea of being able to add a new Town, select which County it belongs to, and automatically inherit the Region and State data. Ideally, I'd like to be able to do something in a Town template like {{entry.state.title}} which would pull the title of the state to which this town's county belongs.

Now, the States and Regions basically are just lists... The States page will be an archive listing all the Regions in the State. The Regions page will be an archive listing all the Counties in the Region. Would these be better suited as Categories, than Channels? If so, would there still be a way to access the State from, say, a Town or Inductee entry? I'd rather not have to rely on the content editor to have to select states and regions for each new Town/Inductee entry. I'd rather they only have to select its County.

I'm new to Craft, so I apologize if this question seems either absurd or incoherent :)

Thanks!


texts: Craft 3 Launguage Switcher by certain group

texts:
I'm working on the language switcher and have it working. The only thing is I want it to pull from group data-id=1 It's pulling from all sites because of the i18n to change the language name to it's native name.

I made a "disabled" group in Craft CMS 3 and put Russian in it and it shows up with i18n.  I had it working before by only the 2 letter abbreviation showed such as "de" instead of Deutsch and Russian didn't show.

{% set currentSite = craft.app.sites.currentSite %}
{% for siteInGroup in currentSite.getGroup.getSites() %}
   {% if siteInGroup.id == entry.siteId %}
      {% for locale in craft.i18n.getSiteLocales() %}
        {{ locale.getDisplayName() }}
   {% else %}
      {% set entryForOtherSite = craft.entries.id(entry.id).site(siteInGroup).one() %}
        {{ locale.getDisplayName(siteInGroup.language) }}
      {% endfor %}
   {% endif %}
{% endfor %}

I figured it out:

    {% set currentSite = craft.app.sites.currentSite %}
{% for siteInGroup in currentSite.getGroup.getSites() %}
   {% if siteInGroup.id == entry.siteId %}
        {{ locale.getDisplayName() }}
   {% else %}
      {% set entryForOtherSite = craft.entries.id(entry.id).site(siteInGroup).one() %}
      {% set locale = craft.i18n.getLocaleById(siteInGroup.language) %}
        {{ locale.getDisplayName(siteInGroup.language) }}
   {% endif %}
{% endfor %}


texts: Internal Server Error: missing method or closure

texts:
Receiving the standard error:

  Craft\MatrixBlockModel and its behaviors do not have a method or
  closure named "sectionArticles".

The problem is that this error doesn't make sense. Here is why:

I have a newsletter template with the block 'sectionArticles'
It lists entries from 3 different sections
These 3 sections do not have a block 'sectionArticles' nor a reference to it in their templates.
If I click on a link that leads to the url for these entries, I receive the above error
If I copy and paste the url into a new tab everything is fine
This only recently started happening. In other words, old issues of the newsletter are fine

Help?

Here is code for referring template:

{% for block in entry.connectionsContent %}
  {% switch block.type %}
    {% case "connectionsTextOnly" %}

          {% set asset = block.sectionImage.first() %}
          {% if asset %}

          {% else %}

          {% endif %}
              {{ block.sectionText }}

    {% default %}
      {% set entries = block.sectionArticles %}
      {% if entries | length %}

            {% for entry in entries %}
              {% if entry.section.handle == "news" %}
                {% include 'news/_includes/feed' %}
              {% elseif entry.section.handle == "pages" %}
                {% include 'pages/_includes/feed' %}
              {% elseif entry.section.handle == "events" %}
                {% include 'events/_includes/feed' %}
              {% endif %}
            {% endfor %}

      {% endif %}
    {% endswitch %}
{% endfor %}

The feed templates are just links and display fine.

The errors occurs on the events/_entry, news/_entry and pages/_entry templates. There is no references of the block 'sectionArticles' in those templates.

One more thing: the error only happens on scheduled entries, where the Post Date is in the future, after the Post Date has arrived.


texts:
Seeing as there currently isn't a way of deleting / managing tags in Craft3, I was wondering if someone could point me to where in the database these tags are stored so I can delete them manually.

Thanks in advance :)

edit:
Looks like tag management through the CMS is also on the agenda for version 3 as seen in this git issue.

https://github.com/craftcms/cms/issues/820


texts: How to Auto-Generate a Craft Commerce Product Title

texts:
How can I auto-generate the product titles in Craft Commerce? I'd like to auto-generate it from the post date and a custom field value. I can see how to auto-generate the SKU, but can't see how to do this for the product titles in the same way (like you can do for normal Craft entry titles).

I asked about this in the Craft Commerce Slack but didn't get a response, so just asking the question here instead. Thanks in advance for any help or possible workarounds.


texts: Is there a way to upload an asset with a URL?

texts:
I'm at the data entry stage of development and I've got a slew of entries with images to create. I'm stepping through the process manually and I'd like to use the URL of the image in the Upload files dialog instead of doing the download/upload rigamarole.

The images are on a server I don't have access to outside of their website. Ideally I would use the image URL in the Upload files dialog box instead of a local path and the image would be fetched and saved as an asset associated with the entry.

If this workflow seems parochial alternative solutions are welcome!


texts: Multiple sources on category field type - possible?

texts:
We're trying to setup a category field type to allow the selection of 1 category but from multiple category sources. Is there a simple way to achieve this without writing a custom plugin / fieldtype?

Currently we've set up 4 Category fields to allow a selection from the 4 sources with instructions to only use one of these fields at a time but it feels messy.  Thanks!


texts: How to use `{% cache %}` and `{% paginate %}` together?

texts:
When using cache tag with pagination should the tag go outside the pagination tag?

{% cache %}

    {% paginate craft.entries.section('employment').endDate('>= ' ~ now).limit(10) as pageInfo, pageEntries %}
    {% for entry in pageEntries %}

{{ entry.title }}

                        {% if entry.openUntilFilled %}
                            Open Until Filled
                        {% else %}
                            Job Closing: {{ entry.endDate.format('M j, Y') }}
                        {% endif %}

{{ entry.body|length > 1 ? entry.body|striptags|slice(0, 150) ~ '...' : entry.body }}

Read More

    {% endfor %}

        {% if pageInfo.prevUrl %}Previous Page&nbsp;{% endif %}
        {% if pageInfo.nextUrl %}Next Page{% endif %}

{% endcache %}


texts: Access site via local dev IP address => certain image path (xxx.dev) isn't replaced with IP address

texts:
I'm accessing my site through a local IP address (192.168.1.128:3000 that mirrors xxx.dev)

In my general.php I have these settings which work fine when accessed through IP =>

I then request for 2 image transforms (one non-retina, the other retina):

But when I check the rendered source code in the browser, I notice that only my retina (big format) doesn't have the IP address in it's path, how is this possible?

This isn't that big of an issue on my desktop because it will always find the xxx.dev, but when I try to test the site on my iPhone - through the IP address - it doesn't render the retina image because it can't find the xxx.dev

Any ideas on this one? Thanks in advance!


texts: Custom Messages including variables in global field?

texts:
Is it possible to setup messages (for transactional emails) as global text fields that include variables such as {{ firstName }}, {{ lastName }}, {{ email }} etc.?

For example:

Custom plugin fires off transactional email
Email copy is pulled from global text field
Variables like {{ firstName }} are substituted from plugin action
Email is sent


texts:
I'm trying to set up a past events archive. Followed the guide provided by PT: craft cms guide to set up an archive.

The only difference is that I use a custom date field (dateAndTime) and not postDate. The route leads to the correct template.

The issue

When it loads the archives/agenda/2018 template (f. ex.), it displays all 2018 events (grouped by month) but also all 2019 events that where entered in Craft in 2018. This under the correct month, but obviously the wrong year.
When it load the 2019 template, only the 2019 events that where entered in 2019 show up.
I can't figure out where the code is wrong.

Route

url: archives/agenda/year (token)
template: _sections/archives/agenda/index

Nav

{% set firstEntryEver = craft.entries.section('agenda').orderBy('dateAndTime asc').one() %}

    {% for year in now|date('Y') .. firstEntryEver.dateAndTime|date('Y') %}

{{ year }}

    {% endfor %}

Index

{{ year }}

    {% set entriesInYear = craft.entries.section('agenda').limit(null).after(year).before(year+1).all() %}
    {% for month, entries in entriesInYear | group("dateAndTime|date('F')") %}

{{ month }}

            {% for entry in entries %}

{{ entry.getLink() }}

            {% endfor %}

    {% endfor %}


texts: Are there any file-based static cache options for Craft CMS?

texts:
Is there an option for storing the pages generated by Craft CMS as flat, static HTML files?

The model used by static driver from ExpressionEngine's CE Cache add-on works pretty well:

Each page request hits a mod_rewrite rule, which checks to see if an HTML file for that page exists in the static cache directory.

If said file exists, it gets served to the browser.

If the file doesn't exist, the CMS generates the output, which is then saved as a cache file for the next user who hits that URL.

It only works in cases where the entire page can be saved, but, it's insanely fast and pretty easy to implement compared to other caching solutions.

... is there anything like that available for Craft CMS?


texts: Trying to capture categories field type data in user profile save/update

texts:
I am trying to capture the data that is selected when a user selects categories within a categories field type (handle: groups) within the Control Panel profile tab.

I was looking thru the Fields, Categories and Content services documentation in the craft docs section and I am still unsure.

I noticed when I did a var_dump of $user:

$user = UserModel::populateModel(UserRecord::model()->findById($id));

It displays the field 'groups' within the _attributeConfigs, but does not show up in private '_attributes' (Craft\BaseModel)

The other fields do show up, for example, occupation shows up within both the _attributeConfigs (its a string) and shows up in private '_attributes' (Craft\BaseModel) with a value of 'Teacher'.

I am unsure how to get the data the user selected when selecting the categories while updating their profile within the control panel.


texts:
How do I group entries by section? I have search results:

{% set entries = allowedSearchableEntries.search(query).order('score').limit(100) %}

But I want to have

SECTION NAME
entry 1
entry 4
entry 6

SECTION NAME
entry 3
entry 12

etc.


texts:
I have a Freeform Email Notification getting sent out where I'm trying to fetch the ID of a specific entry that the Email is associated to. The emails are working, yet the entry that it's returning is completely wrong - yet the ID is right. I don't have a clue what's going on!

{% set entrynumber = submission.entry %}
{% set proposalEntry = craft.entries.id(entrynumber).first() %}
{{ entrynumber }}
{{ proposalEntry.id }}
{{ proposalEntry.title }}
{{ proposalEntry.author }}
{{ proposalEntry.proposalCampaign }}

The above produces the following:

441
471
Domino's Pizza New Yorker range
admin

As you can see, it's the wrong entry that it's calling? It looks like it's just using the latest entry?


texts:
I'm trying to pull entries from an events channel where a date field falls in the current month.  Through google and other SE posts I've gotten to the following code:

{% set currMonth = now|date('m') %}
{% set currMonthFirst = currMonth ~ '/1/' ~ now|date('Y') %}
{% set nextMonthFirst = currMonthFirst|date_modify('+1 month') %}

{{ currMonthFirst|date('m/d/Y') }} - {{ nextMonthFirst|date('m/d/Y') }}

{% set events = craft.entries.section('events').event_startDateTime('>= ' ~ currMonthFirst|date('m/d/Y') ~ ', <' ~ nextMonthFirst|date('m/d/Y')) %}

{% for event in events %}

{{event.title}}

{% endfor %}

currMonthFirst and nextMonthFirst both output the dates I'd expect, but when I use the set & for loop I get the following error - Fatal error: Call to a member function getTimestamp() on a non-object.  Any idea what I'm doing wrong here or how to make what I'm trying to do work?


texts: How do you eager load or join reverse relationships for entries?

texts:
So I have structures that are related in the follwing way:

Locations has many Providers
Providers has many Health Topics

I know that I can eager load all Locations with related Providers and Health Topics very easily using using something like this:

craft.entries.section('locations').with(['providers.healthTopics']).all()

However how can I eager load the reverse relationship, loading all Health Topics with their related Providers and Locations? The eager loading function seems to go from parent to children but not from children to parent...though I could be missing something there?


texts:
I've read through the docs but can't figure out what I'm doing wrong here:

I'd like to display a list of entries by tag, where the tag is in segment 2 of the url.

Here's what I've tried and is not working (they output nothing):

{% set secondSegment = craft.app.request.getSegment(2) %}

{% set diaryEntries = craft.entries.section(['gardenDiary','gardenInfo']).relatedTo({
        sourceSite: craft.app.sites.currentSite.id,
    element: secondSegment,
    field: 'gardenTags'
}).limit(null).all() %}

Also tried:

{% set diaryEntries = craft.entries.section('gardenDiary').relatedTo(secondSegment).all() %}

...

{% for entry in diaryEntries %}
{{ entry.title }}
...etc...
{% endfor %}

Entries are known to be related to tags
I've tried adding a known related tag directly - still nothing.
If I don't specify a tag, it lists all the entries.
Example URL: mydomain.com/tags/fruit
Template is loaded via a Route: [Global] tags/* -->  tags/index.html

What am I doing wrong? Thanks in advance.


texts: Need somebody to help us with our existing Craft web page

texts: Our developer has disappeared and we need some help in changing and adding a few things on our website (www.fincarosablanca.com)? Would like to have somebody in Costa Rica but it doesn't really matter.


texts: Include Time In PostDate/DateTime Field Control Panel Display

texts:
In Craft 3 if you use a DateTime field and have it set to time only, it still displays as a date in the Control Panel with no time.

Even if it is used as a date and time field, just like entry post date it will only display time if it's on the current day.

Is there a way to modify this format to include the time in the control panel display?


texts: Impossible to invoke a method on a null variable

texts:
I call a asset like this:

{% set headImage = entry.geschaeftsbereichHeadImage.first() %}
<img src="{{ headImage.url(headBanner) }}"

If I don't ad any image to this field there is a twig error:

  Impossible to invoke a method ("url") on a null variable

When I don't ad any Image to this field in the CP shouldn't there be just no image? Why the error? If I ad a image it works just fine.


texts: What could the possible causes be for a mismatch between `craft_fields` and `craft_fieldlayoutfields` MySQL tables?

texts:
I'm debugging an Internal Server Error on a site developed by, well, not me. :p The site has an absolutely enormous Matrix field called "Modules", and the blocks in said field have so many fields that it reaches some sort of "65,536 char row limit" in the database when trying to add new fields.

Anyway, so the most recent block added to this giant Matrix field causes an internal server error whenever it gets added to an entry. The relevant web.log line is:

2018-08-20 09:25:06 [127.0.0.1][206][h9dtcm3ad2nb50aie3m6t27be3][error][yii\base\Exception] yii\base\Exception: Invalid field handle: resource2Description in [MyProject]\vendor\craftcms\cms\src\base\Element.php:1932

This was odd, as the Matrix block in question didn't have a "Resource 2 Description" field in the backend. It did, however, have "Resource 1 Description" (and 3 other "Resource 1 ____" fields), and the development pattern I've seen in this site leads me to be nearly certain that at some point, someone tried to add or succeeded in adding a "Resource 2 Description" field (side note: consider this my +1 for Matrix-within-Matrix, and yes, I will be converting this morass to Super Table for the time being).

So this led me to poking around the database, trying to figure out why parts of Craft thought this field existed, but it wasn't being shown in the backend.

What I found was that the Matrix block in question, which has a tabId of 3275 as referenced in the craft_fieldlayoutfields table, has only 4 rows in that table (one for each field seen in the backend):

However, when I looked up those field IDs in craft_fields, I saw that they had a common context column, of matrixBlockType:78. Querying that table for all rows with that same context, I found the mystery fields:

So at this point I have two theories about what happened:

Option 1: Craft may have a bug of sorts where, if you try to add fields but hit that previously-mentioned 65,536-char row limit, the fields only get partially added to the database and you end up with a mismatch between tables.
Option 2: This site had, at one point, upwards of 15,000 rows in the craft_queue table, due to some stuck 'Pending image transform' tasks that the developers had ignored during development. This was "resolved" by wiping out the contents of craft_queue wholesale. I suspect that one of those tasks may have been something to do with saving or updating the fields in the Matrix block.

So the actual question is this: Which of those two scenarios (or some other cause I've not thought of) are more likely to result in mismatching database tables?

Bonus question at no extra charge: Which would be wiser, A) Manually (editing the database) "restoring" the missing rows for those fields in craft_fieldlayoutfields, B) Manually deleting those "extra" rows in craft_fields, or C) Trying to recreating those fields as normal, through the Craft backend?


texts: Create a specific order of paginated entries by entry type

texts:
I am working with a design that requires entries to be laid out on a listing page in a specific order based on whether they are "Standard" or "Premium". The order of the paginated listing page is as follows:

Standard, Standard,  Premium
Standard, Standard, Standard, Standard
Premium, Standard, Standard
Standard, Standard, Standard, Standard
Pagination

There could be a number of approaches with how I store the entries but my approach has been to set up a channel section "Offers" with two entry types "Standard" and "Premium". If the layout was not important I have the following working:

{% paginate craft.entries.section('offers').limit(14) as pageInfo, pageEntries %}

{% for entry in pageEntries %}
  {% if entry.type == 'premium' %}
    {% include "_includes/offers/listing-card-premium" %}
  {% endif %}
  {% if entry.type == 'standard' %}
    {% include "_includes/offers/listing-card" %}
  {% endif %}
{% endfor %}

{# PAGINATIOIN NAV HERE #}

My question is, how do I achieve the above but using the specific order I need, whilst still paginating the entries and keeping track of what's been displayed.


texts: GraphQL - Get related entries based on tags field

texts:
I'm trying to retrieve entries related to the current entry, based on a tag field called topics. Simple stuff.

Now, I use Craft's native GraphQL implementation so I'm bound to the possibilities this interface gives me. In twig, it would be quite easily solved as described in the following topic: Search for related entries based on tags

It seems like the relatedTo property of the entries() query only supports a single ID, without the ability to scope my results based on a certain field. I would expect to be able to do something like the following:

entries(
    section: "article",
    limit: 2,
    relatedTo: {
        sourceElement: 123, // ID of the current entry
        field: 'topics'
    }
) {
    id,
    title
}

This just gives me the following error: Expected type [Int], found {sourceElement: 123, field: \"topics\"}.

Now, if I resort to the documentation it indeed describes that only an entry's ID can be used as the value of relatedTo, like this:

query QueryName {
  entries(
      section: "article",
      limit: 2,
      relatedTo: 123 // Current article ID
  ) {
      id,
      title
  }
}

This does work (it doesn't error), but results in an empty entries array. Even though there's entries that have the same topics (tags) assigned to them.

I'm kinda lost on how to actually retrieve related entries. Should I just revert to using the search param and feed it a concatenated list of the current post's tags?

Any elegant solutions would be greatly appreciated!

Thanks in advance!


texts: Insert action in front of template, while maintaining entry slug

texts:
We are attempting to implement a number of Pardot forms within Craft templates.  Since Pardot's form actions do not allow us to dynamically specify a return URL, our best choice is to use the form's URL as the return URL.

Our page is /about/contact.  We want one of three things to happen on this page:

If the user has an identifying cookie on their machine, display only a comment field, for example
If the user does not have a cookie saved, display the complete form
If the user is returning from Pardot, set a cookie and display a thank you message.

It's important to us that we maintain pretty URLs, so we have created a route in routes.php:

return array(
  'about/contact' => array('action' => 'pardotForm/ManageForm'),
);

Our contact page is an entry in our Landing Page structure.  We've set that entry's slug to be something random so that Craft does not route to the default controller for that entry.  It is set to "contact-us-page".

We would like to maintain the actual slug on the contact page as "contact" so that we can use slug features in normal ways.

Is there any possible way to maintain our slug as "contact", our url as "about/contact", and still route to our 'pardotForm/ManageForm' action?


texts: Different behavior when looping through a list of variables

texts:
I apologize for the seemingly vague title, but I honestly don't know the best way to state this problem succinctly!

This is within the context of a particular section's entry template.

What I want to happen:

I want to loop through a list of variables that call different Entry elementCriteriaModels and for each iteration of this loop I want to get the section's handle.

How I tried to make it happen:

Get related entries from a number of different sections

{% set towns = craft.entries.section('towns').relatedTo(county) %}
{% set citizens = craft.entries.section('inductees').relatedTo(county) %}
{% set events = craft.entries.section('events').relatedTo(county) %}

Make a list of those elementCriteriaModel objects

{% set arrayOfSections = [
    towns,
    citizens,
    events
] %}

Loop through that list and try to get the section handle of whatever the first entry is of each section

{% for section in arrayOfSections %}
    {% set sectionHandle = section.first().getSection() %}
    {{ sectionHandle }}

What actually happens

I get the following error: "Impossible to invoke a method ("getSection") on a null variable."

When I try to do the same thing on an object that is outside of that arrayOfSections list, it works just fine!

Why am I even trying to do this??

There is a huge part of this template that repeats itself over and over. If I can successfully loop through these related sections in this way that problem will be fixed. I've thought about turning this into a macro, but I'd still have to call this macro nearly half a dozen times and manually feed in the desired section each time...


texts: Querying channel entries hits memory limit

texts:
We have a channel that has about 700 entries but is paginated with a limit of 30 entries. Our client is looking to add a button so users can print out all entries. One of our proposed solutions was to redirect to a stripped down page (no header, footer, etc.) with all of the filtered entries that automatically engages the browser's print method. The problem is if no filters have been applied, Craft can't handle 700 entries (I've tested a bit and 130 seems to be the limit).

How should one go about this? Is upping our memory limit (currently 128M) the only way around this? Would it be better to generate a JSON object on channel entry save that we could then load in the print page's template?

Any suggestions would be appreciated!

EDIT

Here is some additional information. The page is basically just a list of companies. There is a field for the company's name, address, contact name, telephone, email, website, type (category), country (category), and also SEOmatic (which we obviously don't need to display). I haven't actually looked at the tables, though.

The error I am getting:

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 79 bytes) in /Library/WebServer/Documents/site/craft/app/fieldtypes/PlainTextFieldType.php on line 59

EDIT 2

Channel: Companies

Field Layout:

Meta: SEOMatic (don't need to output)
Company Name: Plain Text
Company Address: Plain Text
Company Contact Name: Plain Text
Company Email: Plain Text
Company Telephone: Plain Text
Company Website: Plain Text
Company Type: Category (there can be MULTIPLE types, doesn't have any fields associated with it)
Company Country: Category (there can only be ONE type, doesn't have any fields associated with it)

Categories:

Company Types
Company Countries


texts:
This question is a follow up of a previous question see: (Entry Form - Multiple Entries & Entry Type & Parent)

I am trying to add multiple children to a pre-existing multi level structure:

Level 1
--Level 2 (The parent where I am adding the children)
----Child 1
----Child 2
..etc

My Controller:

public function actionSaveAnimals(){
$this->requirePostRequest();

if($rodentsData = craft()->request->getParam('rodent')){
  $rodentErrors = [];
  foreach ($rodentsData as $rodentData){
      if (array_key_exists('entryId', $rodentData) && $rodentId = $rodentData['entryId']) {
          if (!$rodent = craft()->elements->getElementById($rodentId)) {
              throw new Exception('Could not find rodent with the given Id');
          }
      } else {
          $rodent = new EntryModel();
          $rodent->typeId = 6; // change your entryType Id here
          $rodent->sectionId = craft()->request->getParam('sectionId');
          $rodent->parentId = craft()->request->getParam('parentId');
          $rodent->authorId = craft()->request->getParam('authorId');
      }

      $rodent->getContent()->setAttributes($rodentData['fields']);

      if (!craft()->entries->saveEntry($rodent)) {
          $rodentErrors[] = $rodent->getErrors();
      }else{
          $rodentErrors = [];
      }
  }
  // include errors of each item
  craft()->urlManager->setRouteVariables(array(
      'rodentErrors' => $rodentErrors
  ));
}

}

And my form:

<form method="post" accept-charset="UTF-8">
{{ getCsrfInput() }}
{# your plugin name and function name #}
<input type="hidden" name="action" value="experiment/SaveAnimals">
{# the id of your section for me its 4 you need to change this value to your section Id #}
<input type="hidden" name="sectionId" value="4">
{# enable the entry #}
<input type="hidden" name="enabled" value="1">
{# id of your entry leave it blank to insert a new entry, insert a id to change an existing entry#}
<input type="hidden" name="entryId" value="">
<input type="hidden" name="parentId" value="{{ entry.id }}">
<input type="hidden" name="authorId" value="{{ currentUser.id }}">

    Amount of Animals
    {#<input class="pa3 input-reset ba bw0 br2 w-100" type="number" id="Cage__Amount" placeholder="5" max="10" required>#}
    <input type="text" name="rodent[0][fields][title]" value="Add Identifier">
    <input type="text" name="rodent[1][fields][title]" value="Add Identifier">

  <button class="bg-dark-blue white ph3 pv2 input-reset pointer ba bw0 f5 dib lh-copy w-100" type="submit">Create experiment</button>

I am currently getting this error:

Trying to get property of non-object

From EntriesService.php(468)

if ($entry->getSection()->type != SectionType::Structure)

Any help much appreciated!


texts: How to extend Craft.BaseElementIndex for a custom Element Type

texts:
I have a custom Element and need to modify the Element Index page. I'm attempting to extend Craft.BaseElementIndex and register the extended class on my Element Index Page. I'm working on a plugin for Craft 3. Something similar seems to be working fine in Craft 2, but I'm not sure if this is really a version issue or just an issue with my implementation.

Something like this:

(function($){
    Craft.MyCustomPlugin.MyElementIndex = Craft.BaseElementIndex.extend({
      getDefaultSort: function() {
          return ['elements.dateCreated', 'desc'];
      }
    });

    Craft.registerElementIndexClass('mynamespace\\elements\\MyElement', Craft.MyCustomPlugin.MyElementIndex);
})(jQuery);

The javascript file seems to load however doesn't have any effect on the Element Index page.

If I add an init method with a console.log() statement, a message gets logged but then the results on the Element Index page don't load anymore.

(function($){
  Craft.MyCustomPlugin.MyElementIndex = Craft.BaseElementIndex.extend({
    init: function() {
      console.log('Who cooks for you?');
    },
    getDefaultSort: function() {
        return ['elements.dateCreated', 'desc'];
    }
  });

  Craft.registerElementIndexClass('mynamespace\\elements\\MyElement', Craft.MyCustomPlugin.MyElementIndex);
})(jQuery);

Any ideas on what I'm missing?


texts: Normalize then validate unique entry in a custom module field

texts:
I have a custom text field in a module that the user populate with an EAN number. The input is getting validate by a "match" validator and then is serialized before save to get ride of the various variants of the EAN the user can enter ("978-2-87929-647-0", "978.2.87929.647.0" and so on…).
But now I need to validate is uniqueness and I can't find the right way to do this.

How can I normalize the input and then test if this normalized value already exists in the DB?

I cannot find a way to get the actual user input and normalize it before validate it.

I guess I have to use the "UniqueValidator" to test if the entry already exists in the DB.

Thanks for your help.


texts: How to show entries which are live between dates regardless of postdate or expiry dates?

texts: I'm trying to show live entries to user by selecting list of months in a dropdown. Some my entries are live for 2 or 3 months. I having trouble in finding right method. I have tried using after and before but i think these work based on postdate of an entry. Correct me if i'm wrong. This all in template side.


texts: Export more than 50 Freeform submissions (without a lot of scrolling)

texts:
We've got a site with several Freeform forms, and my client has noticed that when they use Freeform's "Export CSV" they only get the first 50. That's because you need to select all the submissions, then export them – and if you've not scrolled down several times to force all of the other entries to load in, you'll only get the 50 that were initially shown.

Does anyone know a way round this? If you've got hundreds of submissions it feels a bit clunky to have to trigger the AJAXing in of entries before you can export them.

We're on Craft 2.6.3011, Freeform 1.8.6.

Thanks!


texts: Browser limited 400 error when logging in

texts:
At random times local sites don't allow me to login to admin with certain browsers. Currently I cannot login to a site using Chrome, but can using Firefox. I have had sites that won't login with Firefox, but do with Chrome.
The error is a browser console error, not a Craft/Twig error:
Failed to load resource: the server responded with a status of 400 (Bad Request)
I've renamed and deleted cpresources (as another post had mentioned to try), but this didn't work.
It happens at random points too. I can login fine then come away from my PC for a few minutes to return to a login screen and not able to login.


texts: How to create an auxiliary page with sub url?

texts:
I have a section where each item has its own URL e.g:
news/{slug}

The Entry Template for this section is:
news/news_detail

For each post I would like to have a link to a unique page which is populated with information from the fields from the parent post/group, e.g news.

The slug would look something like:
news/{slug}/extra

The Entry Template for the news_detail page has a rich text field:
additional

To make this more complicated, the link to this page will be visible only if the "additional" field is populated with data.
And finally each "extra" page should have a link back to the originating post.

I had considered using a simple JavaScript toggle, but having urls for the content is more important in this instance, so not an option.

Thank you for any pointers as I am not sure where to start.


texts: How do I create an index page that loop through the table fields of its entries?

texts:
Every entry in a section has a table.  The table depicts sales over 7 years.

I want to create an index page that lists the title of each entry and the sales for each entry in the section.

I know how to loop through the table fields to template the table for each entry.

I know how to loop through the titles of each entry to create an index page.

But, how do I create an index page that loops through the table data for each entry?

Simple index loop:

{% for item in craft.entries.section('widgets').all() %}

{{ item.title }}

{% endfor %}

The entry table format is as follows:

{% set field = craft.app.fields.getFieldByHandle('budgetTable') %}

                    {% for column in field.settings.columns %}
                    {{ column.heading }}
                    {% endfor %}

                {% for row in entry.budgetTable %}

                    {{ row.widgetTitle }}

                {% endfor %}


texts: How do I get Craft custom settings from inside a module?

texts:
Additional settings added to config/general.php are placed in _customSettings private object.

This means they cannot be retrieved using Craft::$app->config->general->someCustomSetting.

How can I access them?


texts:
How can I filter a for loop based on the value of a field?

I tried filterByValue, but I do not know how to construct the statement.

This is NOT a category field.

I have this...

{% for line in craft.entries.section('docs').filterByVale('account: 05').all() %}
    {{line.lineItemTitle}} ({{line.lineItemTitle}}),
{% endfor %}

How do I do this?

Thanks


texts:
I'm having an issue with Craft 2.6 and the CSRF token. I enabled Csrf Protection in my general.php file by adding this line $config['*'] array so it looks like:

$config['*'] = [
...
    'enableCsrfProtection' => true,
...
],

I also tried adding this line to the section for // Global variables after this array, but still no luck. I try to attach the token to the window object like this:

<script>
        window.csrfTokenName = "{{ craft.config.csrfTokenName }}";
        window.csrfTokenValue = "{{ craft.request.csrfTokenValue }}";
</script>

and the window.csrfTokenName = "CRAFT_CSRF_TOKEN"; but window.csrfTokenValue = "";

I can't figure out how else to get a csrf token and I can't find any documentation that says anything else. I'm just trying to see if I'm missing something really easy or if there is actually something else I need to add. Any help is greatly appreciated!


texts: Assets uploaded image quality is terrible

texts:
When I upload a JPG image through Assets, the image quality is terrible. I dont mean a slight difference for web optimisation, but I mean REALLY bad! See screenshot.

Can't find any helpful about this issue which is strange. A few other posts mention the issue with image transforms, but this is not an image transform, its just the main image uploaded. Opening the image direct on the server shows this bad image so the original is clearly processed. I would not want our images processed if it affects quality (we optimise images ourselves).

I have not done much at all really, no plugins/modules added yet, just a basic template and a few text and asset fields. Its just to demonstrate Craft to a customer at the moment.

I have many CMSs on this server, like Wordpress and other Craft 2 installs, and we don't get this issue with other systems.

I have GD installed, I would prefer to keep that and not use ImageMagick, shouldn't have to use any image processing for just image upload should I?

Interestingly, if I open the original image on my computer and do a screenshot and create a new image from that, then upload that new image, it does not have such bad quality, it looks OK. So maybe its something inside the image. But the images are already used on another website (Wordpress) fine. I was hoping I can just import the images into Craft and not have to do any manual processing first.

Photoshop shows the image as RGB colour at 8 bits.

GD Spec from in Craft PHP Info:

GD Support  enabled
GD Version  bundled (2.1.0 compatible)
FreeType Support    enabled
FreeType Linkage    with freetype
FreeType Version    2.4.11
GIF Read Support    enabled
GIF Create Support  enabled
JPEG Support    enabled
libJPEG Version 6b
PNG Support enabled
libPNG Version  1.5.13
WBMP Support    enabled
XPM Support enabled
libXpm Version  30411
XBM Support enabled
WebP Support    enabled
gd.jpeg_ignore_warning  0

Thanks

Update July 24th 2019: Issue now gone, see comment below for further info.


texts: Validate a lineItem option within a plugin?

texts:
I have a lineItem option that needs validation. It’s actually an input field that can’t be blank, and different to the lineItem’s note.

The docs for Add to Cart mention using onBeforeAddToCart but it also needs to be validated if a customer decides to edit this field in the cart so perhaps commerce_cart.onBeforeAddToCart is not the right event here.

Can anyone offer an example of how to do this? This needs to be server-side validation, not front-end.


texts: Getting environmental variable via plugin

texts:
A similar question was answered before, but I was wonder how I might be able to return the same query from within a plugin (php)?

Convert this:

{{ craft.config.environmentVariables.baseUrl }}

To something like this: (not correct)

return craft()->config->get('environmentVariables.baseUrl');

What would be the correct syntax?

Thanks, Mark.


texts: Order PDF in back-end error with Globals

texts:
I have created a PDF template for orders and this works fine on the front-end. However, when I click to Download  PDF through the admin panel in an order. I get an error that:
Variable "companyInfo" does not exist

companyInfo is a global field - I am using it to populate the company invoice details like so;
{{ companyInfo.companyName }} (there are several of these).

Any ideas why this is an issue on the back-end and not the front-end and how to resolve?


texts: How to get next entry by date in matrix block but limit to just 1

texts:
I need to display a block from a matrix for the following week.

Basically the query I need to build is

{% for block in workshop.workshopSession.where(sessionDate > now).first() %}

I just can't quite get this to work and have been searching for a while. Perhaps I am just missing something obvious. There will be more than one entry with a date greater than "now" so I need to limit it to 1.


texts:
Folks:

I figured this would be simple but apparently not (for me, anyway).

I have a product with two variants (orange and yellow).
I have a page that lists all the available products.
On that page, both variants appear. I really just need one and users
can select their variant from a drop-down on the checkout page.

What I've got:

{# get the products from the categories #}
{% set products = craft.commerce.products.type('shirts,shorts') %}

{# show the product main image and link to the product page #}

    {% if product|length %}
        {% set asset = product.productHeroImage.first() %}
    {% endif %}

I did try {% set products = craft.commerce.products.defaultVariant.type('shirts,shorts') %} but get the same results.


texts: Access logged-in user info when `baseCpUrl` is different than `siteUrl`

texts:
Our site's control panel needs to be on a subdomain for security purposes. So our baseCpUrl setting in our general.php file is http://craft-admin.domain.com/ while our siteUrl is set at http://www.domain.com/.

I'm not able to access user information (specifically if a user is logged in and has accessCp permissions) on the main site. Dumping user information on a template is giving me NULL, I assume because there's no connection being made between craft-admin.domain.com/ and www.domain.com/, so pages on www.domain.com can't tell me anything about logged-in users.

I ran into this trying to add in the Admin Bar plugin so logged-in users can have quicker access to the Control Panel edit screen for a particular page if they're viewing it on the public-facing site. However, since there's no user information being passed along, the admin bar will never show up because it assumes I'm just a regular person browsing the site.

Is there something else I need to do in order to access logged-in user information on the front end if the baseCpUrl is different than the siteUrl?


texts: 500 Internal Server Error when accessing admin

texts:
I just get a server error when trying to access /admin, or any other URL. This is a completely new installation on a staging server. The 'Welcome' page shows OK.
I'm guessing this is a .htaccess problem, because if I remove it and change 'omitScriptNameInUrls' to false the login page shows - but unstyled. If I login I get 400 bad request.
I've looked in the web.log, but can't see anything to help there.
The hosting company is IONOS (1&1).
Any ideas?


texts: Database Query in debugger consistently showing over 2000ms

texts:
In trying to optimize my Craft 3 site, I have discovered that it's apparently taking longer than expected to query my database. The duration for the apparent culprit is typically between 1900 and 2300ms alone.

The query is as follows:

SELECT
`kcu`.`CONSTRAINT_NAME` AS `name`,
`kcu`.`COLUMN_NAME` AS `column_name`,
`tc`.`CONSTRAINT_TYPE` AS `type`,
CASE
    WHEN NULL IS NULL AND `kcu`.`REFERENCED_TABLE_SCHEMA` = DATABASE() THEN NULL
    ELSE `kcu`.`REFERENCED_TABLE_SCHEMA`
END AS `foreign_table_schema`,
`kcu`.`REFERENCED_TABLE_NAME` AS `foreign_table_name`,
`kcu`.`REFERENCED_COLUMN_NAME` AS `foreign_column_name`,
`rc`.`UPDATE_RULE` AS `on_update`,
`rc`.`DELETE_RULE` AS `on_delete`,
`kcu`.`ORDINAL_POSITION` AS `position'
FROM
`information_schema`.`KEY_COLUMN_USAGE` AS `kcu`,
`information_schema`.`REFERENTIAL_CONSTRAINTS` AS `rc`,
`information_schema`.`TABLE_CONSTRAINTS` AS `tc`
WHERE
`kcu`.`TABLE_SCHEMA` = COALESCE(NULL, DATABASE()) AND `kcu`.`CONSTRAINT_SCHEMA` = `kcu`.`TABLE_SCHEMA` AND `kcu`.`TABLE_NAME` = 'resourcepaths'
AND `rc`.`CONSTRAINT_SCHEMA` = `kcu`.`TABLE_SCHEMA` AND `rc`.`TABLE_NAME` = 'resourcepaths' AND `rc`.`CONSTRAINT_NAME` = `kcu`.`CONSTRAINT_NAME`
AND `tc`.`TABLE_SCHEMA` = `kcu`.`TABLE_SCHEMA` AND `tc`.`TABLE_NAME` = 'resourcepaths' AND `tc`.`CONSTRAINT_NAME` = `kcu`.`CONSTRAINT_NAME` AND `tc`.`CONSTRAINT_TYPE` = 'FOREIGN KEY'
UNION
SELECT
`kcu`.`CONSTRAINT_NAME` AS `name`,
`kcu`.`COLUMN_NAME` AS `column_name`,
`tc`.`CONSTRAINT_TYPE` AS `type`,
NULL AS `foreign_table_schema`,
NULL AS `foreign_table_name`,
NULL AS `foreign_column_name`,
NULL AS `on_update`,
NULL AS `on_delete`,
`kcu`.`ORDINAL_POSITION` AS `position`
FROM
`information_schema`.`KEY_COLUMN_USAGE` AS `kcu`,
`information_schema`.`TABLE_CONSTRAINTS` AS `tc`
WHERE
`kcu`.`TABLE_SCHEMA` = COALESCE(NULL, DATABASE()) AND `kcu`.`TABLE_NAME` = 'resourcepaths'
AND `tc`.`TABLE_SCHEMA` = `kcu`.`TABLE_SCHEMA` AND `tc`.`TABLE_NAME` = 'resourcepaths' AND `tc`.`CONSTRAINT_NAME` = `kcu`.`CONSTRAINT_NAME` AND `tc`.`CONSTRAINT_TYPE` IN ('PRIMARY KEY', 'UNIQUE')
ORDER BY `position` ASC

I'm not having much luck in figuring out how to fix this, and as I understand it, there's not a lot that can be done on Craft's end, but I'm at a loss as to where to go next. I've moved over to a VPN (Dreamhost) and I've added the following to my config/app.php:

return [
'components' => [
    'db' => function() {
        $config = craft\helpers\App::dbConfig();
        $config['schemaCacheDuration'] = 60 * 60 * 24; // 1 day
        return Craft::createObject($config);
    },
  ],
];

Any thoughts on where to go from here? Any ideas would be greatly appreciated.

Thanks.


texts: Filtering values from Twig for my custom field type

texts:
I have a custom fieldtype for Craft which stores its value as an array of Models using AttributeType::Mixed. See below for an example of the FieldType and Model setup

class MyCustomFieldType extends BaseFieldType
{
    public function defineContentAttribute()
    {
        return AttributeType::Mixed;
    }
}

class MyCustomModel extends BaseModel
{
    protected function defineAttributes()
    {
        return array(
            'url'      => AttributeType::String,
            'category' => AttributeType::String
        );
    }
}

Then when the value is persisted, it's saved as an array, which Craft natively saves as JSON

$values = [new MyCustomModel(), new MyCustomModel(), ...];

To display the value in Twig I can do something like

{% for item in entry.myCustomField %}
    {{ item.category }}
{% endfor %}

My question is, how can I only display the elements in my field which have a specific attribute value? For example, if I wanted to display only those items with a category of main, where 'category' is an attribute on my model?

{% for item in entry.myCustomField.category('main') %}
    {{ item.category }}
{% endfor %}


texts: How to save dynamically created checkbox values in plugin settings?

texts:
I am in the early stages of developing a plugin for Craft 3. In its settings it should have a checkbox for each section the user has defined that enables the admin to select or unselect each section from processing.

I am struggling with saving the state of the checkboxes when these are created with a loop.

When I create the checkboxes individually it works:

SettingsModel.php:

class SettingsModel extends Model {
    public $sectionArticles = '';
    public $sectionResources = '';
    public $sectionMultimedia = '';
}

_settings.html:

{{ forms.checkbox({
    label: 'Articles',
    name: 'sectionArticles',
    checked: settings.sectionArticles,
}) }}

{{ forms.checkbox({
    label: 'Resources',
    name: 'sectionResources',
    checked: settings.sectionResources,
}) }}

{{ forms.checkbox({
    label: 'Multimedia',
    name: 'sectionMultimedia',
    checked: settings.sectionMultimedia,
}) }}

As one would expect, Craft successfully saves and retrieves the settings.

But when I create the checkboxes dynamically, saving their values fails:

SettingsModel.php:

class SettingsModel extends Model {
    public $sectionOptions = [];
}

_settings.html:

{% for option in settings.sectionOptions %}

    {{ forms.checkbox({
        label: option.label,
        name: option.name,
        id: option.id,
        checked: option.checked,
    }) }}

{% endfor %}

And the main plugin code that retrieves the settings and creates an array entry for each Craft section:

public function init() {
    parent::init();
    $settings = $this->getSettings();

    // Set settings for sections
    $settings->sectionOptions = $this->setSectionOptions();
}

protected function setSectionOptions() {
    $settings = [];
    $sectionConfig = $this->getSectionConfig();

    foreach ($sectionConfig as $key => $value) {
        array_push($settings, [
            'label' => $value['label'],
            'name' => $value['handle'],
            'id' => $value['id'],
            'checked' => false,
        ]);
    }
    return $settings;
}

protected function getSectionConfig() {
    // Get all sections that are channels
    $sections = \Craft::$app->sections->getSectionsByType(Section::TYPE_CHANNEL);
    $sectionConfig = [];

    foreach ($sections as &$section) {
        array_push($sectionConfig, [
            'label'=> $section['name'],
            'handle' => $section['handle'],
            'id'  => $section['id'],
        ]);
    }
    return $sectionConfig;

I have studied the docs and reviewed other plugins but was unable to find this use case.

What am I missing?


texts: Working locally after cloning Craft 3 from Hyperlane

texts:
I'm trying out the recommended Hyperlane hosting with Craft CMS. After installing on Hyperlane, I then clone the repo on to my local machine and run 'composer install'. That runs fine, and I create a .env file with my db connection details in it.

What happens next is I go to install on my machine by viewing the admin panel but I get the following:

Database Connection Error – craft\errors\DbConnectException
Craft CMS can’t connect to the database with the credentials in config/db.php.
↵
Caused by: Invalid Configuration – yii\base\InvalidConfigException
Connection::dsn cannot be empty.
in C:\Users\clive\OneDrive\Desktop\repos\projectname\vendor\yiisoft\yii2\db\Connection.php at line 602

If I add the database details to config/db.php myself, it works fine. It just seems to be a problem with fetching them from .env.

I'm using WAMP on Windows and have numerous Craft 3 projects already running. This same project is fine if I install locally from scratch. It's just when I start by cloning from Hyperlane.

Any ideas?


texts: Need to access year/month variable when grouping entries by date

texts:
Having issues trying to access the year & month variable when grouping entries by month-year. The code is outputting the desired results (ie. December 2014), however I would like to format the url by 'year/month'.

Archives

    Browse news & articles for the last year.

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

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

{{ date }}

{% endfor %}


texts:
So, I am new.  I want to display the 1-n most recent posts in the same category as the current entry (preferably excluding the current entry) -- i.e., I want to have a section with Other Similar Posts at the bottom of an entry page.

I only have one Category Group = beerStyles. There are multiple categories to choose from in beerStyles. Each news entry includes a field called "style" to assign a category from beerStyles. Each entry can have only 1 category.  (Note there is no entries field in news entry, just the style field to select a category form beerStyles.)

Related Posts

                {% set category = craft.categories.slug('beerStyles') %}
                {% set entries = craft.entries.relatedTo(category) %}
                {% for entry in entries %}

{{entry.title}}

                {% endfor %}

No error is thrown, but other news entries with the same category assigned are not appearing.  Nothing is appearing.

Any thoughts?  And thank you in advance for your time and assistance.

P.S.  I know I left off the .limit(x) to limit the number of posts  I just want to get it working first.


texts: What it "Assets in this source have public URLs" good for?

texts:
just a short question - what is "Assets in this source have public URLs" good for? Oh course, I can't use getUrl() in the templates, yes, but I can still get the filename etc. So I don't see the use of this parameter?

Another question: when I upload assets to craft, sometimes they are put in the folder I expect, sometimes craft creates a subfolder (named like the asset-id I guess) and puts the file inside that folder. In which case a subfolder is created?


texts: Dealing with listing multiple categories

texts:
I'm looking to use multiple category group as a navigation. The categories have 3 levels and will be listed depending on set variable. I can list all categories in the group with the following:

{% set categories = craft.categories.group('categories') %}

    {% nav category in categories %}

            {{ category.title }}
            {% ifchildren %}

{% children %}

            {% endifchildren %}

    {% endnav %}

However I would like to list only the third level categories after the top level and secondary level have been set. I've tried playing around with descendantOf but to no avail. Any help to point me in the right direction much appreciated.

---Final code----
After @damon input below this is what I ended up with more or less the same:

{# ---- Set Default Segment ---- #}
{% set segment = 'default' %}
{# ---- If url segment is set, set segment to it ---- #}
{% if craft.request.getSegment(2) %}
    {% set segment = craft.request.getSegment(2) %}
{% endif %}
{% set cat = craft.categories.group('categories').slug(segment).first() %}
{% for categories in craft.categories.group('categories').descendantOf(cat).level(2) %}
    {% if categories.getDescendants().total() != 0 %}
        {% for category in craft.categories.group('categories').descendantOf(categories.id).level(3) %}
            ...
        {% endfor %}
    {% endif %}
{% endfor %}


texts:
All of my assets have fields for alt text and I understand how to access that info from an asset field, but can not figure out how to do it when an image has been inserted using Redactor.

Any help will be much appreciated!


texts:
I'm using code I've been using to update existing entries for a while now and it's failing to fire following the 2.5 upgrade. Trying to figure out what might have changed, or if there's something I'm overlooking. I'm consistently getting the "not saved" response and seeing no update in the entry. showInInvestmentAdvisersReference is the new field I'm setting. I've got limit=1 set for testing purposes.

$entries = craft()->elements->getCriteria(ElementType::Entry);
$entries->section = 'referenceMaterials';
$entries->limit = 1;

$existingEntries = $entries->find();

foreach ($existingEntries as $existingEntry) {
    echo 'id: ' . $existingEntry->id . '
';

    $entryToSave = new EntryModel();

    $entryToSave = $existingEntry;

    // Setting these in case they're required to be set for saveEntry()
    $entryToSave->sectionId = 9;
    $entryToSave->typeId = 9;
    $entryToSave->authorId = 1;
    $entryToSave->enabled = true;
    $entryToSave->getContent()->title = $existingEntry->title;

    $entryToSave->getContent()->showInInvestmentAdvisersReference = 1;

    if ( craft()->entries->saveEntry($entryToSave) )
    {
        echo 'saved
';
    }
    else {
        echo 'not saved
';
    }
}

Is it me? Did something change? Happy to file a bug report but thought I'd start here first where code formatting is supported.


texts: Whats the best way to create short URL's

texts: I have a client that wants to create a short URL to an entry for a mail shot. What would be the best way to do this. I have the Reroute plugin installed which would work (setting to a 302 redirect) but I am wondering if that is the best approach.


texts: Output children of a structure section in reverse order

texts:
How do you output the all the children of a structure in a reverse order (assuming the children are limited to max depth).

Using the order parameter, Craft requires that you use a second parameter like "desc" after a primary order parameter (eg, "title"). This would look like:

craft.entries.section('volumes').order('title desc')

But what would be the primary parameter that would respect the natural structure order?

Or is there any other way?


texts:
I just uploaded my website on my server and I have a problem regarding the admin area. When I arrive on the /admin page, no CSS and no JS have been loaded (after inspection, they all 404'd).

Is there any way to fix this like in the general config ? Thanks a lot !

EDIT :

The .htaccess is working (404 act differently).


texts:
I've got a custom plugin where I'm trying to update a global variable. The variable field type is of type Entry

I'm getting the set using getSetByHandle then using getContent on the set. However, when I do a count on the retrieved content, the value is 1. I have about 10 global variables so would've expected a count of 10.

I'm clearly doing something wrong, so a nudge in the right direction would be appreciated.

Update

Here's the code I'm currently using

$global_set = craft()->globals->getSetByHandle('globalVariables');
$selected_poll = craft()->entries->getEntryById($poll_id);
$content = $global_set->getContent();
craft()->globals->saveSet($globalSet);

Update

I've also tried the following, with no luck:

$globalSet = craft()->globals->getSetByHandle('tempSet');
$content = $globalSet->getContent();
$content->currentItem = craft()->entries->getEntryById($itemID);
$globalSet->setContent($content);
craft()->globals->saveContent($globalSet);


texts:
I recently moved a Craft 2 install from a server running PHP 5.x to one running PHP 7.x. All seems to be well. The custom "system offline" message appears as expected when visiting the home page, anyway. It also appears when visiting a random URL.

But when visiting the admin URL I'm redirected to the installer. I'd obviously rather not do this as the system and DB are already there.

Do I have any options here?


texts: Get the variables of a loop from an include file

texts:
So my 1. file is "_overview-topicTeaser.twig" which is within a matrix:
{% include 'modules/module-squareteaser/_module-squareteaser' with {
  squareTeasers: block.topicTeaserItems.all(),
  squareteaserHeadline: block.topicTeaserItems.one().entryTopicHeadline
} %}

And my 2. file is "_module-squareteaser.twig":

    <div class="squareteaser__wrapper _parent-3-child">
      {% for item in squareTeasers %}

        {% include 'modules/module-squareteaser/_module-squareteaser-item' with {
          headline: squareteaserHeadline
        } %}

      {% endfor %}
    </div>

So i am looping in the 2. file the file "_module-squareteaser-item.twg" and want to put out the "squareteaserHeadline" in the frontend. But it always gives me the same headline from my first teaser in the loop, makes sense to me cause i am using the "one()" when i include the variable "squareteaserHeadline" in the first file.  But if i delete the "one()" i get nothing... so how do i get all teasers whith their own headline?


texts: How can I hide entries depending on which category they are associated with?

texts:
Right now, I have a staff profile page. Each person on the page has a category association (professional, leadership, student). When the students graduate, I want to add an 'alumni' category to their entry, and have them stop showing up on the active page. Right now I have student and alumni associated with the particular entry, and I want to hide all entries with the alumni category. Any idea how to go about this?

{% set leaderGroup = craft.categories.group('staffHierarchy').slug('leadership') %}
{% set leader = craft.entries.section('people').relatedTo(leaderGroup) %}
{% set staffGroup = craft.categories.group('staffHierarchy').slug('student') %}
{% set staff = craft.entries.section('people').relatedTo(staffGroup) %}


texts:
Folks:

When users visit the site only some of the images on the page show. Checking Chrome dev tools shows that the missing images are failing with "server unavailable" errors. The image is there if you go to it directly.

This appears to be random. Images show sometimes but not others. I have erased the cache, rebuilt the search index and the asset list. No change.

The client says that the site sometime fails completely but I have yet to witness this.

I have VPNed from various locations and it seems to be the same no matter where I'm coming from.

The hosting company says the only error they see is "image missing" and the DB connection is fine.

Any help would be great.