texts:
Given a structure that has, for example, three levels of content—how do I just iterate over it and create a nested
 reflecting the hierarchy and containing the title and slug (as a link) of each entry?

The following just gives me a flat representation of the structure:

People

        {% for entry in craft.entries.section('people') %}

{{ entry.title }}

        {% endfor %}


texts: Is it possible to configure the FileLogRoute?

texts:
I am trying to debug a "clean template cache" task that gets stuck. However, it only happens intermittently, and whenever I notice any errors has already been rotated out of the log files.

Is there a way to set the maxLogFiles of the FileLogRoute?  either through the config files, or through php code in a plugin?

(Setting $rotateByCopy to true would also be nice!)


texts:
I'm making a plugin that stores elements in fields and fieldGroups. When deleting one the elements with  the fields/field groups are being removed too.

But when deleting the whole plugin, those fields are still in the database. When reinstalling the plugin this makes it impossible to add the field with the same title again.

I've already added 'onDelete' things in all the records like this:

public function defineRelations()
{
  return array(
    'form'        => array(static::BELONGS_TO, 'PluginHandle_FormRecord', 'onDelete' => static::CASCADE),
    'fieldGroup'  => array(static::BELONGS_TO, 'FieldGroupRecord', 'onDelete' => static::CASCADE),
    'field'       => array(static::BELONGS_TO, 'FieldRecord', 'onDelete' => static::CASCADE)
  );
}

I've been searching the docs to see what actually happens when a plugin is being deleted, but can't find anything. Any ideas?


texts: Imagemanager plugin doesn't show up in toolbar

texts:
I have upgraded redactor 2 to redactor 3, since a lot of things had to be changed. Been fixing those and it works well. I have a problem with image manager plugin which doesn't show up in the toolbar.

Needed a help immediately.

Thanks.


texts: Frontend Profile - Listing out Radio Buttons

texts:
In the official documentation it explains how to let users customize user fields in the frontend, such as:

<label for="bio">Bio</label>
<textarea id="bio" name="fields[bio]">{{ currentUser.bio }}</textarea>

However I set some user profile fields that are Radio Buttons and can't find anywhere on how to output the field options in a form. I want to do something like:

<select id="radioButtons" name="fields[radioButtons]">
  {% for option in fields.profile.myRadioButtons %}
    <option value="option">{{ option | title }}</option>
  {% endfor %}
</select>

But obviously 'fields' isn't a twig variable. Is there a way to do something similar to the above?


texts: Get a key value from a JSON asset in PHP

texts:
I'm using the Apple News plugin to try and display a tweet that's been added as a JSON asset in a matrix field. The JSON looks something like this
{
    "title": "https://twitter.com/TehseenLadha/status/1291773476877959169",
    "description": null,
    "url": "https://twitter.com/TehseenLadha/status/1291773476877959169",
    ...
}

According to the Apple News Publisher docs, all you need is the tweet's URL. I'm trying to get it by converting the JSON file to a string with file_get_contents and then using json_decode, but it's not working. This is what I have in MyNewsArticle.php:
case 'tweet':
  $asset = $block->tweet->one()->getUrl();
  $string = file_get_contents($asset);
  $jsonArr = json_decode($string, true);
  $tweetUrl = $jsonArr['url'];

  if ($tweetUrl) {
    $components[] = [
      'role' => 'tweet',
      'layout' => 'tweetLayout',
      'URL' => $tweetUrl,
    ];
  }
break;

It's grabbing the correct URL of the asset, but fails with failed to open stream: Operation timed out on the $string = file_get_contents($asset); line. Apparently this is something to do with IPv4 vs IPv6? I'm not certain how to get around it though.


texts: Element API — Endpoint has an invalid elementType

texts:
I'm trying the Element API for the first time and getting this error message {"error":{"code":404,"message":"Endpoint has an invalid elementType"}}

I cannot for the life of me figure out what I'm missing... I've read the docs, followed the Mijingo "Creating an Element API video", read Andrew Welch's post (https://nystudio107.com/blog/lazy-loading-with-the-element-api-vuejs) and hunted through Stack Exchange but haven't came across any fixes.

This is from my current element-api.php file:

<?php
namespace Craft;

return [
    'endpoints' => [
        'api/news.json' => [
            'elementType' => 'Entry',
            'criteria' => ['section' => 'news'],
            'transformer' => function(EntryModel $entry) {
                return [
                    'title' => $entry->title,
                    'body' => (string) $entry->newsText
                ];
            }
        ],
    ]
];

Previously, I tried changing the code slightly to:

<?php

use craft\elements\Entry;
use craft\helpers\UrlHelper;

return [
    'endpoints' => [
        'news.json' => function() {
            return [
                'elementType' => Entry::class,
                'criteria' => ['section' => 'news'],
                'transformer' => function(Entry $entry) {
                    return [
                        'title' => $entry->title,
                        'url' => $entry->url,
                        'jsonUrl' => UrlHelper::url("news/{$entry->id}.json"),
                        'newsTitle' => $entry->newsTitle,
                    ];
                },
            ];
        },
    ]
];

but still no luck. With the second block of code the error message I get is Template not found: api/news.json

Apologies if I'm missing something completely obvious, this is the first time using the plugin, and I don't know PHP, but following along with the Mijingo video helped me understand what was going on.

If anyone has any suggestions to fix this that would be greatly appreciated!

Cheers


texts: What are Search Targets and Search Query Input in seomatic?

texts: I am not sure this is the right place to ask this question but I really need to know it, but I couldn't ask it on the plugin's Github as this is not an issue. I am new on Craft CMS and my client need SEOmatic installed on it. I have configured everything but I couldn't understand the need of Search Targets and Search Query Input in Site Meta Section. It would be very helpful if someone helps me out for this with some real-life examples.


texts: Craft chokes on rendering large amounts of entries?

texts: So I have a section with 900 entries and I tried to just list them all on the page but Craft seems to choke after about 200 and will just not render any of them. Although I probably don't need to output all 900 it would be good to know what the issue is here?


texts: How to prevent Craft from injecting scripts in the page?

texts:
I have a website that resides behind a static cache. Today, I realised that some of the cached pages contain this bit of JavaScript at the end:

<script type="text/javascript">
/*<![CDATA[*/
(function(){
    var XMLHttpFactories = [
        function () {return new XMLHttpRequest()},
        function () {return new ActiveXObject("Msxml2.XMLHTTP")},
        function () {return new ActiveXObject("Msxml3.XMLHTTP")},
        function () {return new ActiveXObject("Microsoft.XMLHTTP")}
    ];
    var req = false;
    for (var i = 0; i < XMLHttpFactories.length; i++) {
        try {
            req = XMLHttpFactories[i]();
        }
        catch (e) {
            continue;
        }
        break;
    }
    if (!req) return;
    req.open('GET', "https://allaboutberlin.com/index.php/actions/queue/run", true);
    if (req.readyState == 4) return;
    req.send();
})();
/*]]>*/
</script>

Since the page is cached, every page loads makes this HTTP request, and it could easily bring my website down if it gets a traffic spike. How do I disable this feature?


texts:
When trying to login to my live env on craft, I get the following error in the javascript console.

[Error] Failed to load resource: the server responded with a status of 404 (HTTP/2.0 404) (login, line 0)

This only happens in the live environment, which is weird because the DB and front-end code are synced between local and live. There is also a staging website where the login page works.


texts: Use of App::env() compared to getenv() since Craft 3.4.18

texts:
I've noticed since Craft 3.4.18 there is a App::env() function from craft\helpers\App::env(). This was created from the discussion here it seems: https://github.com/craftcms/cms/pull/5893
It seems getenv() can be problematic on multithreaded environments, which is why this change was made.
Should getenv() calls be replaced by App::env() in PHP code now, if using Craft 3.4.18 or above given the App::env() function will check $_ENV first then use getenv() as a fallback?


texts: How to filter entries by clicking multiple categories on front end

texts:
I would like to be able to filter my entries list by multiple categories on the front end. For example, if I first click a category button "lunge" then the results would show entries which are categorized as "lunge".  If I click a second category button labeled "dumbbell" then the results would be filtered more and show only entries that are categorized as both "lunge" and "dumbbell".

I found some similar threads but haven't been able to get the suggestions to work for me.  I believe I need to pass the categories into a URL query string like this:

www.website.com/training/exercise-list?q=lunge,dumbbell

where q is my search query parameter and lunge and dumbbell are the categories that were clicked.

Section is called exercisesDb
Category Group is calledtrainingCategoryGroup
Category Field in the section is called
trainingCategory

Thanks so much!


texts: Correct way of showing errors when editing profile via front-end form?

texts:
I've been looking at the following resources:

https://craftcms.com/docs/templating/user-profile-form

Allow user to change or delete their photo for their profile from the front end

Front end edit: entry doesn’t get saved

Front end registration form, no errors

To try and put together a profile editing page that returns errors once submitted, but can't seem to get it.

user is equal to either the currentUser or craft.users.id(craft.request.getSegment(3)).first()

<form method="post" accept-charset="UTF-8" enctype="multipart/form-data">

{{ getCsrfInput() }}
<input type="hidden" name="action" value="users/saveUser">
<input type="hidden" name="redirect" value="partners/view/{{ user.id }}">
<input type="hidden" name="userId" value="{{ user.id }}">

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

            {% for error in errors %}

{{ error }}

            {% endfor %}

    {% endif %}
{% endmacro %}

{% from _self import errorList %}

{{ dump(user.getErrors) }}

        First Name:
        <input id="firstName" name="firstName" autocomplete="off" type="text" data-parsley-required="true" value="{{ user.firstName }}">
        {{ errorList(user.getErrors('firstName')) }}

        Last Name:
        <input id="lastName" name="lastName" autocomplete="off" type="text" data-parsley-required="true" value="{{ user.lastName }}">
        {{ errorList(user.getErrors('lastName')) }}

        Email:
        <input id="email" name="email" autocomplete="off" type="email" data-parsley-required="true" data-parsley-type="email" value="{{ user.email }}">
        {{ errorList(user.getErrors('email')) }}

        User Photo:
        {% if user.photoUrl %}

            <input type="hidden" name="deleteUserPhoto" id="deleteUserPhotoInput" value="">
        {% else %}

        {% endif %}
            <input id="profilePhoto" type="file" accept="image/*" capture="camera" name="userPhoto" value="{{ (user.photoUrl ? 'Change Photo' : 'Upload') }}">
        {% if user.photoUrl %}
            Delete
        {% endif %}

        User Description
        <textarea id="userDescription" name="fields[userDescription]" autocomplete="off" data-parsley-required="true" value="{{ user.userDescription }}"></textarea>

<button type="submit" class="btn btn-solid">Save</button>

</form>

Could anyone point out where I'm going wrong, or provide a working example?

Many thanks!


texts:
I have had Craft CMS installed for a while. then today, I created some new pages, and pushed them with git to the templates folder, added them in sections etc, then, when I go to edit the entry, it comes out like this..?

That is my main sites styling/CSS, but craft shouldn't be using it...should it?

Every other admin page shows okay, and the frontend is fine... just when I edit the entries.


texts: Is it possible to output month names in my native language?

texts:
I'm doing this:

{# Get events from `events` section in desired sort order #}
{% set allEvents = craft.entries.section('events').order('eventsDate asc') %}

{# Loop through `allEvents` and print the list #}
{% for event in allEvents %}
    <li>{{ event.title }} - {{ event.eventsDate|date('j F, Y') }}</li>
{% endfor %}

I guess I can do something with this: http://php.net/manual/en/datetime.formats.date.php, but I need to display months in my native language, which is slightly different from how Craft outputs it.

For example I'd like it to say "7 des", not "07 dec", "15 mai", not "15th may" and so on.


texts: Commerce 2: How to get the tax amount of a line item, or the line item subtotal without taxes?

texts:
In Craft Commerce 1 we could get the tax amount for a line item by using

lineItem.tax

Now, in Craft Commerce 2, this always returns 0. How can I get a line item's (or variant's) tax amount, or subtotal without taxes, using twig?

EDIT: on top of that, the suggested method for getting a cart's total tax:

getAdjustmentsTotalByType('tax')

also returns 0, no matter whether there are tax adjustments.

EDIT 2: Following Robin Schambach's comment, when the tax amount is included in the price, passing 'true' as second option is necessary:

getAdjustmentsTotalByType('tax', true)

This returns the tax amount from the order or the lineItem, thanks Robin!


texts: Sprout SEO: Getting error on save, preventing updating "default" meta data

texts:
After creating a default meta entry in Sprout SEO. Any subsequent updates aren't saved and I get an error message "Couldn't save the default"

Using:

Craft 2.4.2725
Sprout SEO 1.1.1

Has anyone else come across this?


texts: Display events that appear at certain venue

texts:
I'm trying to work out how to query some channel posts (events) that take place at a certain venue.

{% set params = {
    section: 'events',
} %}

I have a 'eventVenue' field in my events section which is an entries field powered by a channel called venues. I want to query by venue ID?


texts: When is the find() method actually necessary?

texts:
I've noticed code samples like the following that use the find() method.

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

{{ entry.title }}

{% endfor %}

I've noticed that this code sample works just as well without the find() method attached. Is there a particular reason we use find()? Are there instances where it's required? Should I be using it even if the code works without it?


texts: Getting properties out from the Craft text object

texts:
I got this kind of object.

Craft\RichTextData Object
(
    [_pages:Craft\RichTextData:private] =>
    [_rawContent:Craft\RichTextData:private] =>
    Standard Rate:  Cancellation policy is 24 hours prior to 11.00am
        on day of arrival.

    [content:protected] =>
    Standard Rate:  Cancellation policy is 24 hours prior to 11.00am
        on day of arrival.

    [charset:protected] => UTF-8
 )

Can someone help me to get the text out from this ?


texts: How do I setup the Login Page to work with requireLogin?

texts:
I want to create a login page.  It would be a Single.

The URI is set to login.  So how do I name and map the twig file?

I tried:

creating a login folder under templates.
naming the twig file either login.twig or index.twig
setting the template location to login/login.twig or login/index

Neither approach worked.

How do I setup a login page so that when I use requireLogin the login page is in the right location for loginPath.  At the bare minimum, where is the easiest location to place the login path?


texts: How can I return the entry with the highest value?

texts:
Each entry in posts has a field called value.  Value is a number.

For a category, how can I return the entry with the highest value?

This is not for Craft Commerce.  Value represents a budget figure.

Alternatively...

How can I return the top 3 entries (based on value)?


texts: How would one allow users to edit only some other users entries but not all? Linked via a related field

texts:
I have users that are assigned to an organisation. An organisation can have many users.

I would like users within the same organisation to be able edit entries (in this case projects) created by a "parent" user in that organisation.

I could allow users to edit other users entries, and code into the template a check if they are not in the project's organisation then dont allow them to edit it, but this is not fool proof because someone could change the hidden project ID fields in the HTML and therefore could save an entry for another organisation.

Anyone have any ideas how best to accomplish the above?

Thanks


texts: Do not send email activation on public registration while keeping the requireEmailVerification setting on

texts:
Is there a way to not send Email Activation on public registrations while keeping the requireEmailVerification setting on.

Because, I have two type of users. The one is the off street registration (no email invite from a member) and the other one is invited.
I want to make the invited users not to receive an Activation Email after registration as  I already activating them in the controller.

Btw, I am just calling the $response = Craft::$app->runAction('users/save-user'); on my controller to handle the registration.


texts:
I'm on a read-only filesystem using Google App Engine Flex. I was able to write my cpresources to cloud storage using a plugin, however, now I need to have project.yaml be written elsewhere. perhaps cloud storage as well.
Not sure how to approach this


texts:
I'm using the following form, and occasionally through testing the e-mail activation link will send, however the majority of time it never gets sent. Did I do something wrong with the form?

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

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

                    {% for error in errors %}

{{ error }}

                    {% endfor %}

            {% endif %}
        {% endmacro %}

        {% from _self import errorList %}

Username

        <input id="username" type="text" name="username"
            {%- if account is defined %} value="{{ account.username }}"{% endif -%}>

        {% if account is defined %}
            {{ errorList(account.getErrors('username')) }}
        {% endif %}

Email

        <input id="email" type="text" name="email"
            {%- if account is defined %} value="{{ account.email }}"{% endif %}>

        {% if account is defined %}
            {{ errorList(account.getErrors('email')) }}
        {% endif %}

Password

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

        {% if account is defined %}
            {{ errorList(account.getErrors('password')) }}
        {% endif %}

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


texts: Is there any alternative for the Redactor plugin in Craft 3?

texts:
The Redactor plugin not working well for me. So I am in need of another good plugin for an editor that supports HTML, image, video, etc.

Please advise me about this.


texts:
So I am using a plugin to import data and it isn't assigning the values (asset is inside of Matrix) so I am going to modify the plugin and add code to lookup values that I need to assign to MatrixBlockModel and then re-save the item.

I looked up how to create a command and based on that I wrote 3 lines of code but I have no idea on how to iterate through the results. Here is the sample code:

$query=craft()->db->createCommand()
  ->select('id, folderId, filename, kind')
  ->from('{{ assetfiles }}')
  ->where('filename= :fileName', array(':fileName' => 'somefilename'));

How do I iterate through the results and how can I access info from the query?


texts: Craft CMS - Dynamic Order Field Layout In Sections

texts:
I'm wanting to have the order of my elements within a template dynamic so that the user whilst in a template of page can reorder the modules as they please.

See screenshot for example

Within the entries of the home page where I am editing content, could I reorder the "Hero Detail Body" to appear above the "Hero Detail Heading"?

My initial thoughts were no as within the Sections site, the components display order are defined for the template / tab there.

Is this possible?


texts:
I want to get only entries with a specific date. I created a date field customDateField. It has the following code:

{% set entries = craft.entries.section('orders').customDateField('2016-04-14') %}

but this not work. How it will look in php?

In element api plugin i was code:

'endpoints' => [
    'orders.json' => [
        'elementType' => 'Entry',
        'criteria' => [
            'section' => 'orders',
            'date' => '>='.craft()->request->getPost('date')
        ],
        'transformer' => function(EntryModel $entry) {
            return [
                'id' => $entry->id,
            ];
        },
    ],
]

but it only shows a larger date of entries, need to write 'date->format("Y-m-d")'


texts: Entry ancestors is null in dynamic asset subfolder path or during EVENT_AFTER_SAVE event

texts:
I'd like to use the slug of the top-level entry in a structure in an asset's dynamic folder subpath.
I have a structure where the entry I'm concerned with for this question can sit at either the second or third level. Forgive this very dubious example: possible locations for clothing in a bedroom (socks get left on the floor in this bedroom).
Bedroom
  -- Wardrobe
      -- Shirt
      -- Jacket
  -- Socks

Shirts and Jackets have a parent of Wardrobe, Socks have a parent of the Bedroom. Still with me?
Items of clothing have an Asset field which has a dynamic subfolder path, where the only thing I'm really concerned about is the top level item in the structure (the bedroom). The asset subfolder path for these items of clothing are therefore:
/bedroom/Clothing/socks.jpg
/bedroom/Clothing/shirt.jpg
/bedroom/Clothing/jacket.jpg

In other words, <structure top level slug>/Clothing/<entry slug>
I have tried to make use of ancestors but any element queries using it are returning null when saving the entry.
{ancestors.level(1).one() ? ancestors.level(1).one().slug : parent.slug}/Clothing/{slug}/
I'm also seeing the same in an Entry::EVENT_AFTER_SAVE event (checking it's not a draft or revision), where (ModelEvent) $event->sender->ancestors->level(1)->one() returns null for the entry being saved.
In both cases, parent has a correct value, but that's no use for things in the Wardrobe.
How do I get at the slug for the top level entry in a structure, for use in an asset's subfolder path?


texts: Using Sprig's live search but show all entries first

texts:
I want to display all results in the games section to start with, then once you search, it shows the filtered results. Sprig's starting point I think assumes that you're showing nothing, like a normal search box.
With the code below, it shows all results to start with - but once there's a search query, it shows the filtered results, then also ALL of the results underneath those. What do I need to change to show all results first and REPLACE them with the filtered results after searching?
It's something to do with the s-target stuff I think. The original loop gets 'moved' into #results when you search, but as I don't understand how Sprig works so I don't really know why it's doing it
{% set queryParams = {} %}
{% set relatedParams = ['and'] %}

{# This is where the query logic is -combining category filters and text search etc #}

{% if sprig.include %}
    <select sprig s-target="#results" name="verdict" id="verdict">
        {# loop through options #}
    </select>
    <select sprig s-target="#results" name="rating" id="rating">
        {# loop through options #}
    </select>
    <select sprig s-target="#results" name="platform" id="platform">
        {# loop through options #}
    </select>
    <input sprig s-trigger="keyup changed" s-target="#results" type="search" name="title" id="title" />

{% endif %}

{% if queryParams %}
    {% set entries = craft.entries(queryParams).orderBy('score').all() %}
    {% for entry in entries %}
        {{ entry.title }}
    {% endfor %}
{% else %}
    {% set entries = craft.entries.section('games').orderBy('title').all() %}
    {% for entry in entries %}
        {{ entry.title }}
    {% endfor %}
{% endif %}


texts: How to create custom field type in Craft 3

texts:
I have been struggling to create my own custom field, so I would like to ask how to create it.

First of all, I don't know where the files should be in.
I have some custom fields in Craft 2.
It might be able to be migrated, but it is not.

I have these files under src folder in a plugin.

fields/{fieldtypeName}FieldType.php
templates/_fieldtypes/{fieldtypeHandle}/input.html
templates/_fieldtypes/{fieldtypeHandle}/settings.html

Then I added a registration as the documentation, but Craft says it is not found.
https://docs.craftcms.com/v3/extend/field-types.html


texts: Why does getting a single block in NEO prevent getting the remainder of the blocks?

texts:
I have blocks set up for nutritional values: Calories, Total Fat, Carbohydrates, etc. These are set up in NEO blocks.
I can successfully loop through all of the NEO blocks (about 20 rows total) and output the content using this for loop:
{% for block in entry.nutritionBuilder.level(1).all() %}
    ...
{% endfor %}

Later, I added a line ABOVE this loop to retrieve the content of a single block:
{% set item = entry.nutritionBuilder.type('blockCalories').one() %}
{{ item.nutritionValue }}

This works, in that it will output the value I need to retrieve. However, the for loop below this line now only outputs a single row from nutritionBuilder which is blockCalories row.
Can anyone see why this is happening?


texts:
I'm trying to include a PHP file (BrowserDetection) within my plugin.

I've tried this:

Craft::import('plugins.myPlugin.resources.php.BrowserDetection');

Which doesn't return any errors, but also doesn't work. I've also tried:

require_once 'resources/php/BrowserDetection.php';

Which does pull in the file, but each time I tried to refer to it like: "$browser = new BrowserDetection();" I get something like this:

  Fatal error: Class 'Craft\BrowserDetection' not found in /Volumes/Mark
  Notton/Clients/The STC/Website/craft/plugins/myPlugin/MyPlugin.php on line
  33

Apologies for the very noob question. I just don't understand how to pull in additional PHP resources. Perhaps I'm overlooking some bespoke craft syntax?


texts:
How to auto-generate URLs in Craft? For example when we upload images on Tumblr, an URL to the post is created:

http://twotimeselliott.tumblr.com/post/95032257420

And an URL for the image is created:

http://31.media.tumblr.com/2142197f5273865770be44723c2a5df0/tumblr_nagyr9INCE1r6ky2bo1_500.jpg

How can we do that in Craft?


texts: Free shipping discount on whole order doesn't appear as adjustment

texts:
TL;DR : Free shipping on order discounts don't appear as a discount (or any type of) adjuster. So how do I check if a free shipping discount has been applied?
Sorry for the long post - hopefully it explains what I'm trying to achieve!
I have a custom module that shows and hides shipping options depending on a few factors.
At the moment the client has a discount that allows Free Shipping on all orders over $200. They have set this up and ticked the "Remove all shipping costs from the order"

This is working well and no shipping is being applied correctly at the right time. However the only thing that shows you have free shipping is that the shipping price is 0.
To make it clearer to the user I'd like to display a notice to show they are getting free shipping. I can't do this using the shipping total as that may be zero simply because they haven't selected anything yet.
So my idea was that I could use the adjusters to check if the discount was being applied, but this type of discount doesn't seem to appear in the list of adjusters. Here are a couple of scenarios where I have listed all adjusters:
1.) Order with normal shipping applied: - shipping and tax adjusters applied.

2.) Order over $200 (free shipping) - only tax adjuster applied.

3.) Order over $200 (free shipping) and 10% discount applied.

So my question is how do I detect that a free shipping discount has been applied to an order? Should the discount appear as an adjuster? Is there a different way to detect what discounts have been applied?
Thanks


texts: Add Database Relationship to craft_user table from a Plugin

texts:
Within a plugin I'd like to create a table which is linked to the craft_users table, keyed on the id. In my table I have a user_id column which I'd like to be unique and only contain Id's which exist in the craft_users table. Now, I know I can't monkey about with the craft_users table or the UserRecord, so I wondered what the best way of doing this would be?

Here is my Record code:

<?php
namespace Craft;

class MyPlugin_MerchantRecord extends BaseRecord
{
  public function getTableName()
  {
    return 'myplugin_merchants';
  }

  protected function defineAttributes()
  {
    return [
      'user_id' => [AttributeType::Number, 'required' => true],
      ...
    ];
  }

  public function defineIndexes()
  {
      return [
          ['columns' => ['user_id'], 'unique' => true],
      ];
  }

  public function defineRelations()
  {
    return [
      'user' => [static::BELONGS_TO, 'UserRecord', 'user_id'],
    ];
  }
}

If I try and install the plugin I get the following error:

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint.
The SQL statement executed was: ALTER TABLE `craft_myplugin_merchants`
ADD CONSTRAINT `craft_myplugin_merchant_user_id_fk` FOREIGN KEY (`user_id`)
REFERENCES `craft_users` (`id`) ON DELETE SET NULL

I've tried it with/without the defineIndexes() call, and get the same error. I'm sure I'm missing something simple, but can't see the wood for the trees!

As always any help gratefully received.


texts: Can't search for drafts in Control Panel

texts: I just updated to Craft 3.6x, and I noticed that suddenly all my drafts are showing up by default. This confused users, as there were a bunch of them that people had abandoned. But I noticed that the search filter at the top does not apply to drafts. Is there somewhere to change the setting? And is there also a way to show LIVE entries only, by default?


texts: Can control panel date display always be numeric?

texts: I understand the display of entries' postDate, etc., in the control panel can be localized, but I'm wondering if it's possible to get rid of the "yesterday" and "today" designators, and force displaying to always be M/DD/YYYY instead.


texts: Problem pulling email address from admin user in plugin

texts:
Is there some difference between admin users and other users? In my plugin, I have code that grabs the email address off of a selected user and then sends an email to that user. It works fine is the user is not an admin, but breaks if the user is an admin.

// grab the user object so we can get the email address from it
foreach ($users as $user) {
    if ($user->id == $settings->users) {
        $emailRecipient = $user;
    }
}

Later, I pull the email address and send the email.

$email          = new EmailModel();
$email->toEmail = $emailRecipient->email;
$email->subject = 'New Entry in ' . $sectionTitle . '.';
$email->body    = $body;

For non admins, it works but for admins, I get the error PHP notice: Trying to get property of non-object

Any ideas?


texts:
Is there any way to output the content of a channel entry by their slug?

For example, say I have an asset field called "image" in each channel entry, I want to output the content of that field only for the channel entry filtered by the slug "home", I've tried both:

{% for item in craft.entries.section('images').slug('home') %}
    {{ item.image.first() }}
{% endfor %}

and

{% for item in craft.entries.section('images').find().slug('home') %}
    {{ item.image.first() }}
{% endfor %}

but neither work...


texts: Check if we're the second or last sunday of the month today

texts:
How can I check if today is the second or last sunday of this month?
My effort:

{% set now = now|date('U') %}
{% set monthyear = now|date('F Y') %}
{% set secondSunday = now|date_modify("#{monthyear} second sunday")|date('U') %}
{% set lastSunday = now|date_modify("#{monthyear} last sunday")|date('U') %}

{# check if now is second or last sunday #}
{% if now == secondSunday or now == lastSunday %}
   {# YES, today is the second or the last sunday #}
{% else %}
   {# NOPE #}
{% endif %

But I keep getting the following error:

DateTime::modify(): Failed to parse time string (juni 2017 second sunday) at position 0 (j): The timezone could not be found in the database

Maybe it doesn't work because the monthyear variable is formed in dutch and not english? (juni = june) If this is the case, how can I modify this to english in order to get it to work?

Also, my timezone is correctly set to UTC+2 (CEST) - Europe/Brussels via Settings > General

Thanks!


texts: How do I display entries, grouped by distinct categories where the entries share a relationship to both the category and an entry in another channel

texts:
I have 2 channels:survivors, survivorContent and a Category:themes. Relationships are as follows:
survivorContent has -> related themes (max 3) AND survivorContent has -> related survivors (max 1)

Themes are always only one level deep.

I have a template that receives survivor.slug as a variable (based on a route). Given the survivor slug, I need to show a list of distinct themes that are indirectly related to this survivor (via the survivorContent->survivor relationship and the survivorContent->themes relationship). Then I need to show the survivorContent entries under each of those filtered themes that are related to both that theme and the given survivor to get output like this:

Survivor.title

Related Theme 1

Related survivorContent1 (related to both the Survivor & Theme 1)

Related survivorContent2 (related to both the Survivor & Theme 1)

Related Theme 2

Related survivorContent3 (related to both the Survivor & Theme 2)

Related survivorContent1 (related to both the Survivor & Theme 2 as well as Theme 1, above)

etc...

I'm struggling to find a way to do this that is remotely efficient. Any ideas?


texts:
I have a Craft site where I need to redirect any traffic to www (including dev.lakesideohio.com). The rule seems to be working but for some reason the url gets changed to using index.php with query string which I am not using.

For example https://mysite.com/news goes to https://www.mysite.com/index.php?p=news/ instead of https://www.mysite.com/news.

<IfModule mod_rewrite.c>
RewriteEngine On

# Redirect to www
RewriteCond %{HTTP_HOST} !^www\.mysite\.com$ [NC]
RewriteRule ^(.*)$ https://www.mysite.com/$1 [R=301,L]

# Send would-be 404 requests to Craft
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/(favicon\.ico|apple-touch-icon.*\.png)$ [NC]
RewriteRule (.+) index.php?p=$1 [QSA,L]


texts:
I'm running PHP 5.3.3, which the docs say is supported, but if I try to go to the main admin page or go to add a field, I'm getting an error:
    Use of undefined constant JSON_HEX_TAG - assumed 'JSON_HEX_TAG'

Everything I'm finding online points to this being an outdated PHP issue, but thought I would check since I am running a supported version of PHP.

Thanks!


texts:
I am using Craft only for the blog section of my site. The rest is HTML.

How do I make my site's 404 page come up for errors in the Craft-blog section?

Do I use the errorTemplatePrefix?

Where does that go?

What to I put in there if Craft is above root and my page is mydomain.com/404.html


texts: Sorting Entries by category, from multiple category groups

texts:
I'm struggling to figure out how to do this:

We have a bunch of entries in single a channel.
There are two category groups an entry can be assigned to, with multiple categories in each group.

We want to show all entries, but grouped in a nested format as follows:

Loop through Category Group One and get the entries grouped by each category.
Within each Group One category, loop through Category Group Two, to output entries grouped by Category Group Two categories.

I've found Relations hard enough to wrap my head around when I'm passing just a single category, but this has melted my mind completely.

For more specifics:

Category Group One has categories which are days of the week: Mon, Tue, Wed, Thus, Fri, Sat, Sun.
Category Group Two has categories that are activities: Walking, Running, Skiing

The output ought to be grouped something like:

Mon - Walking [entry title, entry title, entry title]
Mon - Running [entry title]
Mon - Skiing  [entry title, entry title]
Tue - Walking [...]
Tue - Running [...]
...

This is the code I've got closest with, but it's outputting duplicate entries within each day group...

{% set days       = craft.categories.group('day') %}
{% set activities = craft.categories.group('activity') %}

{% for day in days %}

        {{ day.title }}
        {% for activity in activities %}
            {{ activity.title }}
            {% for entry in craft.entries.section('attractions').relatedTo(
                'and',
                { targetElement: day },
                { targetElement: activity }
            ) %}
                    {% if loop.first %}
{% endif %}

{{ entry.title }}

                    {% if loop.last %}
{% endif %}
            {% endfor %}
        {% endfor %}

{% endfor %}


texts: Where are all the references to the URL stored?

texts:
I have my first craft website all working great on my local dev server and want to move it to the production server. I think I went about this the wrong way but I installed a fresh install of craft on the pro server then purchased a pro license.key. This all installed OK. This is the same root level structure as the local dev version.

I made sure both sites were upto date then copied over my database dump from dev and uploaded my templates. However this has broken the URLs (the home page loads). Have I missed something?

The production server doesn't have the domain pointing at it but can be view via the IP like so.

http://79.170.40.48/mydomain.co.uk/    <-- though it does require the trailing lash

The odd bit is if I visit the link

http://79.170.40.48/mydomain.co.uk/products

the browser address bar says

http://79.170.40.48/mydomain.co.uk/products

the apache error says the requested URL is
/home/sites/mydomain.co.uk/public_html/index.php was not found on this server.

And curiously the /home/sites/ address is what my my local dev path is. So where is the remote product install getting this from?


texts: Using Services to get all the Categories related to an Entry?

texts:
In a plugin, I've been advised to try to use craft built-in services instead of direct db queries. So can anyone help with this:  For an entry type that includes a categories field, how to get all the categories related to an entry?

I found this:

$entry = craft()->entries->getEntryById($entryId);

So I suppose this might work as well:

$category = craft()->categories->getCategoryById($categoryId);

But I can't find anything intelligible to me under the relations service.

Thanks for any help.

EDIT: On a related note, I see here that in twig you can do this:

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

{{ entry.title }}

    {{ entry.summary }}
    Continue reading

{% endfor %}

Whereby Craft/Twig does all the work to find and return the 'summary' field related to each entry. Is there any php statement like this next confused one, following which I could get the categories related to each event?

$events = craft()->entries.section('events').start('<=$toDateYmd').end('OR', '>=$fromDateYmd', '').status('publish');
foreach ($events as $event)
   $categories = $event.category;

Thank you!


texts: So I'm getting to a point where I have a lot of services in a particular plugin, and I would like to organize my plugin services into sub-folders. I've tried a couple ways but the controllers don't seem to be able to find the appropriate services unless they are in the main services directory. I know I can put controller files in sub-folders of the controllers folder, so I thought the same would be true for services. Does Craft support what I'm trying to do?


texts: Is it possible to Filter entry types via the URL?

texts:
I'm wondering if it's possible to dynamically filter a section list by entry type based on a url segment?

I'm hoping to avoid assigning a category to every entry.


texts: Using the Charge plugin for membership subscriptions

texts:
A project I'm working on requires that publicly registered users pay a fee upon registration, and when payment is successful an Entry belonging to them should automatically be created.

I have component pieces of this working but am struggling with how to tie them together.

I currently have a basic plugin I wrote which handles the creation of an Entry when a user is Activated. The plugin has no money-taking facility. It works fine; the public user registration form posts to the built-in 'users/saveUser' action, and the plugin listens for the users.activateUser event which is fired when an admin manually activates their account.

We want to take that 'manual' step out by having the system automatically activate the user if a Charge has been successful. This means integrating Charge into the public registration form. Which would seem to involve me having to change the action for the form to 'charge/charge', so Charge can do its thing.

How then do I also get it to create the user?

I see that Charge has an event for successful payment, which I'd like to hook onto and trigger the 'user/saveUser' like what's already working - but how, and how do I pass the username/email fields through from the form to 'user/saveUser' via Charge?


texts: What do I use for the Path to the Craft folder?

texts:
I want to place my Craft folder above the root.   But, this is for an add-on site that sits within the public_html folder of the main site.

So, the index.php file sits here...

../public_html/add-onsite-folder/public/index.php

The Craft folder sits just above the /public_html folder of the main site.

So, how - specifically - do I set the $craftPath?   It's not the default '../craft'; and I have tried numerous variations.

I am not installing locally.

Thanks


texts: Image transforms not working on front-end

texts: I'm able to upload images correctly to the server. I can see the thumbnail and view the larger image inside the control panel on the Assets page. However, the front-end image transforms result in a 500 error.


texts: Update category selection in user custom fields

texts:
I have a Category "Colors".
This category has: Blue, Red, Green

I've added a custom users field (CP > Settings > Users > Fields), this field is the category type. "Colors".
In the front of website I need users to select their faviourte color/s and save/update it.

Below code saves successfully "Settings saved!", but I go into the CP > Users > user@gmail.com > (custom field category colors)
and the colors have not been selected:

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

        $request            = Craft::$app->getRequest();
        $myUser             = Craft::$app->getUser()->getIdentity();
        $cat                = $myUser->getAttributes()['colors']->all(); // Get users seletected colors
        $availableColors    = Category::find()->group('colors')->all(); // Query all available colors

        // Organise array for users already seletected color items
        $usersCurrentColors = array();
        foreach($cat as $item)
        {
            array_push($usersCurrentColors, $item['slug']);
        }

        // Organise all available colors to tailor to format
        $organiseAvailableColors = array();
        foreach($availableColors as $item)
        {
            $organiseAvailableColors[] = $item['slug'];
        }

        $allAvailableColors       = array_fill_keys($organiseAvailableColors, '');

        // Organise new selected colors from the form(post data)
        $newSelectedColors  = array_intersect_key($request->getBodyParams(),$allAvailableColors);

        // Set the new data that soon will be saved
        $myUser->setAttributes(array(
            'colors' =>  Category::find()->group('colors')->slug($newSelectedColors),

        ), false);

        // Save data and create error messages
        $save = Craft::$app->getElements()->saveElement($myUser);

        if($save){

            return Craft::$app->session->setFlash('success_userSettings', 'Settings saved!');

        }else{
            return Craft::$app->session->setFlash('success_userSettings', 'Settings failed, please contact support!');
        }

    }

Craft Pro: 3.4.6.1


texts:
I'm attempting to pull out a list of categories starting with certain letter(s).

What I've come up with so far seems a little excessive and I'm wondering if I've missed something obvious.

Can it all be done with just the 'craft.categories...' line?

{% set allCats = craft.categories.group('listingCategories').order('title').limit(null).find() %}
{% set allCatsByLetter = allCats|group('title | first') %}

{% for letter, allCats in allCatsByLetter if letter == "A" %}

        {% for cat in allCats %}

{{ cat.title }}

        {% endfor %}

{% endfor %}


texts:
I want to build my first website with Vue.js but have difficulties how to start.
Craft and Vue.js both use {{ }} as delimiters, but I found out that I can change this for Vue. So to start, I tried the following in my JS file.

Vue.config.debug = true;
Vue.config.delimiters = ['${', '}'];

new Vue({
    el: '#content',
    data: {
        message: 'Hello Vue.js!'
    }
});

But the output I get is ${ message }

In the html file I have the following:

<div id="content" role="main">
    ${ message }
</div>

In the html file, I first load vue.js, then my script.
I use Vue.js v2.0.0-rc.6

Any idea how I can make this work?


texts:
I have the following setup for a language switcher. I have Member Directory pages which are using Users (rather than Entires or Categories). How can I update this to get it working on these pages?

{% set langSwitcher = craft.app.sites.getAllSites() %}

 {% for lang in langSwitcher %}
 {# Set homepage as default #}
 {% set url = alias(lang.baseUrl) %}

 {# Entry is defined #}
 {% if entry is defined %}
  {# Check if that entry exists in other locale #}
  {% set otherLocaleEntry = craft.entries.siteId(lang.id).id(entry.id).one() %}
  {% if otherLocaleEntry %}
    {% set url = otherLocaleEntry.url %}
  {% endif %}

{# Category is defined #}
{% elseif category is defined %}
  {# Check if that entry exists in other locale #}
  {% set otherLocaleCat = craft.categories.siteId(lang.id).id(category.id).one() %}
  {% if otherLocaleCat %}
    {% set url = otherLocaleCat.url %}
  {% endif %}
{% endif %}

{{lang.name|upper}}

{% endfor %}


texts:
below is my controller code for getting a data of prodcuts.

$service = craft()->entries;
$entry = $service->getEntryById(108);

$title = $entry->getTitle();
$description = $entry->description;
$overview = $entry->productOverview;
$price = $entry->price;

$slider = $entry->productSlider;

i store a slider data into matrix fields.

Block type = productSlider

fields is = images,title

Thanks


texts: Set user based on their attachment to a product

texts:
With Craft Commerce, I have a custom field that allows you to select which user from a defined group the product belongs to/is associated with.

I want to be able to set the user in order to access additional information about this user (profile info etc) and display this on the relevant product page.

How would I achieve this?


texts: Plugin RegisterUrlRulesEvent - Regex URL-Routing gives 404

texts:
I'm updating a Craft 2 plugin to Craft 3 and I'm having difficulties getting the Regex URLs working correctly. The eocs I'm using: Craft3 Docs
I used pluginfactory.io to create the basic craft3 plugin scaffold.
 For context: the plugin name is expedweather.

This is the Route I'm trying to register:

$map_page = 'data/<range:\w+>/<peak:\w+>/<view:\w+>/<parameter:\w+>';
$event->rules[$map_page] = 'expedweather/forecastPanel';

In my DefaultController.php I've got this:

protected $allowAnonymous = ['index', 'forecast-panel'];

And I'm not sure what I'm doing wrong here but All I get is

  HTTP 404 – Not Found – yii\web\NotFoundHttpException Page not found. ↵
  Caused by: Invalid Route – yii\base\InvalidRouteException

I've made sure the plugin is enabled in the backstage.


texts:
I recently switched host to DigitalOcean and also moved my assets onto S3. The system is freezing when I upload an asset which seems to be 1mb or over, I have altered my php.ini file to make sure this wasn't the culprit.

There is also an issue with some images appearing and others not. I'm getting this message when looking at some files

  This XML file does not appear to have any style information associated with it. The >document tree is shown below.

When I add a policy statement this seems to disappear but I'm not sure if this was even required, hard to see how other files are showing up.

In craft_assetsources I have the following which still seems to carry the old url??

{"path":"images\/ads\/","url":"http:\/\/digbmx.com\/images\/ads\/","keyId":"AKIAJCJA6QHXEOAZ2LMA","secret":"EDGceqipqQOSqM7ItU8L52oT+ZjQD+pnK\/Z+30gW","bucket":"digbmx","subfolder":"ads\/","urlPrefix":"http:\/\/s3-eu-west-1.amazonaws.com\/digbmx\/","expires":"","location":"eu-west-1"}

Any help on these issues would be much appreciated.

Thanks, Dc


texts:
We are working on a plugin that needs to update the contents of a Matrix field within Globals. I've found little snippets of code but none that do exactly this. Can anyone provide some code or point me to some code that does such? I can't seem to figure it out. Code sample of what I have so far is below. This does not result in any sort of area, but also does not seem to do anything.

As you can see, I'm trying to force all couponCodes to be 'BBB' whilst copying all other values. Maybe there is a much better way? It would be nice to just update the code value without recreating the full set of data if possible.

$couponCodeMatrix = craft()->globals->getSetByHandle('couponCodes');
$newMatrixData = array();

foreach($couponCodeMatrix->couponCodes as $block) {
    $blockData = array(
        'type' => $block->getType()->handle,
        'enabled' => true,
        'fields' => array(
            'couponCode' => 'BBB',
            'couponType' => $block->couponType,
            'couponValue' => $block->couponValue,
            'expiryDate' => $block->expiryDate,
            'singleUse' => $block->singleUse,
        )
    );

    $newMatrixData[$block->id] = $blockData;
}

$couponCodeMatrix->setContentFromPost($newMatrixData);

craft()->globals->saveContent($couponCodeMatrix);


texts:
I'm trying to set Mailgun up on Craft (Like we've done plenty of times before) but each time it keeps saying that the connection to SMTP is failing.

The error I'm getting is:

  2017/03/29 09:54:13 [error] [application] Email error: SMTP Error: Could not authenticate.

I've checked https://craftcms.com/support/troubleshooting-email-errors#dealing-with-errors and error description is:

  “Use SMTP authentication” was checked, but the credentials were incorrect.

But I've double checked these details over 10x now and they are 100% correct.

Is there any other reason this could fail? We're using port 587 and tried other ports but no success. Even opening these ports on the server doesn't connect.

Where would the problem be... Craft, Mailgun or Server?


texts: Validate fields in Solspace Freeform plugin

texts:
I have been using Solspace Freeform plugin (Lite edition) with Craft 3.
However, I cannot find how to develop validations for the form.
Could you tell me how to develop form validations?
(E.g. postal code, password)


texts:
I have a Smart Map setup and installed it on a site.

The section averages 300 page views per day according to Google Analytics, but Google API is maxing out the 2500 requests on the free plan. I've bumped up to a paid plan, but does anyone know why there are so many requests?


texts: Sort merged array by array value in Twig?

texts:
I have two Instagram API responses that I want to merge, by the photo's created_time. Is there a way to do that in Twig?

Right now I am just using this

{% set instagram = <data> %}
{% set community = <data> %}
{% set feed = instagram|merge(community) %}

    {% for photo in feed %}

    {% endfor %}

Each photo has a created_time string that I'd like to sort the array by, is that possible without creating a custom Twig extension?

The sortByField plugin looked promising and sort of what I want, but it was directly aimed at Craft entry manipulation. Is there anything hacky that could be done?


texts:
I'm using Feedme to display content in my temmplates from a podcast RSS feed - not importing entries, just displaying.

Everything is working fine except that I can't display the <itunes:summary> node.

When I use this code

{# podcaast #}
{% set params = {
    url: 'https://website101podcast.com/feed.rss',
    type: 'rss',
    element: 'item',
    cache: 60,
} %}

{% set feed = craft.feedme.feed(params) %}

{% for node in feed|reverse %}
  {% if loop.index <= 1 %}

{{ node.title }}

{{ itunes:summary }}

    Listen Now
  {% endif %}
{% endfor %}

I get the following template errors:

  Unexpected token "punctuation" of value ":" ("end of print statement" expected).

Is it possible to call in the itunes field?


texts: Git Workflow and Multi Environment - how to approach

texts: I'd like to be able to use git version control with Craft. Is this possible and if it is what is the best approach to ensure that all files/assets and the database are properly synced across local, staging and production servers?


texts: Updating matrix field from font-end with $entry->setFieldValue() pulls in Cp bundle on save

texts:
I have an entry with a matrix field which I'm updating from front-end. The update works fine, but when the (font-end) page reloads after submitting the form, the CP bundle assets get included (selectize.css, craft.css, charts.css). If I then reload the page, the CP assets are no longer included. I believe have narrowed it down to the use of $entry->setFieldValue(). Does anyone know why that's happening and how to stop it? Or is there a different way to update an entry with a matrix field from font-end that doesn't require me to use setFieldValue()?

Here's the relevant part of my update function:

$field = Craft::$app->getFields()->getFieldByHandle('fieldHandle');
$existingMatrixQuery = $entry->getFieldValue('fieldHandle');

$serializedMatrix = $field->serializeValue($existingMatrixQuery, $entry);
$serializedMatrix['new1'] = [
    'type' => 'update',
    'enabled' => 1,
    'collapsed' => true,
    'fields' => array_merge($params['fields'], $params['required'])
];
$entry->setFieldValue('fieldHandle', $serializedMatrix);

if (Craft::$app->getElements()->saveElement($entry)) {
    return true;
}


texts: Check length of textfield in header file

texts:
Some links in the menu should only be shown if the textfield is not empty. For example:

{% if craft.entries.section('aboutus').textField|length == 0 %} style="display: none;" {% endif %}.

But craft.entries.section('aboutus').textField|length always returns 1. I also tried is empty.

So, how I get the real length of this textfield?

And I have the same problem with a matrix. How can I check if the Matrix field has any blocks?


texts: How can I limit a list based on a custom date field

texts:
I a trying to display a simple event listing. I set up a custom date field called eventDate to note when the event happens.

This code delivers me the list of events sorted by eventDate:

 {% for event in craft.entries.find({section: 'events', order: 'eventDate'}) %}

        {{ event.eventDate }}
        {{ event.title }}

{% endfor %}

However, I want to omit events whose eventDate falls before the current date/time. If it were an entry date I guess I'd just use "after", but I am not sure how to apply that to a custom date field.

Any help is appreciated.


texts: I have a couple of youtube iframes loaded into a channel entry. I also have a script running that resizes those iframes. It appears the script fires on window load but it appears that it fires before the iframes load in from craft. Is there any quick fix to this issue and if so how do I fix it?


texts: Assign entry id to title with entry form

texts:
I have an entry form to take user generated content.

The section it passes the info to has a customised title format Submission ID: {id}

However, when the entry gets submitted, the title in the CP (and indeed in the templates) just show as Submission ID:

It's not until the entry is re-saved at the control panel level (although I haven't tried a front end edit form) that the appropriate id shows e.g. Submission ID: 12465


texts: "Eager loading" of relations like Yii's "with" function

texts:
Is there any way to "eagerly load" Craft element relations a la Yii's ActiveRelation "with" function?

http://www.yiiframework.com/doc/api/1.1/CActiveRecord#with-detail

This seems like a very handy way to request one big query instead of many small ones in cases where you know up front that you are going to be using all the relations.

** UPDATE **

Okay after experimenting with this, I guess my real question should have been, is there any way to do this kind of thing at the ElementCriteriaModel level, taking advantage of Craft relational fields.

For instance, I want to get a list of children of a Structure entry, along with all the assets in a field:

foreach ($entry->children->find() as $child) {
    // do something with $child->assetsField...
}

Is there any way to load those assets in one big query rather than individually for each child?


texts: How should an index page be setup/defined in Craft?

texts:
Site construct question...

I have categories.   Craft knows where to find the template for a category - i.e. markets/{slug}.

But I also have a Markets (categories) page with the first 6 entries for each category (market).  The template is markets/index.html.

The same holds true for and index page with all my entries.  Craft knows where to find an entry posts/_entry - but what about the posts/index page?

How should these pages be setup/defined in Craft - should they be a single page or something else?

Background - Right now, they aren't defined in Craft - but I realize that I probably need to add them to work with an SEO plugin.


texts: How to Prevent Composer from Updating Plugin?

texts: I have a plugin installed from a well known Craft developer. I have made significant tweaks and changes to the plugin and need to prevent it from updating. Is there an easy line of code to add to the composer.json file to prevent it from updating? I may have to go the route of breaking it out into our my plugin but for time reasons I am looking for simple ways to prevent updating.


texts: Can we set properties to establish a valid asset per field?

texts:
Craft will let us define what file-type is valid for a given asset field, but there are many times where I'd like to enforce other properties too - e.g., a minimum dimension for valid images uploaded to that field (i.e., dimensions must be larger than 800x600). Is there a way to do that?

Currently I can only see Craft enforcing file-types and file-size limits if they're too large (e.g., 4Mb is too big). I'd like some more options to avoid clients uploading unsuitable files.


texts:
I've created a plugin that will check for a unique email address in the submissions of Freeform.
Because I don't want this check to be done with Ajax, I use the Freeform hook 'onBeforeSave'.

Whenever a email is already used, I want the user to know. I'm telling Freeforms that the form is not valid:

craft()->on(
    "freeform_submissions.onBeforeSave",
    function (Event $event) {

        // Let Freeform know the form is not valid
        $event->performAction = false;
    }
);

Unfortunately I haven't found a way to communicate this to the frontend. It would be nice if I could set a Freeform error message.

Any solutions?


texts:
Recently migrated a site from staging server (Digital Ocean VPS) to client's production server – pretty basic shared hosting (their choice). They were running PHP 5.3 so got them to upgrade to PHP 7.3. I also ran the Craft Server Check first and everything passed fine. No composer so had to FTP everything and set permissions etc...

Front end is live but Typogrify and Map plugins aren't working for reasons so far unknown. The bigger problem though is the control panel cannot load styles or scripts (403 errors on cpresources dir) and cannot login. I upped permissions on that directory to 774 and still no luck. Hosting support hasn't responded so I'm kinda stuck. Never encountered these dramas before. Any advice very much appreciated.


texts: redirectToPostedUrl with object (Model) passed to it and keep template resolving

texts:
I am creating a plugin where the user is submitting data to a controller.

With a successful saving of the data in the controller/service I want to honour the standardised redirect param:

<input type="hidden" name="redirect" value="success/{stripeId}"/>

The stripeId is a property of the PaymentModel $payment being passed to the redirectToPostedUrl param:

$this->redirectToPostedUrl($payment);

This works in that when the person is redirected the person is brought to page desired with url like this:

http://web.dev/success/ch_5GW2RFTNvW8qeR

The problem is that craft cannot find the success template and the success page does not show since it is trying to find a template a success/ directory called ch_5GW2RFTNvW8qeR.html

2 Solutions I have found:

Option 1) My plugin users need to set up a route manually in the control panel to allow this to resolve correctly (and have full control over where the success page is and what the url looks like):

Option 2) The other option is that I use the Plugin hook registerSiteRoutes to register a front end route to that template. The obvious problem with that is I either need to make that hard coded, or user configurable (pain).

Since I would obviously need to make it user configurable, it kinda defeats the purpose of the user of the plugin being able to decide the name="redirect" value="success/{stripeId}" in the first place. I would imagine I would have to come up with my own redirection/routing config and logic. I understand this is not a problem in the control panel actions since I know what I want my urls to be, but as a plugin developer I want to give flexibility to users of my plugin to choose their front-end urls.

Any thoughts? I am leaning towards having to put into the documentation of my plugin that they need to do option 1 above, but still think its not optimal.

Edit:
Just had another idea. Option 3) Since I will be giving my users demo templates for the front end forms on installation - should I possibly create a route in the craft_routes table for  the user? That way on first install everything should work without needing to manually set up a bunch of routes manually to match my demo templates.


texts: Receive all locales with ElementAPI plugin

texts:
I use Craft to return some JSON data. The content however is available in different languages and I would like to get all those translations in a single API call.

I tried something like

'endpoints' => [
    'products.json' => [
        'elementType' => 'Entry',
        'criteria' => ['section' => 'products', 'order' => ['default' => 'lft asc']],
        'transformer' => function(EntryModel $entry) {
            $translate = [];
            foreach(array_keys($entry->getLocales()) as $locale) {
                //$entry->setLanguage($locale); Doesn't work with EntryModel
                $translate[$locale] = [
                    'title' => $entry->title,
                    'slug' => $entry->slug
                    // ...
                ];
            }
            return $translate;
        },
    ],

Unfortunately, there doesn't seem to be a method call setLanguage() like with fields.
I'm out of ideas.


texts: Using getCriteria with a custom element type

texts:
I've setup a custom element type for badges for a system I'm building, but I've run into some trouble trying to query for badges using craft()->elements->getCriteria(ElementType::Badges_Badge);, however I'm getting an error saying 'Undefined class constant 'Badges_Badge', but when I loop through all element types using getAllElementTypes() I see an entry for 'Badges_Badges', and I'm able to add and edit badges in the cms.

Is it impossible to query for custom elements using getCriteria, or am I missing something more fundamental?


texts: Charge plugin: subscription start and end dates not updating for recurring subscription payments

texts:
I've been using Charge to handle a subscription service on a client site, and for the most part, it's been working well for the past year. Now that a year has gone by, the first set of recurring membership subscriptions are starting to be automatically renewed.

A problem I'm seeing is that the dates displayed using Charge's subscription.currentPeriodEnd template variables are not showing updated dates. They still show the end date for the initial year of the subscription, not the new end date which should be one year past the date of the renewal.

Anyone else experiencing this and can suggest a fix?

In a potentially related issue, the recurring payment is being displayed as "TEST" mode in the UI in Charge. See screenshot:


texts:
I'm trying to get the same features I had in Craft 2 in Craft 3 redactor field.
This is the code I had in config/redactor/standard.json:

{
    "buttons": ["format","bold","lists","link","file"],
    "plugins": ["fullscreen","table","video"],
    "formatting": ["p"],
    formattingAdd: {
        "heading": {
            title: 'Heading',
            args: ['h2']
        },
        "sub-heading": {
            title: 'Sub-Heading',
            args: ['h3']
        },
        "sub-sub-heading": {
            title: 'Sub-sub-Heading',
            args: ['h4']
        },
        "add-attr": {
            title: 'Make a link a button',
            args: ['div', { 'class': 'button' }]
        }
    }
}

The Craft 3 changes page says:
"All strings must use double quotes rather than single quotes" and that "All object properties (the config setting names) must be wrapped in double quotes".
I've tried changing them all and I still get an error. I've looked on the Imperavi Redactor docs pages, but they don't use double quotes and their examples are not in the same format as the craft plugin uses. Some more examples would be useful.


texts: Eager loading of reverse related elements?

texts:
Is it possible to load reverse related elements? I mean if the elements I’m querying are the target elements?

Example:

I’m setting up a criteria model to get some categories and I also want to load the entries related to each category. I’m using a Categories field, so my categories are the target elements of those relations.

{% for category in craft.categories.group('news').all() %}
    {% set query = craft.entries.relatedTo({
        targetElement: category,
        field: 'myCategoriesField',
    }) %}

    {# Oh no, a N+1 query problem... #}
    {% set entries = query.all() %}
{% endfor %}

I could probably do it the other way around, query for the entries and eager load the categories. Then use the group filter to order everything by category. But that approach is awkward and has limitations, e.g. doesn’t play well with pagination.


texts:
Is there a way to delete an entry's assets when the entry is deleted? We're going to end up with a lot of orphaned assets.

Or is this not a feature because an asset can be shared between entries? Thus requiring me to write a plugin to tie into the onDeleteEntry event (Where and how should you listen for entry delete in plugin?)?


texts: How to implement "cookie consent message" to visitors of our website using Craft 3

texts:
I want to implement cookie using message to the visitors of our site. How we will implement this in craft 3?

A sample message is

"Hi there, we use cookies to offer you a better browsing experience and to analyse site traffic. By continuing to use our website, you consent to the use of these cookies. Learn More"

This will appear like a popup in footer of the page.

Thanks


texts: Assetconflict after changing general.php

texts:
I've made a matrix field on one of my templates. After adding alot of content, and then trying to delete it, I get this message:

  include(/home/blabla/bla/craft/app/enums/AssetConflictResolution.php): failed to open stream: No such file or directory

The reason might be that I changed my basepath in general.php / staging issues. Any idea, anyone?


texts: Get all entries for a structure section including disabled

texts:
I am building a plugin and in that plugin I am trying to grab all entries including disabled ones.  My structure is a single entry as the parent and then it will have multiple levels of children.  Currently I am grabbing the main parent with this code.

{%   set events = craft.entries.section('events').first() %}

Then I am doing nested for loops to work my way down such as the following.

{% for event in events.children() %}
   {% for day in event.children %}
      {% for session in day.children() %}
      {% endfor %}
   {% endfor %}
{% endfor %}

This works just fine but the issue is it will not return the disabled entries.  I have noticed the status(null) when you are doing a find but I have not figured out a way to do it with the for loops.  I intend to keep the relationship structure in the ui so I am not looking to just get a random ordered list of all entries.

Any help would be appreciated and I am open if there is a more efficient solution.


texts: Best practice for naming fields shared across entries in CraftCMS

texts:
I have a question about best-practice for naming fields; I am creating a craft site for a football club, which include the following:

club name (Global)
team names
player names

These are all plaintext fields. In the interest of being DRY, should I create one 'Name' field for all? Is this problematic - and therefore better to create different fields for each, so I have teamName, playerName, clubName handles etc?


texts:
I'm trying to build my blog functionality with craft, and struggling to get the functionality of showing "when" that post was created.

Is it possible to do the following:

Posted X days ago,
Posted x Weeks ago,
Posted x Months ago,


texts:
The typical way to get your user's IP address via PHP is with $_SERVER['REMOTE_ADDR']. This is pretty solid, but can lead to some IP detections that are surprisingly far away from the user's actual location.

Craft also has it's own IP detection with craft()->request->userHostAddress. This jumps through a few more hoops before finally falling back to $_SERVER['REMOTE_ADDR'].

Which is better in terms of geolocation accuracy?

The Craft docs say this:

  Considering any of these server vars besides REMOTE_ADDR can be spoofed, this method should not be used when you need a trusted source for the IP address. Use $_SERVER['REMOTE_ADDR'] instead.

I don't think my source needs to be that "trusted". I'm using the IP address for best-guess geolocation, not for any sort of security purposes.

I'm just looking for whichever one will pinpoint closest to the human user.

Disclaimer: I'm well aware that IP detection is a lousy way to pinpoint users, and that HTML5 / JS offers much more accurate geolocation results. But when using that method, geolocation is optional to the user, and they may deny permission to share their location. It's good to have the IP detection as a fallback.


texts:
on the template

_events.twig

{% include "./components/_listing" with {
  entries: craft.entries.section('events').orderBy('eventStartDate ASC').limit(3),
  columns: 3,
  heading: 'On this month',
  art: 'art3',
  headings: true
} %}

_listing.twig

{% if pagination is defined and pagination == true %}
        {% paginate entries as pageInfo, pageEntries %}
    {% else %}
        {% set pageEntries = entries %}
    {% endif %}

             {% for entry in pageEntries %}
    ~~~~

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

The line number is {% for entry in pageEntries %}

I referred Explanation of Deprecation Warnings and Output deprecation error

But seems I'm away from those two answers.

Can someone suggest me to find a solution for this?

Update:

{% set featuredEvents = craft.entries.section('events').featuredEntry(1).limit(10).orderBy('offerStartDate') %}

on the template

{% for featuredEvent in featuredEvents %}

When we limit to 10, why `{% for featuredEvent in featuredEvents %} line highlight for

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


texts:
Good afternoon,

Is it possible to have a next prev button to cycle through a number of matrix blocks within a single entry and show the blocks content individually on screen? The block contains an entry from another channel.

If so, can someone point me in the direction of docs for it as Im struggling to find at the moment.

Many thanks.


texts: PHP Exception for errors on Craft Contact Form with additional fields

texts:
I'm having trouble with additional message fields in my Craft Contact Form using Craft 3 and the Pixel & Tonic Contact Form plugin.

I've added two additional fields by splitting up the message field as described in the plugin documentation. If all the fields are filled in, everything goes smoothly. But if the form is submitted with any blank required fields, I get a PHP error "Array to string conversion." Live example at http://striveforfive.creativeforthepeople.org/contact.

EDIT: The code is:

    {% if entry.formCopy|length %}{{ entry.formCopy }}{% endif %}
    {% macro errorList(errors) %}
        {% if errors %}

                {% for error in errors %}

{{ error }}

                {% endfor %}

        {% endif %}
    {% endmacro %}

    {% from _self import errorList %}

    <form class="contact-form" method="post" action="" accept-charset="UTF-8">

            {{ csrfInput() }}
            <input type="hidden" class="form-control" name="action" value="contact-form/send">
            {{ redirectInput('contact-ty') }}

            <input id="from-name" class="form-control" type="text" name="fromName" value="{{ message.fromName ?? '' }}" placeholder="your name">
            {{ message is defined and message ? errorList(message.getErrors('fromName')) }}

            <input id="from-email" class="form-control" type="email" name="fromEmail" value="{{ message.fromEmail ?? '' }}" placeholder="your email">
            {{ message is defined and message ? errorList(message.getErrors('fromEmail')) }}

            <input id="affiliation" class="form-control" type="text" name="message[Affiliation]" value="" placeholder="your school / organization / home locations">

            <select id="position" class="form-control" type="text" name="message[Position]" value="">
                <option value="" selected disabled>your position</option>
                <option>Educator / Care Giver</option>
                <option>Family Child Care Provider</option>
                <option>Center Director</option>
                <option>Student Teacher</option>
                <option>Other</option>
            </select>

            <textarea rows="5" cols="40" id="message" class="form-control" name="message[body]" placeholder="your message">{{ message.message ?? '' }}</textarea>
            {{ message is defined and message ? errorList(message.getErrors('message')) }}

            <input id="bluebeard" name="bluebeard" type="text">

            <input id="contact-submit" type="submit" class="btn btn-outline-primary" value="Send">

    </form>

All help is appreciated!


texts: How do I sort a collection of entries from multiple sections by date?

texts:
I want to create a featured story slider on my website and gather the latest entries from multiple channels to populate it.

Here is what is working:

# fetch the entries
{% set featuredBlog = craft.entries.section('blogs').limit(1).find() %}
{% set featuredArticle = craft.entries.section('articles').limit(1).find() %}
{% set featuredSpecialReport = craft.entries.section('specialReports').limit(1).find() %}
{% set featuredInfographic = craft.entries.section('infographics').limit(1).find() %}

# create a collection out of the above entries
{% set allEntries =
featuredBlog|merge(featuredArticle)|merge(featuredSpecialReport)|merge(featuredInfographic) %}

# loop over the collection and output them
{% for featuredEntry in allEntries %}
  {{ featuredEntry.title }}

{% endfor %}

Now I want to sort the collection of entries by postDate so that the latest entry in the collection shows up first, no matter what section it is from. How do I do this?

I tried:

{% for featuredEntry in allEntries|group('postDate.day') %}
  {{ featuredEntry.title }}

{% endfor %}

But this doesn't work and crashes the template saying Key "title" for array with keys "0, 1, 2" does not exist

So how do I sort a collection of entries from multiple sections and show them by latest date descending?


texts: Foreign Key column pointing to `craft_relations` table

texts:
I am writing a plugin with a Record. I want the primary key of the table to also be a foreign key relating to the craft_relations table. Ordinarily, I would add something like this...

public function defineRelations()
{
    return array(
        'element' => array(static::BELONGS_TO, 'ElementRecord', 'id', 'required' => true, 'onDelete' => static::CASCADE),
    );
}

However, it seems like the craft_relations table does not have a matching Record.

How can I add a primary key column which is also a foreign key?


texts: Query a subselection of Sales and Discounts

texts:
Imagine a less than perfect world, where a 'bundles' product type is just a new product with a sale/discount on it.
Would there be any way to query all sales and all products only related to these but ignore every other regular "used as intended" sale/discount?

From what I can tell, there is no way to categorise sales/discount, only ways to categorise what the affect?


texts: Control panel field name & instructions translations

texts:
I've installed a Craft Pro site with 3 locales: Dutch, French & English, but the people who are going to input data will speak those languages too, so I need to translate the instructions field in the control panel (and, if possible, the field names too since most of the time that makes it clear enough).
Is this possible, and if it is: how?
Thanks!


texts: Is there a way to filter calendar results by location?

texts: My current calendar plugin has filters by category, location and a date selector. Is this all achievable in solspace calendar?


texts:
I'm looking answer because I need access for all user in database access to disable entries

This mean somebody will publish something and administrator will be change status for entires from live to disable and CMS will be send notification to user about that. When you user will be login to account will be see entires live and disable and access to this entries. Right now I can show every entries live and disable but when click link live entire go to template and work fine but when I click link disable entries to to 404 page.

Thanks for help,
SS


texts:
I'm using amforms for a client and need to create a user confirmation email that has a pdf attached containing the submitted form data, like a receipt.

After a little google searching, I believe I'd have to hook into amforms' onEmailSubmission method and generate the pdf using the mPDF library, is this correct?

How do I add the mPDF library to Craft?
After creating a nice pdf template design, how can I populate a 2 column table in the pdf with form names/values submission data from all the fields?
And then finally attach that pdf to the user confirmation email?

Does anybody have experience with this whether using amforms or not?


texts: How can I get field values for the sections that I created

texts:
New to Craft CMS. We decided to make Craft headless and have an api fetch the data.
I have 5 (simple) sections that represent 5 pages and they all have some fields in them with some texts or images. So far so good.
Now, the cms is headless, so I added a controller to return the pages data (some texts and images). I used Entry::find()->section('homepage')->one(); It returns an Entry Object, but the field's values are nowhere to be found.
Ex: In the cms, I have a hero field that contains a text and an image, but for the love of god I can't get the values of them using the query builder...
When I print the result of the query, I see the field names in the Entry object, but they are all NULL. Yes, my homepage entry in the cms is filled with texts and images for those fields...
[_behaviors:yii\base\Component:private] => Array
(
    [customFields] => craft\behaviors\CustomFieldBehavior Object
    (
        [hero] =>
        [titre] =>
        [description] =>
        [fullWidthCTA] =>
        [...]
    )
)

I also tried Entry::find()->section('homepage')->one()->getFieldValue('hero') but same problem...
If it's not clear enough, just let me know and I'll post an update in the morning.
Thank you.


texts:
1) Where To Put It

I’m wondering how I should proceed with the SECURITY_KEY which is now mandatory in Craft 3 (RC2). It has to be the same for one project, right? So it should be shared across developers. But is it a good idea to commit it to a Git repository? I guess not.

But then – where do I put it without losing it and still sharing it with team mates.

2) What If It Changed?

Due to some circumstances I lost the security key of the initial installation and added a new one. Could that lead to unwanted behavior down the road?

Enlightenment of any kind is much appreciated :)


texts: Getting unique values from Smart Map addresses

texts:
Using the following filter will return all the entries for 'CA'.

{% set params = {
    filter: {
        state: 'CA'
    }
} %}

{% set meetings = craft.entries.address(params) %}

Let's say that I get 10 returns for 'CA':

Los Angeles
Los Angeles
Los Angeles
San Diego
San Diego
San Diego
San Diego
San Diego
San Diego
Modesto

How would I go about one getting 3 results returned for each unique value for City? I only want to list each city once rather than 3 Los Angeles, 16 San Diego's and 1 Modesto. Like this:

Los Angeles
San Diego
Modesto

It could also be helpful to have them like this:

3 Los Angeles
6 San Diego
1 Modesto

I am building a navigation by state with a list of cities under each state. To look like this:

CA
   Los Angeles
   San Diego
   Modesto
KS
   Wichita
   Kansas City


texts: Craft Commerce: Soft Delete on Payment Methods?

texts:
I was just playing around with my payment methods. I deleted them. Then I tried to re-add them with the same names and settings but I couldn't. "Name "Manual" has already been taken."

Apparently they have been soft deleted? How do you reinstate a soft delete?


texts:
I'm relatively new to CraftCMS, so feel free to smack me upside the head if I'm missing something obvious.

We have an ElasticSearch provider that I'd like to use instead of Craft's default search.

The file at /app/etc/config/common.php appears to be a dependency injection system that should make replacing core components relatively easy, and
the class defined in /app/services/SearchService.php looks simple enough to replace with a custom solution.

Unfortunately I'm having trouble finding documentation around replacing core components, and I'm not having much luck finding any way to override the common config file from outside the core application.

It might be that I'm going about this the wrong way, and I'm totally open to suggestions. Either way, thanks in advance!


texts: Sprout Email: object variables will not resolve in text and redactor field since upgrade

texts:
I upgraded my whole system: Craft Pro (2.9.2 to 3.5.15.1), Sprout Email Pro (2.4.7 to 4.4.8), and several others.
After fixing many errors, most occurred with Sprout Email, I now have only one major problem with Sprout Email: object variables will not resolve in text and redactor field in emails, although it has worked for several years before!
Object variables in the subject line will resolve and be shown in emails, all others are output as text: { myObjectVariable }
I changed the syntax to {{ object.myVariable }}, but it doesn't work with that either!
One interesting thing: When I click on preview in the notification email list, the {{ object.myVariable }} are replaced with the values from the last submitted form (= saved entry), the { myObjectVariable } are not.
What is going wrong?


texts: Is it possible to filter entries based on entry table field values?

texts:
I have an entry called "reviews" and within reviews I have a table field with several values. I would like to use the field values to display entry listings in a particular way.

First: I would like to be able to display entry listings so that if the field value is = x to display a particular set of entries.

Second: I would like to be able to display these values so that they are in an ascending order.


texts: Site is inaccessible after updating plugin with new attribute/db column

texts:
I'm making some modifications to a custom plugin. I added a new attribute to one of the models and created a migration to add a new database column to hold that attribute. I updated the version number in my main plugin file and everything ran smoothly in my local environment. However in production I get "an unknown error occured" with no actual PHP errors or Craft errors being logged. This is after Craft tries to perform it's database updates (and tells me it went successfully).

Running Craft 2.6.2982


texts: How to handle entry save in plugin when entryId is not set?

texts:
Referring to my older question, I have the entryId working on an existing entry. However I've noticed a new entry doesn't have an entryId set (makes sense).

I have some custom information in text fields that needs to be saved after onSaveEntry is fired (which I have working). I have a custom model, record, controller and service setup. In my controller I retrieve these custom text fields including the entryId field from Craft. But because a new entry doesn't have an entryId set yet, my controller/service is not working as it should.

When the entry is saved and the page redirects to wherever, I also lose all the information in the text fields. So that's why I want to save my custom information directly after the entry is saved.

My question is, how do I handle this when I don't have the entry id. I don't want the user saving the entry first (to basically generate the entry id), then fill in the custom text fields and then save again (which works). But I think this is very devious.

This is my controller:

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

   if ($id = craft()->request->getPost('recordId')) {
          $model = craft()->plugin->getRecordById($id);
     } else {
        $model = craft()->plugin->newRecord($id);
   }

   $model->entryId = craft()->request->getPost('entryId');
   $model->customField = craft()->request->getPost('customField ');

   if ($model->validate()) {
       craft()->plugin->saveRecord($model);
   }
}

This is the service:

public function saveRecord(PluginModel &$model)
{
    if ($id = $model->getAttribute('id')) {
        $pluginRecord = PluginRecord::model()->findById($id);

        if (!$pluginRecord) {
            throw new Exception(Craft::t('Can\'t find record with ID "{id}"', array('id' => $id)));
        }
    } else {
        $pluginRecord = new PluginRecord();
    }

    if ($model->validate()) {
        $attributes = array(
            'entryId' => $model->entryId,
            'customField' => $model->customField,
        );

        foreach ($attributes as $k => $v) {
            $pluginRecord ->setAttribute($k, $v);
        }

        if ($pluginRecord ->save()) {
            // update id on model (for new records)
            $model->setAttribute('id', $pluginRecord->getAttribute('id'));
            return true;
        } else {
            $model->addErrors($pluginRecord->getErrors());
            return false;
        }
    }
}

The rest of the plugin can be found here for reference: https://github.com/iNalgiev/webtexttool1


texts:
Trying to display the author photo of the entry (it's there for sure).  The Craft 2 way I used entry.author.photoUrl but that is not working so I tried entry.author.photo.url and that does not show anything and no error or warnings.

Is what I am doing correct?


texts: Paypal Express shows a 404 error when returning to Commerce's completePayment endpoint

texts:
I'm trying to use Paypal Express with Craft Commerce.
It sends us Paypal's login page correctly, with the right amounts, but when you click pay it returns us to this URL:

/index.php/actions/commerce/payments/completePayment?commerceTransactionId=43&commerceTransactionHash=cbcad33abe2cf99ea63c8ee49c0ee9af&token=EC-0N649078HJ025430W&PayerID=VAWBVKWL78DHN

but shows a 404 error with no other errors

I've tried using the show errors code mentioned in this post:
Handoff to Paypal Express with Craft Commerce

and I've tried it with Stripe which fully works.

There are no log error logs in PHP or Craft's logs, just a 404.

I've tried changing different products, different shipping types, I've uninstalled all other plugins.

It just fails with Paypal, and works with Stripe.

Any ideas?


texts:
I'm running Craft CMS with MAMP at localhost:8888.

When I pass in a URL with {{ entry.title }}, I get http://localhost/news/2016/we-just-installed-craft which gives me a 404 until I manually put in the :8888 after localhost.

Am I missing something in the set up here?


texts: Unable to set planAmount for Charge 2 - Stripe

texts:
I keep getting an error response for my test field for Charge. I've pretty closely followed the example just for testing and can't seem to get a successful charge.

I've tried setting a hidden field for amount and planAmount to no success.

Error:

array(1) {
  ["errors"]=>
  array(2) {
    [0]=>
    string(37) "planAmount : Amount must be a number."
    [1]=>
    string(74) "There was a problem with your details, please check the form and try again"
  }
}

Form:

<form method="post" id="charge-form" class="charge-form">
    <input type="hidden" name="action" value="charge/charge">
    {% set options = {
        'planAmount': 79,
        'planInterval': 'year',
        'planIntervalCount': 1,
        'planCurrency': 'aus',
        'actions': {
            'onSuccess': {
                'subscription': 'gold-membership'
            }
        }
    } %}
    {{ craft.charge.setPaymentOptions(options) }}

        Receipt Email
        <input type="text" name="customerEmail" value="{{ charge is defined ? charge.customerEmail : currentUser ? currentUser.email }}" id="customerEmail">
        {% if charge is defined %}{% for error in charge.getErrors('customerEmail') %}{{ error }}{% endfor %}{% endif %}

        Card Number
        <input type="text" data-stripe="number" placeholder="•••• •••• •••• ••••" id="cardNumber">

            Expiration (MM/YY)
            <input type="text" size="2" data-stripe="exp_month">

         /
        <input type="text" size="2" data-stripe="exp_year">

        Card CVC
        <input type="text" data-stripe="cvc" placeholder="123" id="cardCvc">

    <button type="submit">Upgrade</button>
</form>

JS:

Stripe.setPublishableKey(this.s.publicKey.test);
$(window).charge(this.s.form);


texts: Cannot remove index.php from URLs either

texts:
I am having the same issue as here: Another index.php?p= problem

I tried to post this as a comment rather than open another post but I don't have enough reputation...

I have tried all of the suggestions listed and none of them are working. Without index.php I get 404's.

I've tried with the rule applied to the config file it breaks the admin (doesn't load asset files like css - they're still pointing to URLs with index.php) and I still get 404's on the entry URLs.

I also double checked with the hosting company on the apache configurations and the AllowOverride All is indeed set.

Here is my htaccess file:

<IfModule mod_rewrite.c>
    RewriteEngine On

    # Send would-be 404 requests to Craft
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !^/(favicon\.ico|apple-touch-icon.*\.png)$ [NC]
    RewriteRule (.+) index.php?p=$1 [QSA,L]
</IfModule>

I did try to add RewriteBase / just below RewriteEngine On and nothing happened. I also verified the file is actually working by adding invalid stuff in it and getting a server error.

I've tried this in my general.php config file:

return array(
    'omitScriptNameInUrls' => true,
);

And this version:

return array(
    '*' => array (
        'omitScriptNameInUrls' => true
    )
);

When I do, it doesn't fix the index.php issue, but it removes index.php from the admin, but breaks the admin because the assets 404 (mentioned above).

Any other suggestions out there?

Thanks!


texts:
i'm running a macOS 10.15 Beta (to check out SwiftUI) but now i'm running into problems with craft, specifically with the php zip extension.

It's PHP 7.3.5 and i can't update it, because the install process doesn't recognize my system as an macOS above 10.6 :/

Has anyone an idea how to get the craft installation running under macOS 10.15 or how to fix the specific problem with the missing php zip extension?

Thanks in advance.


texts: Using `getPrev` and `getNext` with entries sorted by SuperSort plugin?

texts:
I applied the superSort plugin function to a list of entries and it works perfectly:

{% set entries = craft.entries.section('sectionName').type('entryType').order('entryTitle')|supersort('natsort') %}

Trying to apply it to an entry page with this code to get the previous and next entry. It does not work:

{% set arrowParams = craft.entries.section('sectionName').type('entryType').order('entryTitle')|supersort ('natsort') %}
{% set prevEntry = entry.getPrev(arrowParams) %}{% set nextEntry = entry.getNext(arrowParams) %}
  {% if prevEntry %}
    {{ prevEntry.title }}
  {% endif %}

  {% if nextEntry %}
    {{ nextEntry.title }}
  {% endif %}

Thanks for helping!


texts: How would I pass an entry URL to an iframe in a template?

texts:
I'm trying to showcase some responsive code and would like to create entries just with that code example. I would like them to appear in a template that has some js to resize an iframe and show responsiveness of the entry.

Any thoughts on how I can accomplish this?


texts: How do I force www in URL along with the Patrol plugin to force https

texts:
I'm using the Patrol plugin to force https in the domain, but I also need to force www into the URL. When I do that with some htaccess rewrite rules I found online I get an error when I try to load the site that there's too many redirects happening.

This is my htaccess code

<IfModule mod_rewrite.c>
RewriteEngine On

RewriteRule ^(.*)/$ /$1 [L,R=301]

# Send would-be 404 requests to Craft
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/(favicon\.ico|apple-touch-icon.*\.png)$ [NC]
RewriteRule (.+) index.php?p=$1 [QSA,L]

And this was the code to force WWW that I was trying unsuccessfully to use that resulted in the "too many redirects" error.

<IfModule mod_rewrite.c>
RewriteEngine On
#force www in URL
RewriteCond %{HTTPS_HOST} !^www\.adacore\.com
RewriteRule (.*) https://www.adacore.com/$1 [R=301,L]

RewriteRule ^(.*)/$ /$1 [L,R=301]

# Send would-be 404 requests to Craft
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/(favicon\.ico|apple-touch-icon.*\.png)$ [NC]
RewriteRule (.+) index.php?p=$1 [QSA,L]

I'm not sure how or if the Patrol plugin (https://github.com/selvinortiz/craft.patrol) factors into the htaccess file to be honest. Any idea what I'm doing wrong?


texts: Can I disable channels in Redactor "Link to entry" feature?

texts: I have some channels with entries that I don't want my client to be able to link to using Redactors "Link to entry" feature. Can I disable some channels for a specific field in a specific channel/structure/single?