texts: How to use required fields on localised entries?

texts:
I'm building a multi-lingual site and have found Craft's locales / translatable fields useful for setting up structures where each page will have a translated version. However, for at least one of the Channel sections it would make more sense to have separate entries for each locale, rather than having each entry being translatable and appearing in all locales.

This seems doable by disabling all but one of the locales on each entry in the section, but the problem I'm having is that if an entry has required fields, I can't save it if these fields are empty, even if they're only empty in a locale that I'm trying to disable. (eg. I want to have a Spanish-only post, but when I try to disable the English version I can't save the post because the English version has required fields that aren't filled in...)

It seems I either have to make my required fields non-required, or fill them with spurious stuff in the locale I want to disable. I'm sure there must be a way of making required fields work with multi-lingual posts, but I can't figure out quite how... I'd be grateful for any pointers here!


texts: Possible to set 2 data fields within 1 select option?

texts:
I have the following code in my form, but I'd like to also save the eventDate of the selected entry into a separate date field to enable sorting/selection later.

<label for="eventName">Event
<select id="eventName" name="fields[eventName]">
  <option value="">select from list</option>
    {% set events = craft.entries.find({section:'events,activities', eventDate : ">= " ~ now.w3cDate() , order:'eventDate'}) %}
    {% if events %}
        {% for entry in events %}
            <option value="{{ entry.eventDate.format('D j M') }},{{ entry.eventName }}">{{ entry.eventDate.format('D j M') }},{{ entry.eventName }}</option>
        {% endfor %}
    {% endif %}
</select>
</label>


texts: Getting Matrix content from within a relationship field

texts:
Here are my channels and fields I need to get to work together.

Blog Channel (blog)

Matrix Field (bodyMatrix)

Gallery Block (gallery)

Gallery Field (galleryInclude [entries])

Gallery Channel (gallery)

Matrix Field (galleryMatrix)

Slide Block (slide)

Slide Image Field (slideImage [assets])
Slide Text Field (slideText)

In my Blog Channel, I have a Gallery block inside a Body Matrix field. This Gallery block contains just an Entries relationship field that is pulling from my Gallery channel.

Inside the Gallery channel is a Matrix field as well, with a single block for slideImage and slideText.

This being my second day working with Craft, but years of experience with EE, how do I pull in the content from that Gallery entry and it's Gallery Matrix?

I've been able to pull in that Gallery title, but can't at all get the Gallery Matrix to output anything.

{% for gallery in block.galleryInclude %}
  {{ gallery.title }}

    {% Gallery Matrix %}

    {% end Gallery Matrix %}

{% endfor %}

I'm not even sure when I use 'gallery' above, if that's the right variable to use, but it works.


texts: Best way to handle redesign of large site

texts:
I have no experience using Craft but will be redesigning a large site using Craft. Most of the content will not be moved or restructured, I'll mostly be making cosmetic changes with HTML and CSS.

What is the best way to redesign a site while it is already live? I'd like to keep the CMS active whilst I'm making changes so that other people on my team can keep adding content before activating certain pages.


texts: Set password for user when create from CP

texts:
I would assign the password and send it to the user in an email when I create that user from Backend Control Panel.  I have the following code, but I got False return on craft()->users->saveUser($user). I also try to use users.onSaveUser trigger, still no luck. Does anyone know how to save the random password to the user? Thanks

craft()->on('userGroups.onAssignUserToGroups',function(Event $event) {
    $user_id = $event->params['userId'];
    $user = craft()->users->getUserById($user_id);
    $userId = craft()->request->getPost('userId');
    $isNewUser = !$userId;

    $email = new EmailModel();
    $emailSettings = craft()->email->getSettings();
    $email->fromEmail = $emailSettings['emailAddress'];
    $email->sender = $emailSettings['emailAddress'];

    if ($isNewUser) {
        /* generate random password */
        $randomPassword = $this->getRandomString(8,false);

        /* set random password to user */
        $user->newPassword = $randomPassword;

        if (craft()->users->saveUser($user)) {
            $result = "success";
        } else {
            $result = "fail";
        }

        $email->subject = 'confirm created email'
        $email->body = "Text to user".$result;
        $email->toEmail = $user->email;

        craft()->email->sendEmail($email);
    }
});


texts: Can Auth0 be used for Craft Commerce user accounts?

texts: I want to use Auth0 to provide a Single Sign On (SSO) for a couple of services I am integrating, one of which is Craft Commerce user accounts. Does Craft Commerce allow something like Auth0 for authentication?


texts: Starting & Ending Loops with Eager Loaded Elements

texts:
Basically, I have two sections of a page. In one section of the page, I want to output the first 8 entries in a loop. In the next section of a page, I want to output from the 9th entry to the end of the loop. The entries that I'm looping through are eager loaded.

This is how I'm doing it right now:

{% set clients = element.clients.find({
    with: [
        ['logo', {
            withTransforms: ['newClientLogoPage']
        },]
    ]})
%}

SECTION #1:
{% for client in clients %}
    {% if loop.index0 <= 7 %}
        DO SOME STUFF

SECTION #2:
{% for client in clients %}
    {% if loop.index0 >= 8 %}
        DO SOME STUFF

Essentially, I'm fully looping through the same entries twice and just starting and ending what is output at different spots using loop index.

Is there a better / more efficient way to start and end my loops at different points without doing two full loops like I am now?


texts: Craft CMS logo still showing on CP Login page

texts: We have uploaded a logo in the CP, but the CP Login page still has the craftcms logo under the login box. Perhaps a config setting to remove this that I don't know about?


texts: Output of matrix field twice in one template

texts:
I have a matrix field with with multiple types. In a template I want to loop through all of the entries of that matrix field as you normally would. However, I also want to access a bit of data from a specific type and I can not figure out how to do it. Very frustrating. Definitely would have been a no brainer to do in craft 2.5.
The matrix field has a type of "Instructor" which is an entry type. The entry has a field of "FullName".
So I want to say, if there is an entry type of Instructors in the matrix field, then output the full name of each entry selected in the matrix field of type "Instructor".
I've tried various methods based on the matrix blocks documentation and nothing works. The closest I get is the ID of the matrix field entry. Here is one example that should explain what I'm attempting to do.
  {% set classBlocks = entry.classBlocks %}
  {% if classBlocks|length %}
    {% set instructors = clone(classBlocks).type('instructors').all() %}
    by <strong>
      {% for instructor in instructors %}
        {% if not loop.first %}, {% endif %}
        {{ instructor.fullName }}
      {% endfor %}
    </strong>
  {% endif %}

Is this even possible? Seems pretty simple. At least in craft 2.5 I could have just looped through the matrix field and if the type was 'instructors' loop through the instructor entries outputting their full name.


texts:
I'm using an assets directory with Amazon S3 and I have to manually update the indexes through the control panel after uploading files externally. Does anyone know if it is possible to do anything custom to do this on login. Or is it possible to set up a URL that could be hit with a cron or manually.

One idea I had failing any of the above would be to do a custom plugin with just a button to make it a bit quicker than the current method through the settings.


texts: Unable to set slug to value used previously

texts: I have an entry whose slug I would like to set to 'archive', but when I save it, it is 'archive-1'. There is no existing entry with slug of 'archive' (craft.entries.slug('archive') returns null). There have been previous entries with that slug.


texts: In Craft 2.5, how can you sort the entry index page by a custom field?

texts:
I recently updated a very large site to Craft 2.5. One of the great new features is the ability to view custom fields as columns on the entry index page.

Previously, I used the DashCols plugin to view those columns, but DashCols was rendered obsolete by the Craft 2.5 release. However, there was one other feature that DashCols has, which Craft 2.5 doesn't have...

How can you sort by custom fields on the entry index page?


texts: being replaced by  tags in redactor rich text editor

texts: I have read previous questions and answers about the redactor rich text editor but in this version of Craft i only found simple.json and standard.json under craft/config/redactor. I have tried with both but <div> tags are still replaced by <p>. Is there another way to add <div> into a redactor rich text field?


texts:
Using Craft 2. Here's my code, which sends the email fine if I remove the attachment part. Can anyone point me in the right direction?

$email = new EmailModel();
$email->toEmail = $toEmail;
$email->cc = $ccEmail;
$email->bcc = $bccEmail;
$email->subject = $subject;
$email->body = $body;
//$email->attachments = $attachments;

$attachments = [
  ['path'=>'http://website.localhost/img/uploads/nameoffile.pdf',
  'name'=>'afile',
  'encoding'=>'base64',
  'type'=>'application/pdf']
];
if (!empty($attachments)) {
  foreach ($attachments as $attachment) {
    if ($attachment) {
      $email->addAttachment($attachment['path'], $attachment['name'], 'base64', $attachment['type']);
    }
  }
}

if ($email->getErrors()) {
  throw new Exception('there are errors'); // exception not returned
}

// SEND THE MAIL
if (craft()->email->sendEmail($email)) return true;
else throw new Exception('not sent'); // returns this exception


texts:
So I am working on converting a previously-standalone Yii 2 app into a Craft module and am having some issues with routing.  I wish to keep my old URL structure as much as possible.  As such, I created a plugin and register routes.  However, I've noticed an issue: When I call Url::to(), I get back URLs that seem to rely on the actionTrigger parameter, even if I explicitly defined routes in my plugin.

Here are the routes as I have them in my plugin:

class CustomerPortal extends \craft\base\Plugin
{
    public function init()
    {
        Event::on(
            UrlManager::class,
            UrlManager::EVENT_REGISTER_SITE_URL_RULES,
            function(\craft\events\RegisterUrlRulesEvent $event) {
                $event->rules['portal/<action:[\w-+]>'] = 'customer-portal/portal/<action>';

If I make the call in a controller to redirect to a route, it builds the URL using an action param, not the rules we defined.  For example:

class UserController extends \craft\web\Controller
{
    public function actionRedirect()
    {
        echo Url::to(['checkout');
        // I'd expect to see '/checkout', but instead we get
        // '/actions/customer-portal/user/checkout' since we aren't
        // applying either of our rules.
    }

    public function actionCheckout()
    {
    }

It seems that the rules are checked when parsing, but not during URL creation, and if you come in with an action prefix, the rules aren't parsed then, but the raw action is attempted.

Am I missing something or is this a bug and either way, can anyone think of a way to work around it?

Edit: Figured out the issue with routes not resolving I had originally, it turns out in the end, my issues was that the regex in the rules wasn't accounting for the fact that many of routes have dashes in them (for example: /user/billing-info).  The default Yii docs say to use <action:\w+>, but that doesn't match the dash character in the URL.  Using <action:[\w-]+> works perfectly and makes this all work.

That said, I'm still not getting Url::to or anything else that references UrlManager to work properly since UrlManager seems to add the action param to the URL before checkout to see if we match existing routes.


texts: Plugin DB migration add "not null" column

texts:
I set up a quick and dirty migration to add two columns to two tables. These are to be basically boolean 1/0 switch fields. I'm setting up my migration file as follows, note the 'not null' in both column types:

<?php
namespace Craft;

class m171020_153541_grnplatform_AutoRenewUpdate extends BaseMigration
{
    public function safeUp()
    {

        $this->addColumn('grnplatform_payment_cards', 'expireNotified', "tinyint(1) unsigned NOT NULL DEFAULT '0'");
        $this->addColumn('grnplatform_subscriptions', 'failedRenew', "tinyint(1) unsigned NOT NULL DEFAULT '0'");

        return true;
    }

    public function safeDown() {

        $this->dropColumn('grnplatform_payment_cards', 'expireNotified');
        $this->dropColumn('grnplatform_subscriptions', 'failedRenew');

        return true;
    }
}

However after the migration runs, my show create table command yields this:

CREATE TABLE `craft_grnplatform_subscriptions` (
  `id` int(11) NOT NULL,
  `userId` int(11) NOT NULL,
  `active` tinyint(1) unsigned NOT NULL DEFAULT '1',
  `renewalPeriod` enum('monthly','quarterly','yearly') COLLATE utf8_unicode_ci DEFAULT NULL,
  `autoRenew` tinyint(1) unsigned NOT NULL DEFAULT '0',
  `lastRenewal` date NOT NULL,
  `nextRenewal` date NOT NULL,
  `failedRenew` tinyint(1) unsigned DEFAULT '0',
  `dateCreated` datetime NOT NULL,
  `dateUpdated` datetime NOT NULL,
  `uid` char(36) COLLATE utf8_unicode_ci NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  UNIQUE KEY `craft_grnplatform_subscriptions_userId_unq_idx` (`userId`),
  KEY `craft_grnplatform_subscriptions_nextRenewal_idx` (`nextRenewal`),
  CONSTRAINT `FK_craft_grnplatform_subscriptions_craft_grnplatform_vendor_data` FOREIGN KEY (`userId`) REFERENCES `craft_grnplatform_vendor_data` (`userId`) ON DELETE CASCADE,
  CONSTRAINT `craft_grnplatform_subscriptions_id_fk` FOREIGN KEY (`id`) REFERENCES `craft_elements` (`id`) ON DELETE CASCADE,
  CONSTRAINT `craft_grnplatform_subscriptions_userId_fk` FOREIGN KEY (`userId`) REFERENCES `craft_users` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

Notice how the "not null" is missing from the column declaration for 'failedRenew`...

How can get set the NOT NULL value on a column I'm adding from a migration?


texts:
I have a controller in the console folder. How can I call this controller via ajax please?

I tried to config a route in Routes.php, and then call this route by jquery Get() function. But none of these below work...

'api/v0/hub-loader/<sheet_id:\d+>' => 'craftplugin/import-hubs/test',
'api/v0/hub-loader/<sheet_id:\d+>' => 'craftplugin/console/controllers/import-hubs/test',
'api/v0/hub-loader/<sheet_id:\d+>' => 'craftplugin/console/import-hubs/test',

All these routes return 404 page not found error


texts: How to reference Twig form values from within controller action?

texts:
I have a form and a hidden action that successfully runs the controller action.  I now want to include 2 variables (form input values) and then use those values while I am in the controller action.  How do I grab the value (theemailaddress) that was in the form?

Twig template file:

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

<input type="hidden" name="action" value="psychEmail/publication/pubRequest">
        <input type="text" name="theemailaddress" value="" size="100">

        <!-- ...-->

        <input class="btn submit" type="submit" value="{{ 'Submit'|t }}">
    </form>

function IN controller:

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

    $email = new EmailModel();
    $email->fromEmail = 'email@school.edu';
    $email->toEmail = 'myemail@gmail.com';
    $email->subject = 'Publication Request';
    $email->body    = 'Your requested publication is attached.';

    craft()->email->sendEmail($email);
}


texts: Using cache tag on array outputs nothing

texts:
Okay. I've figured it out but it left me with the question. After some page refreshes It's got stack back at empty output again.

Bad:

{% cache %}
  {% for item in orders %}
    {# Following variable was the problem #}
    {% set cart = item.cart %}
    {# Loop in cart's table fields: title and quantity #}
    {% for row in cart %}
      {% set data = data|merge([{ title: row.title, quantity: row.quantity }]) %}
    {% endfor %}
  {% endfor %}
{% endcache %}

On second page load it outputs nothing. So I simply call for a check like this.

{% for item in data %}
  {# for example #}{{ item.title }}
{% endfor %}

Good:
This is my current state of the code design. It's a bit extended to the original post. But a problem may be in data merging into an array.

{# Prep array #}
{% set data = [] %}

{% cache %}
  {% for item in orders %}
    {# Loop in cart's table fields: title and quantity #}
    {% for row in item.cart %}
      {% set data = data|merge([{ title: row.title, quantity: row.quantity }]) %}
    {% endfor %}
  {% endfor %}
{% endcache %}

{% set someProduct = 'someProduct' %}
{% set someOrderQuantity = 0 %}
{# Count order's quantity #}
{% for item in data %}
  {% if someProduct = item.title %}
    {% set someOrderQuantity = someOrderQuantity + item.quantity %}
  {% endif %}
{% endfor %}

Setting variable cart to reuse in orders loop and wrap  in cache tags wasn't good idea because it outputted nothing. So I had to take cart variable out. It worked out but I don't know why was setting variable in entries loop for another loop causing that empty output?
I properly don't know how cache tags works?


texts: Using CTA Buttons as Supplemental Subnav

texts:
I am a content administrator for a major US city that's using Craft CMS. The content categories for our website (i.e., Resources, Services, Topics, etc.) are great for providing different ways to input and display information. But they also serve as a left-hand side navigation set on pages that have content in each of those categories. The problem is that these content categories provide very little context for visitors regarding the topics for those Resources, Services, and so forth.

To help alleviate this problem, I am seeking to create a supplemental subnavigation menu that allows people to go to landing pages that provide more context for visitors seeking different types of information or services (see attached mock-up). I really like how CTA buttons appear toward the top of index pages, and think they could serve as quick and accessible ways of linking people to subpages on our department's website.

Is there a way to customize the Craft CMS to allow for multiple CTA buttons on select landing pages (perhaps up to 8 buttons total)? Or are there more elegant ways to create a useful supplemental sub-nav menu?

Thanks in advance for any advice folks may have on this!


texts: How do you setup CloudFront in P&T S3 plugin & how do you know if it works?

texts:
I have the P&T Amazon S3 plugin.   It's connected to my S3 bucket.  It stores a few test .PDF files.   It is working.  I am able to access the files - and the URL is that of my S3 bucket - i.e., my-bucket-name.s3.amazonaws.com/filename.pdf

I created a CloudFront distribution.   It is deployed and enabled.

I added my CloudFront Distribution ID to the CloudFront Distribution ID field in the plugin.   Do I need to add the distribution's Domain Name to any of the plugin's settings?

How do I know if the image is being accessed through CloudFront?  The URL has not changed - i.e., - i.e., my-bucket-name.s3.amazonaws.com/filename.pdf

I can access the .PDFs in my S3 bucket using the CloudFront domain name -- i.e., cloud-front-domain-name.cloudfront.net/filename.pdf.


texts: Where can you set a form field to required in the DB

texts: Can someone point me to where in the DB you set a field as required? I am actually wanting to do this on a Sprout Forms field I am not sure if that makes a difference or not. I can't find which table you would do that in.


texts: Setting Google maps circles using Smart Map plugin

texts:
So, I'm trying to set circles around marker locations using Smart Map and some JS.
I've got the following which gives no errors, but outputs no circles.
$(function () {

  $.each( smartMap.marker, function( key, value ) {

    var circle = new google.maps.Circle({
                    map: smartMap.map['smartmap-mapcanvas-1'],
                    radius: 40233,    // 25 miles in metres
                    fillColor: '#000000'
                 });
    circle.bindTo('center', marker, value.getPosition());

    });

  });

});

I'm out of ideas at this point!


texts:
Is there a quick an easy way to change the asset thumbnail size when it's attached to an entry?

By default this is quite small and restrictive and would like to show a more representative version of the image when add/editing each entry.

I would have thought this is possible using a transform but how would this be tied back to the entry form?


texts:
I am getting an error with oauth (1.0.79) when using Facebook:

  Required option not passed: access_token Array (
  [{"error":{"message":"Error_validating_verification_code__Please_make_sure_your_redirect_uri_is_identical_to_the_one_you_used_in_the_OAuth_dialog_request","type":"OAuthException","code":100,"fbtrace_id":"A2ThFvRVsAZ"}}]
  => )

Facebook is changing the url entered and replacing the /'s in the p=actions/oauth/connect part of the redirect URI with ASCII characters %2F p=actions%2Foauth%2Fconnect which I assume is then not matching the 2 uri's causing the above error.

Is this the issue? Is there a workaround? Or is this a tweak that needs to be made to oauth?

Cheers


texts: Apologies if this has already been brought up but shouldn't each input have a unique id? I assumed Freeform would prepend the input ids with the form id or something but it seems it just duplicates ids everywhere. Doesn't seem great for what is a pretty expensive plugin.


texts: Is it possible to include a thumbnail in an element type index view?

texts:
I'm trying to emulate what Assets does, in which a thumbnail of the asset is shown along side the title of the asset. When I alter the _toString() method of the model, what I get is the URL instead of the image (the URL is being added to the data-label attribute of the containing div).

Is there a way to accomplish what I'm after?


texts: In Commerce, can I apply a discount only on a specific number of one product?

texts:
I know that I can apply a discount if a specific number of products is ordered. I could also add a discount for a specific product, with a specific amount. But, am I able to create a discount with this conditions:

Applies to entire product type
A specific number of one product is added to the cart

So, if I set this discount for 3 products, but people buy 2 x PRODUCT A, 1 x PRODUCT B, it would not apply. If customers buy 3 x PRODUCT A, 2 x PRODUCT B, it would apply for product A.

I could probably fix it with a plugin, but is it possible out of the box? Am I missing something?


texts: Element API using the entries field to display related content from a separate section

texts:
I've seen similar questions but none seem to help.
I have two sections named jobs and jobDescriptions. I'm using the entries field to pull in a description field from the jobDescriptions section to the jobs entry. I need to output the related description field to the element api but I'm stuck. No idea where to go from here.
The other issue is that I also have a field in the jobs section that is named descriptionOverride. I want to show the descriptionOverride field if it has a value instead of the related field.
<?php

use craft\elements\Entry;
use craft\helpers\UrlHelper;
use craft\elements\Tag;
return [
    'endpoints' => [
        'jobs.json' => function() {

            return array(
                'serializer' => 'jsonFeed',
                'elementType' => Entry::class,
                'criteria' => array('section' => 'jobs'),
                'transformer' => function(Entry $entry) {

                    return array(
                        'title' => $entry->title,

                        {# pulling the description field from the jobDescriptions section using the entries field relatedJobDescriptions in the jobs section. I'm obviously
way off base. #}
                        'description' => $entry->relatedJobDescription->description,
                    );
                },
                'meta' => array(
                    'description' => '',
                ),
                'pretty' => true,
            );
        },

        'jobs2.json' => function() {

            return [
                'serializer' => 'jsonFeed',
                'elementType' => Entry::class,
                'criteria' => ['section' => 'jobs'],
                'transformer' => function(Entry $entry) {

                    return [
                        'title' => $entry->title,
                    ];
                },
                'meta' => [
                    'description' => 'Recent news from Happy Lager',
                ],
                'pretty' => true,
            ];
        },
    ],
];


texts: Blank white pages after moving index.php

texts:
I was developing a site on my server. Craft was living at ~/mysite.com/craft/, the webroot was ~/mysite.com/www/, and the URL was dev.mysite.com.

Now I want to deploy the site to www.mysite.com, but the host (HostGator) requires that the hosting account's primary domain (www.mysite.com) point to ~/public_html/. Ok, fine. First, I changed the dev subdomain to point to ~/public_html/ instead of to ~/mysite.com/www/. Then I moved the index.php and .htaccess from ~/mysite.com/www/ to ~/public_html/ and updated the $craftPath variable to point to the proper directory, but now all I get is blank white pages, both on the frontend and the admin.

I deleted everything under the craft/storage/runtime/cache/ and craft/storage/runtime/logs/ directories, opened up an incognito Chrome window, and pointed it at dev.mysite.com/admin (which is now pointing and .htaccess-requesting ~/public_html/index.php?p=admin, I believe...). I get redirected to dev.mysite.com/admin/login, but still end up with only a blank white page there.

The only [error] appearing in the log file is related to testPathInfo:

2016/06/08 21:52:06 [error] [application] Unable to determine if PATH_INFO is enabled on the server: [curl] 6: Couldn't resolve host 'dev.mysite.com' [url] http://dev.mysite.com/index.php/testPathInfo

Halp?


texts: How to Cache Globally Except for One Page

texts:
I have a template element that is used on almost every page of the site. I would like to cache that element globally, except on one particular page I would like it to just be a normal cache based on the page URL.

The current code I'm using is below, which is not working as intended. The global cache is still working on entry id 126.

{% cache globally using key 'entry_' ~ entry.id ~ '_elements' unless entry is not defined or entry.id == '126' %}

What would be the best way to make that functionality work without slowing down any other pages? Thanks!


texts: Is it possible to create a cleaner replace?

texts:
any help on this one appreciated.

I have an entry url that is automated to take several fields and make the the uri.

It pulls the jobTitle, jobCity and jobId fields and then... well... this:

jobs/{jobTitle|lower|url_encode|replace("%20", "-")|replace("%2C","")|replace("%80","")|replace("%E2","")|replace("%8B", "")}-{jobCity|lower|url_encode|replace("%20", "-")|replace("%27", "")}-{jobId}

As you can see... it is a tad... long.

The problem I have is the % stuff that creeps in. Some times the job titles have odd characters that the url encode converts into % symbols. These then break the url and stop craft from displaying the page.

My short term solution has been to add lots of replace's for each one, but is there way to make a replace that uses a wildcard - so if it sees % it replaces the next two characters as well?

Something like:

|replace("%wildcard","-") etc

The current replaces work, but it just feels unwieldy.

Many thanks for any advice.


texts:
I've been looking at the documentation for a long time now and can't figure out how to create several custom shipping methods in Commerce 2. Does anyone have any examples of how this can be achieved?
I think you may have to use the adjuster model, but having an example would help me a lot.
Thank you!


texts:
I'm querying a dropdown field to loop through all of the options and followed best practice (so I thought) in the twig template. Does anyone know how to update for the deprecation below?
Deprecation message:

craft.fields.getFieldByHandle() has been deprecated. Use craft.app.fields.getFieldByHandle() instead.

Code line:
{% set siteOptions = craft.fields.getFieldbyHandle('siteSelector').settings.options %}


texts: How to populate a custom checkbox field with tag data dynamically?

texts: Hi wondering if this is possible. I have a custom checkbox field for user interests added to the user profile. Is there a way to populate the checkbox options dynamically using tag data?


texts: How can I split a discount/line item during checkout?

texts:
I have built a credit system that is working great. My original plan was to use the onOrderComplete event, but it turns out after testing I need to update the user's credits before they actually pay.

For example, A user could have one credit, but have two items in their cart. Or, have a quantity of two of any given item. Either way, the user does not have enough credits, and will have to pay for one of the items.

Here is how I am updating the user's credits:

// Get the user's credit entry to find out how many credits they have left.
$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section = craft()->config->get('section', 'myplugin');
$criteria->authorId = $user->id;
$criteria->status = null;
$criteria->limit = 1;

$entries = $criteria->find();

...

craft()->on('commerce_discounts.onBeforeMatchLineItem', function ($event) {

    foreach ($entries as $entry) {
        if ((int)$entry->qualifyingItem > 0) {
            $entry->setContentFromPost([
                'qualifyingItem' => ((int)$entry->qualifyingItem > 0) ? ((int)$entry->qualifyingItem - (int)$lineItem->qty) : 0
            ]);

            error_log((craft()->config->get('devMode')) ? 'CREDITS LEFT: ' . (int)$entry->qualifyingItem : '');

            if (craft()->entries->saveEntry($entry)) {
                error_log((craft()->config->get('devMode')) ? 'SUCCESS: credits successfully updated.' : '');
            } else {
                error_log((craft()->config->get('devMode')) ? 'ERROR: Could not update the user\'s credits.' : '');
            }
        } else {
            $event->performAction = false;
            error_log((craft()->config->get('devMode')) ? 'Uh - oh: User is out of credits . ' : '');
        }
    }
});

So it seems the credits are working a bit too well. Either everything is "free" or the user has to pay for everything. I am having trouble figuring out how to allow one item be "free" and the other is not.

Thank you for any suggestions!


texts: Searching entries by title's first initial only

texts:
We're looking to pull entries from a channel that starts with a specific letter. We've tried using Craft's search option, with 'C*', to pull any title with a word that starts with C. However, it's pulling entries whose second or third words begin with C as well. Is there another route we should consider to achieve this result?

{% set myQuery = craft.entries.section('channelName').limit(null).search('title:C*').order('title') | group('title|first') %}


texts: Query a Supertable using MySQL Stored Function

texts:
I have a supertable which lists stockists. Each stockist has a lat/lng for map location. On a page of the site i am implementing a map locator which will need to make an ajax request for the 10 closest stockists to a user supplied address. Basically I will need to query the supertable of stockists (in a plugin) to find these 10 closest. I have written a MySQL stored function to calculate distance between two pairs of lat/lngs. If I was doing raw sql on the database, the query would, for example, look like:

SELECT * FROM `craft_supertablecontent_stockistlist`
order by (GeocodeCalcDistance(field_lat, field_lng, -27, 153, "km")) ASC
limit 10

where GeocodeCalcDistance() is my stored function. I have tested this sql and it works.

Now to tranlate that into craft code! My stockists are stored in a supertable, which is defined wholly in the CP (i.e., I don't have custom Model/Record classes in a plugin for the data). How do I express this query in Craft logic? Usually you could do something along the lines of:

$criteria = '....';
$params = array('param1' => value1);
$stockists = RecordClass::model()->findAll($criteria, $params);

but I don't have a "record" class for the table data. I am pretty stumped. any clues greatly appreciated.


texts: Is it possible for a user group to be notified by email when a post is submitted using either the backend or a form on the front end?


texts: Is it possible to replace uploaded assets?

texts:
I have a site that uses several PDF forms that update from time to time. Instead of adding a new asset, I would rather replace the existing one.

I couldn't see how to do that from within the Craft admin. I suppose it's possible to do via FTP, but I'd really like it to be able to be done by the client.

Am I missing something, or is this not possible at this time?

Thanks


texts:
I have tried to get a number of plugins from the Plugin Store but each time on install, I get the following errors:

Status: Not Found

Response: {"error":"Template not found: internal_error.html"}

Has anyone seen this as well?


texts: Elegant Way To Pass Configuration To yiic?

texts:
I am trying to write a console plugin for yiic so that I can import data programmatically from an old site.

I have a multi configuration setup for the craft site. Is there an elegant way to tell yiic which configuration I am targeting (so that it opens the right database etc)?


texts: Is it a security risk to put Craft templates inside public root?

texts: Due to the way our build and deployment process works, it's convenient for us to have the Craft templates inside our /public/assets folder together with our css and javascript, instead of in /craft. Does this make the site less secure than having them outside of the public root?


texts: How to require form submission before template display?

texts:
I have a white paper PDF file that I want visitors to be able to download, but only after they've submitted a form with their contact information. How can I do this in Craft?

Currently, I'm using the Sprout Forms plugin to build a form, and I've set the redirect for the form to a template containing the download link. This does work, but seems clunky, and any visitor who has the URL for the download page can visit it without submitting the form.

How can I require a form submission before displaying the template with the download link to the visitor?


texts:
I'm trying to configure a rich text field to allow script tags for a demo section on the page.

I added the following settings and linked this to the field

    {
  buttons: ['html','bold','italic','unorderedlist','orderedlist','link','image'],
  plugins: ['fullscreen'],
  toolbarFixedBox: true,
  replaceDivs: false,
  paragraphize: false,
  replaceDivs: false,
  deniedTags: [],
  removeComments: false,
  cleanSpaces: false,
  cleanOnPaste: false,
  removeDataAttr: false
}

However, The script tag is still always removed on save. Is there some other setting i am missing?


texts: Is there a way to make all templates automatically private? Or do I really have to put an _ before every single one?


texts:
any help would be much appreciated.

I have Live Preview working on my entries ie. I can see and use the button, but the live preview won't update as I manipulate the content? It was working before so it is baffling me as to how it could stop working.

The only change I think I have made in that time is removing the open_basedir settings in my php.ini, but I wouldn;t imagine that would affect it?

Thanks,

Dc

UPDATE::

This is the htaccess code:

<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>


texts: Stop currency translation in Craft Commerce

texts:
I’m creating a multi language site (Arabic/English) with Craft Commerce. On the Arabic cart page I output item.total with the help of

{{ item.total|commerceCurrency(cart.paymentCurrency, convert=true, format=true) }}

The price is output like so: "دولار أمريكي 5.00".

It translates $ to دولار أمريكي) دولار أمريكي = American dollar) and I want it to be output like so: "$5.00".


texts:
I want to develop an API within Twig template that will have PDO implementation to get data. My application will be using content through CRAFT.
Is it possible to develop API with TWIG template?
Thanks


texts:
I'm trying to get tags out of the underlying craft DB and serve it as a REST endpoint - however, I'm only interested in exposing the tag id and title, so my data should look like this:

{id: 1, title: "hello"}, {id: 2, title: "test"}

I'm currently able to achieve this with the following query:

$tags = \craft\elements\Tag::find()->all();

The problem with this is that this returns all the fields the tag has. I then have to filter out the two fields I want by doing:

foreach($tags as $tag) {
   $out = [];
   $out['id'] = $tag['id'];
   $out['title'] = $tag['title'];
   return $out;
}

This is quite wasteful as I'm fetching a bunch of fields I don't need from the DB, then looping through all the tags and parsing out the two fields I need.

What I'd like to do instead is only fetch these two fields from craft in my query.

I found two possible ways of doing this - one of them uses the select method:

Something like

$tags = \craft\elements\Tag::find()->select(['id', 'title']).all();

The problem with the above code is that the SQL query which is executed by the above doesn't actually have fields called id and title due to aliasing and joins being carried out on multiple tables - therefore I'd have to know exactly which fields I want and in which table in the SQL schema they sit...this doesn't scale well for more complex queries.

I also found https://www.yiiframework.com/doc/api/2.0/yii-base-arrayable#fields()-detail which seems like it could be useful but I wasn't able to get this to work at all and the documentation isn't too helpful.


texts: Craft 3 validate new password in change password

texts:
I'm trying to validate user's new password and confirm password in my custom plugin init().

Event::on(User::class, User::EVENT_BEFORE_SAVE, function(Event $event) {
    $formData = $_POST;
    $newPassword =  $formData['newPassword'];
    $confirmPassword =  $formData['confirmPassword'];

    if ($newPassword != $confirmPassword){
        Craft::$app->session->setError('Confirm password does not match new password');
    }
});

On the template:

{% set error = craft.app.session.getFlash('error') %}
{% if error|length > 0 %}
    {{error}}
{% endif %}

The problem with this is, it displays the message "Confirm password does not match new password" on frontend but the password gets changed into newPassword value. Is there a way to stop processing any further after returning error?


texts: Plugin settings per site / locale (Craft 3)

texts:
This is a followup question to this question which asked about the possibility of per-site plugin config for Craft 3.

I'm a plugin author and have had a feature request for allowing my plugin to have different settings based on the current site. Looking at the above question, it sounds like this used to be possible in Craft 2:

<?php

return [
    'flagName' => [
        'de' => 'Bundesflagge',
        'fr' => 'Tricolore',
    ],
];

This doesn't work in Craft 3, alas (throws an error). I could write something into my plugin's admin area to loop through known sites and output config per-site but this seems like something Craft should be able to do out-of-the-box (especially given the above method used to be valid). Does anyone know if there's a good way to do this in Craft 3?


texts: How to change the display order of columns in Entry List view?

texts: When adding a custom column to an Entry List view using the modifyEntryTableAttributes hook, how would you also set the display order of columns?


texts:
Is it possible somehow to add custom fields to the users in Craft?
I'd like the users to be able to add a Bio.

I know I can add a channel but wondering if I am missing something obvious or if this would be a good feature request?

I'd like to add, bio, social media info ect, about the author etc.


texts:
Getting the following error on production environment when trying to add a new Field.

  CDbCommand failed to execute the SQL statement: SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'redacted' already exists

Anyone have any idea what could be causing this?


texts:
Tried doing an update to 3.6.x from 3.5.19 from the terminal and got this horrifying message:
``
Performing one update:
- craft 3.5.19 => 3.6.15

Backup the database? (yes|no) [yes]:yes
Backing up the database ... done
Performing update with Composer ... Killed
``
php version is 7.4.3
The Composer,json file was changed to require Craft 3.6.15, but looks like no other files were actually changed, there is nothing in the logs and, thankfully, the website is working fine.I have done similar updates on other sites without a problem. Any suggestions for how to troubleshoot this? "Killed" is not much of a starting point.
Thanks!


texts:
I am looking for some help with persistent form data.

If a user submits a front-end entry form for some Entries data, but there are errors with the submission, they are currently redirected to the entry page and successfully shown the errors (eg field is required). Is there a method or syntax where this form can also retrieve the posted form data so the user is not required to fill in the whole form again?

Many thanks for any help from the community!

Dan


texts: Show active parent's listed children when viewing it children

texts:
When I view a entry that's belong to a small group of children with a parent assigned. When I view the child, I want to display list all children that the child assigned to?

Is there anyway to achieve this method?


texts:
Craft 3 RC is installed locally. After clicking on the Plugin Store the loading animation stays for 1-3 seconds. After that, the right canvas leaves grey without content.

I've checked the XHR request, it seems working.
reinstalled Craft with composer
tested several browsers

What could be a reason for an empty Plugin Store?

Update

I've tested the issue with a clean install of Craft 3, same problem there. So it should be something global on my machine.

Someone have an idea where the problem could be hidden?


texts: Painfully slow Feed Me import of User accounts

texts:
I'm aware of this thread on Feed Me slow performance, but I'm raising it as a separate thread in case there is anything particular about my circumstance that is pertinent.

I'm running Craft 3.4.18 and trying to import a large number of users (about 1,500) into a specific user group using Feed Me:

I'm using .csv sources on the local file system above web root
I'm importing:

Username (as email address string)
Email
First name
Last name
Shared password
User group string

I'm batching imports in 500s but because things are so slow will now try smaller batches
I have read and attended to the performance aspects of the Feed Me troubleshooting docs
There is plenty of memory and execution time allocation to Craft and the instance is on a dedicated Linux server with 8Gb of RAM

Imports are working without error, but paaaaaainfully slowly -- we're talking hours -- to the point of the import process being effectively useless*.

I have looked into Andrew Welch's #1 solution to running the queue as a background process, but have bumped into installation issues with the Async Queue plugin.

Any suggestions much appreciated.

I'd be happy in principle to do SQL inserts directly into the craft_users and craft_usergroups_users tables but I infer that's not an option since each hash of the shared password is unique and there is a unique UID to generate for each row too.

Update on #3 above:

I'm currently running a batch of 100 instead of 500 and that makes no difference to speed whatsoever.

Next step is perhaps to try a JSON feed instead of CSV?

*'Effectively useless' in the sense that although I have time to run extended imports right now, if it's going to generally take this long it's a non-starter for time-pressured imports.

Second update on #3 above:

An import batch of 100 I started over 2 hours ago has crept along incrementally, with me periodically reviewing its status during that time and seeing barely any change, and then…

I have just revisited it and it suddenly went from 64% complete and unchanging to 100%. Now onto the next batch to see what happens.


texts: Multilingual Dates where date format varies

texts:
I have a multilingual site, and I want my dates formatted like:

English site: July 13, 2014
Italian site: 13 lulgio 2014

So the month name is translated, and the order of the elements changes as well.


texts:
I've got SearchPlus working great on my Craft localhost. But what I'm trying to achieve is making it so that when you type in the navigation bar (_layout) from any page it'll jump onto a search results page and display the results there. I've not got a clue how to go about achieving this, any direction or help would be great. My current setup is as follows:

templates/search/index.html

{% block content %}

Basic Search

            <form class="form-inline"
                  id="searchform"
                  data-applicationId="{{ craft.searchPlus.getAlgoliaApplicationId }}"
                  data-searchApiKey="{{ craft.searchPlus.getAlgoliaSearchApiKey }}"
                  data-index="products">

                    Search
                    <input type="search" class="form-control" id="searchinput" placeholder="Search.." autocomplete="off">

            </form>

    {% raw %}

    {% endraw %}
{% endblock %}

{% set searchPlusJs %}
    (function() {
        $(this).searchplus();
    })();
{% endset %}

{% includeJsFile url('//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js') %}
{% includeJsFile resourceUrl('searchplus/js/searchplus-combined.min.js') %}
{% includeJs searchPlusJs %}


texts: Getting unknown property: craft\web\Application::GeneralConfig

texts:
Sorry, rusty at PHP and learning Craft.

My code looks like this:

$url = craft::$app->GeneralConfig->siteUrl();

What am I doing wrong? I want to build a URL for some links in a plugin.


texts: currentUser global is null. I can't figure out why

texts:
Does anyone know why currentUser would return null? I'm logged in as an admin.. actually the only user.

I've cleared cache, logged out and back in, etc. I can't seem to get it to work.

I'm trying to set an edit link for an entry like so:

{% if currentUser %}

        Edit

{% endif %}

And also tried this:

{% if entry.isEditable() %}

        Edit

{% endif %}

Neither are working. Any ideas?


texts: Having an issue with assets, while i am upload the image from the admin

texts:
When i have upload the image using below settings that will give me an error  The error message was: "Error uploading the file: The file system path "/public_html/src/assets/images/" set for this source does not exist.

general.php file

<?php

 $siteUrl = array(
    'en_gb' => 'https://www.ancamotion.com/',
    'de' => 'https://www.ancamotion.de/',
    'zh_cn' => 'https://www.ancamotion.cn/',
    'zh_tw' => 'https://www.ancamotion.com.tw/',
);

return array(

    '*' => array(
        'devMode' => false,
        'extraAllowedFileExtensions' => 'exe, xml',
        'maxUploadFileSize' => 67108864,
        'omitScriptNameInUrls' => true,
        'timezone' => 'Australia/Melbourne',
        'setPasswordPath' => array(
            'en' => 'securezone/resetpasswordform.html',
                 'de' => 'securezone/resetpasswordform.html',
                  'cn' => 'securezone/resetpasswordform.html',
        ),
        'setPasswordSuccessPath' => array(
            'en' => 'password/thanks-reset.html',
                'de' => 'password/thanks-reset.html',
                'cn' => 'password/thanks-reset.html',
        ),
    ),

   'ancamotion.com' => array(
        'siteUrl' => $siteUrl,
        'environmentVariables' => array(
            'basePath' => '/public_html/',
            'baseUrl'  => 'https://www.ancamotion.com/',
        ),
    ),
   'ancamotion.de' => array(
        'siteUrl' => $siteUrl,
        'environmentVariables' => array(
            'basePath' => '/public_de/',
            'baseUrl'  => 'https://www.ancamotion.de/',
        ),
    ),
   'ancamotion.cn' => array(
        'siteUrl' => $siteUrl,
        'environmentVariables' => array(
            'basePath' => '/public_cn/',
            'baseUrl'  => 'https://www.ancamotion.cn/',
        ),
    ),
   'ancamotion.com.tw' => array(
        'siteUrl' => $siteUrl,
        'environmentVariables' => array(
            'basePath' => '/public_tw/',
            'baseUrl'  => 'https://www.ancamotion.com.tw/',
        ),
    ),

);

my settings from website admin Assets are

File System Path --> {basePath}src/assets/images/

URL --> {baseUrl}src/assets/images/

Can anyone help me with this?

Thank You in advanced.


texts: Use Asset field as a Global Set Variable?

texts:
Is it possible to use an Asset field as a Global Set? For example:

{{ companyInfo.logo }}


texts: Managing sections and field updates between environments

texts:
What is the best practice for the following:

Client site running CraftCMS (v3) is in production. Updates are needed which require additions or modifications to the data structure / schema of the site (new sections, fields, etc.). Taking a remote dump of the database for local development is not a realistic option as the client makes regular updates to the website in production. Particularly for new additions, is there a way to easily make those updates in production after I've completed them in my development environment?

Real scenario: I'm adding a new section (a blog) to add to an existing Craft site. I will be working in the development environment for several days, making many additions to the data structure / schema, which I'd prefer not to have to replicate via the admin UI in production once I'm ready to deploy.

Note: I do not want to sync the entire databases - just the structure.


texts:
when following the information for enabling Redis in Craft 3, my site just refreshes to a blank screen with a "Internal server error" generic message. Reviewing the server logs reveals:

ReflectionException: Class yii\redis\Cache does not exist in /storage/path/www/staging_html/vendor/yiisoft/yii2/di/Container.php:428

Talking with my hosting provider (Arcustech), informs me that Redis is indeed running and php-redis is installed. The details I entered into config\app.php were

return [
'components' => [
    'cache' => [
        'class' => yii\redis\Cache::class,
        'defaultDuration' => 86400,
        'redis' => [
            'hostname' => 'localhost',
            'port' => 6379,
            'database' => 0,
        ],
    ],
  ],
];

Any light that could be shone onto my predicament would be amazing.
thanks!


texts:
Just looking for pros and cons here, I guess. My gut says to let updates flow through version control, but the part of me that wants to give up web design and become a mountain man says it might be beneficial if the client was at least able to patch in critical updates if necessary.

Thought I remember glancing at a conversation about this in the Slack channel, but couldn't find it.


texts:
Anybody got any suggestions on debugging autoLoginAfterAccountActivation and activateAccountSuccessPath not working?

These are set in general.php of my config but when a user activates their account (sets their password) they are redirected to the homepage and not logged in. The user is showing as active in the control panel.

Hayelp!

Hayelp! http://www.cartoonscrapbook.com/01pics-L/penelope-pitstop_L20.jpg


texts:
In a template, I want to show only enabled categories. I can't figure out how to filter the returned categories by only enabled ones, without doing it in the for loop.

This works:

{% for category in craft.categories.level(1) if category.enabled %}
  # only enabled categories
{% endfor %}

but instantiates the disabled categories, even though they won't be used.


texts:
I am trying to update Craft, but when I do, it says update complete, but still shows that there is an update available. It stays on version 2.5.2759 but never updates to the latest 2.6.2776 version. I am running PHP 5.5 and Craft is installed locally.

Any ideas how I can diagnose what is going on?


texts:
I'm currently Authenticating users via OAuth and Social Login by Dukt. I have Facebook app all set up and running as well as Twitter. The user gets redirected, asked to Authorise but when it returns back to the Craft website the user hasn't been created or exists.

My current setup is as follows:

Connected Facebook to OAuth
Connected Facebook with Social Login
Activated my Facebook app so it's "Live"

My questions are as follows:

I haven't got a config file for the user, do we need to create this?
Do you need to add "Fields" to the "User" in Craft CP such as Username/Email? If so - which ones are the defaults for social login?

Thanks


texts: Any documentation about the elementindex template available?

texts:
I'm trying to customise the elementindex view. For example I want to filter out some entries that don't match certain criteria. Also if possible add some hooks to the read calls. Is there any documentation available about this?

Thanks in advance


texts: I pasted in incorrect copy in my product description window in the dashboard, then updated the entry. Is there a way to find/revert to my previous draft? Thank you.


texts: When I try to edit an entry: "Unable to find 'craft\services\EntryRevisions'"

texts:
I have just moved my site onto the live server and imported my local db. It is a multi-site setup.

In the Entries section of the CP, when I click on an entry to edit it I get the following error page:

  Unknown Class – yii\base\UnknownClassException
  Unable to find 'craft\services\EntryRevisions' in file: /home/careacas/vendor/craftcms/cms/src/services/EntryRevisions.php. Namespace missing?

Any ideas?


texts: Is there any way to create reciprocal related entries?

texts:
I'm working on a sign language dictionary project. Each individual sign (or word) is an entry.

I want to be able to have an area that shows words that are similar to the word that is being currently viewed. I'm looking for a way to create reciprocal relationships between word entries to show these similar words.

For example, I want to say that word A is related to word B. Then I'd like for word B to also be automatically related to word A without having to go into word B and manually create the relationship.

Is there any way to make this kind of reciprocal relationship in craft? Thanks for any ideas.


texts:
I'm looking to set a 'score' property on my "category" field, this will be done by calculating how many entries are within that category similar to a 'Trending' feature.

Is there any way to set a property by doing a sum something like entry.count x 0.4 and then setting the field with the result?

Thanks


texts: Change how the PDF filename is formatted?

texts:
In the Commerce plugin, there are several ways to download a PDF of a specific order.

However, the default formatting of the PDF filename isn't very helpful...

  Order-14ef9b78dae6893cd2ca75ec047ed9a0.pdf

Is there any way to control the formatting of PDF receipt filenames?


texts: Sorting matrixblocks by earliest date from child table

texts:
I have a matrix field (events), each of this blocks (event) contains a table (dates) with individual rows (date), those have a start date and a start time. I would like to sort the events (matrix blocks) by the earliest start date / start time. Also at some point I would only want to display future events.

Whats the "best" way to achieve this kind of sorting in a template (twig)? Would I have to loop through them and sort them "manually"? I think about something around sorting the child tables first and then sort the blocks by their first table rows.

Entry

Event A [matrixblock]

Dates [table]

Date 1 | (12/12/2015) [datetimefield] | (10:00) [datetimefield]
Date 2 | (10/10/2015) [datetimefield] | (10:00) [datetimefield]

Event B [matrixblock]

Dates [table]

Date 1 | (09/09/2015) [datetimefield] | (10:00) [datetimefield]
Date 2 | (10/10/2015) [datetimefield] | (10:00) [datetimefield]
Date 3 | (11/11/2015) [datetimefield] | (10:00) [datetimefield]

This simple case would sort Event B, Event A. Because of the earliest date being Date 1 of Event B.

Appreciate any input. Cheers.


texts: Filter entries by specific child field of a field?

texts:
Is it possible to create a query which filters the results by a child of a field?
For example I have an address field which has multiple fields amongst other a country field.
I would like to fetch the results for a section for a specific country.
How should I construct the query?


texts:
Does anyone know of a good way of handling emojis in a rich text field?

I'm aware that is possible to copy and paste them into one, but does anything along the lines of an emoji 'button' (i.e. to sit in the toolbar with a dropdown of categorised emojis) exist? Other suggestions welcome! Just keen to avoid the extra steps of having to find the emoji on an external source, copy, and paste in to the field.

A reference point would be Slack's 'emoji menu'.


texts: How to configure the system messages  url?

texts:
we have got a multisite environment and have imported users with different preferred languages (de and en). Therefore we made a module, cause the feedme plugin doens't set the preferred language https://github.com/craftcms/feed-me/issues/612. All the users are set to pending. Now we want to sent the activation mails for alle these imported users, so they can set their passwords.
The email is translated cause of the preferred language - thumbs up - but the  with the activation code is just from one domain - in our case the .de domain. This means, all users with a preferred language set to "en" are getting a well translated mail, with a link to the .de page and not the .com for setting their passwords.
So the question is: why is the link not dependent on the preferred language as well or could be localized via a config for this case?


texts: Craft URLs intermittently being cached as /index.php/my-page/ or /index.php?p=my-page

texts:
Cross-posting from here, as I'm not sure if this is a Craft issue or specific to the cache-clear plugin.

Intermittently (twice in a day now), I've seen templates being cached with Craft URLs outputting as either /index.php/my-page/ or /index.php?p=my-page

Once this happens, clearing cache via the plugin url (http://domain.com/actions/cacheClear/clear?key=myKey) doesn't seem to fix anything, but clearing cache in the control panel does.

Any ideas?


texts:
I am trying to import a few reasonably straightforward fields to populate some entries from a CSV. It seems to run ok but nothing comes through and when I look a the logs I get the error below - anyone know what this means?

The shell command "mysqldump --defaults-extra-file="C:\Users\Malcolm\Google Drive\CRAFT-SITES\marshall-bridge\storage\runtime\temp\my.cnf" --add-drop-table --comments --create-options --dump-date --no-autocommit --routines --set-charset --triggers --single-transaction --no-data --result-file="C:\Users\Malcolm\Google Drive\CRAFT-SITES\marshall-bridge\storage\backups/feedme-190524_100041_cdm7gla482.sql" marshall-bridge && mysqldump --defaults-extra-file="C:\Users\Malcolm\Google Drive\CRAFT-SITES\marshall-bridge\storage\runtime\temp\my.cnf" --add-drop-table --comments --create-options --dump-date --no-autocommit --routines --set-charset --triggers --no-create-info --ignore-table=marshall-bridge.assetindexdata --ignore-table=marshall-bridge.assettransformindex --ignore-table=marshall-bridge.sessions --ignore-table=marshall-bridge.templatecaches --ignore-table=marshall-bridge.templatecachequeries --ignore-table=marshall-bridge.templatecacheelements --ignore-table=marshall-bridge.cache --ignore-table=marshall-bridge.templatecachecriteria marshall-bridge >> "C:\Users\Malcolm\Google Drive\CRAFT-SITES\marshall-bridge\storage\backups/feedme-190524_100041_cdm7gla482.sql"" failed with exit code 1. - Connection.php: 58


texts:
I am new to Craft CMS. I am building my first industrial design portfolio site and am facing a brick wall.. The problem is that I have three image handlers that I set up in field. thumbnail, projectBanner and projectThumbnail that I want to display in project section. I found this code snippet and made changes to it to match one of my image handler.

{% for asset in entry.projectBanner %}
    <img src="{{ asset.getUrl(thumb) }}" alt="{{ asset.title }}" />
{% endfor %}

I made sure that I have upload the image (projectBanner) to a entry and refreshed the browser. The image does not show up but the title does. Could anyone please tell me what I did wrong and what the correct method to achieve outputting images into entries?


texts:
I'm currently creating a plugin for craft and have stumbled across a slight problem. I'll try summarise of what I am doing and what I am trying to achieve.

So, I'm trying creating a plugin which will update entries within craft via an external API. I have managed to get the initial save to work using these following lines:

$entry = new EntryModel();
$entry->getContent()->title = $project->name;
$entry->sectionId = 10;
craft()->entries->saveEntry($entry);

The issue arises when I'm trying to update the model. Obviously, I don't want to duplicate entries.

I can get the entry using this line:

EntryRecord::model()->findById(45);

(this is just used for testing, eventually I will be getting the record via a custom variable).

What I'm trying to do here is update the title of this record, from what I can see this is stored in the craft_content table.

Basically what I'd like to do is something like :

EntryModel::model()->findByAttributes(array('title'=>$project->name);

So I can then update the content title of that row.
I can see I can't do it this way, would you be able point me in the right direction?


texts: How do you create a front-end form for users to submit content?

texts:
I'd like to create a form for users to load events (that I will moderate and publish).

How do I do this?


texts: Define email environment-specific email settings?

texts:
I'd like to define the SMTP server deets in my local config as I regularly need to push/pull databases between environments and will have different settings.

There doesn't seem to be any of doing this currently. Are there any workarounds? I thought maybe I could just put the SMTP deets in my code (testing for current enviroment) but the EmailModel class doesn't accept any of the SMTP-related properties of PHPMailer.


texts: Rebuilding my portfolio site from scratch in CraftCMS 3 and having an issue getting content to display

texts:
I'm rebuilding my portfolio site in CraftCMS 3 and started building some VERY basic templates to test the sections and ensure everything is connecting properly before uploading a bunch of content and building all the more complicated elements in my templates. I have a layout template and a home page index template that extends this layout. The layout is just a basic HTML5 boilerplate from emmet and a block tag. The index page template has a headline pulled from a single and an entry query that will generate a list of portfolio pieces from a structure. Below is the code for this page in its current, basic state.
{% extends "_layouts/main" %}

{% block main %}

{{ entry.title }}

{# Create an entry query #}
{% set portfolioGrid = craft.entries().section('portfolio').all() %}

{# Display the entries #}

    {% for portfolioTile in portfolioGrid %}

{{ portfolioTile.title }}

    {% endfor %}

{% endblock %}

{{ entry.title }} displays fine and the  tags are generated but the {% for %} loop isn't doing anything. I'm not getting any errors in the debug toolbar that I can see. The section name is correct. What else am I missing here? This should be a simple, straightforward query but it's blank.


texts: I want to replace the login function with a custom one validating against Office 365 oAuth.  I already have the connection to MS coded, but I can't find a way to replace the core login function.  I can see the "before login" hook, but that would still display the login screen.  Is there any way to accomplish via plugin, or do I have to alter the core code to accomplish what I want?


texts: Removing old Block Handles in Matrix Field?

texts:
I'm working with Matrix field. When adding and then removing and then adding again fields with the same handle I get the following error.

Handle "videoUrl" has already been taken.

Is there a way of removing old handles that are not being used?

This is actually creating issues adding new fields with a different handle too. Even though a new handle is being used an old handle is being referenced as a blocker to adding a new field. I get the following error when trying to save a post.

Invalid field handle: embed

'Embed' isn't even listed in the field manager area as a field handle but the problem persists.


texts:
We have a client that has a good deal of products in one channel. We're categorizing each product entry with a pretty extensive category tree. The reason we didn't go with a structure is because many products needed to exist in multiple categories and a structure tree would get messy.

Everything is working great, but they now want to be able to re-order entries by category in the CP and we're sort of stuck. The new Category Sources plugin sort of gets us half way there but it doesn't allow you to reorder and save the order in any way.

Anyone run into this sort of issue? Thanks.


texts: How do I pull the first image from the first entry of the first subcategory?

texts:
I just want to apologize in advance if I'm not quite understanding how the element criteria model works. I know that's the basis of Craft but I learn best by doing and this StackExchange has been an incredible resource. Thank you!
As my question title explains, I'm trying to get an image (image url actually) located in an asset field from the first entry of the first subcategory within a category.
This is what I have so far:
    {% set lastSeg = craft.request.lastSegment %}
    {% for cat in categories.slug(lastSeg) %}
      {{category.title}}
      {{category.catContent}}

        {% set subCategories = craft.categories.descendantOf(category) %}
        {% for subCat in subCategories %}

            {{subCat.title}}

        {% endfor %}

    {% endfor %}

I'd like the image url to replace http://fpoimg.com/280x280 as the img src. I'm getting stuck after looping through the subcategories. I'm not sure how to loop through entries in the subcategory and return the first one, so that I can then loop through the assets and pull the image url I need.
-- edit --
I think I have gotten it to work thanks to Marion's comment, but I would love some input to be certain:
    {% set lastSeg = craft.request.lastSegment %}
    {% for cat in categories.slug(lastSeg) %}
      {{category.title}}
      {{category.catContent}}

        {% set subCategories = craft.categories.descendantOf(category) %}
        {% set products = craft.entries.section('products').relatedTo(subCategories) %}

        {% for subCat in subCategories %}
        {% for entry in products.relatedTo(subCat).limit(1) %}
        {% set image = entry.productImage.first() %}

            {{subCat.title}}

        {% endfor %}

    {% endfor %}


texts: Localization Section propagation settings, and related entry field setting "Manage relations on a per-site basis"

texts:
Craft 3.4.20.
Site is running multiple localizations
Sections:
Blog Post
Propagation method set to, "Save entries to all sites enabled for this section"
Blog Category (Structure entry with nothing more than the default Title)
Blog Post Section entry has a field to relate to our Blog Category Structure. We have a field under our Blog Posts entry with the option, "Manage relations on a per-site basis".

A Blog Post entry has an entry field to where you can select multiple Blog Category entries from a Structure.
Issue is that editors publish Blog Posts and may not consider the other locales. You would think the relationship field would take into consideration of the setting, Manage relations on a per-site basis.
When publishing an entry under the Default site (in our case North America), and the publishing editor disregards the other Locales (the toggle drop-down for an entry on publish view), the field data of the entry relationship for "Blog Category" on North America duplicates itself to the Europe relationship field.
I don't know if this is intentional, or if the Manage relations on a per-site basis setting is not being factored in?
Is there a way to exclude certain fields from being populated with the same localization data as the default entry. I simply thought the field settings, Manage relations on a per-site basis would be factored into this and be left null when publishing a North America entry, but Europe, and all the other sites receive that same field relationship value based on North America Blog Post publish. It seems as though there is no way to exclude certain fields from doing this, and is there a solution to this?
Is it intended for the Section settings Save entries to all sites enabled for this section to override this field setting with first publish?


texts: Sorting entries based on an a bespoke algorithm

texts:
We have been asked to scope a solution for a new site build that we'd like to use Craft for. There is one requirement I'm not sure how we'd approach though.

In Craft terms, we would have an Articles channel that has a number of fields:

Employer (relationship to a single Employer channel entry)
Sector (relationship to a single category)
Stage (select field)
Tag (tag field)

Then each logged in User would also have the same fields on their profile. I guess it would be easy enough to query the user attributes and pass those to a craft()->entries() call, but the requirements call for a very specific sorting algorithm.

That would work something like this:

Article Employer matches User Employer = score of 10
Article Sector matches User Sector = score of 3
Article Stage matches User Stage = score of 4
Article Tags intersect with User Tags = score of 1 x number of matches

The result of that score would then be added up and used as a sort dimension against a list all the latest Article entries.

Can anybody suggest a practical (processor efficient) way to achieve this?

My current thinking this:

Get all Article entries.
Loop through each Article them and add the calculated score to an array containing the entry ID and the score.
Order the array by score.
Requery all Articles with pagination enabled, passing in a the list of entry IDs in the order defined by the sorted array.

Would that work? In particular the last step - can we define entries be sorted by an array of ID numbers?

Any other suggestions would be gladly received.


texts: Why would getEntryTableAttributeHtml(EntryModel $entry, $attribute) not return proper labels?

texts: I have getEntryTableAttributeHtml(EntryModel $entry, $attribute) setup in my plugin file.  I have attributes defined in defineAdditionalEntryTableAttributes().  However when the page loads $attribute returns field:85 instead of one of the expected labels. Why might this occur?


texts:
I am attempting to update my craft instance from Craft CMS 2.6.2781 to the latest. (Critical Update).

Unlike before where there was a button that would do everything for me nicely and automatically, this update just downloads a zip file.

Is it possible to auto update this fix? If not are there instructions on what to do for this update? The readme.txt has pretty generic instructions.

Thanks


texts: Craft 3: admin is showing "500 Internal Server Error" (apache) after fresh install

texts:
Just successfully installed a fresh copy of Craft CMS via web browser method under:
http://kultursprung.org

Frontend is visible but the admin is showing raw Apache error 500 after fresh install:
http://kultursprung.org/admin

The 500 error is not the styled Craft dev one but instead the raw Apache version.

Server requirements check passed:
http://kultursprung.org/server/checkit.php

Did set all correct file and folder permissions.

Database is showing all necessary tables as expected after a successful fresh install.

phperrors.log:

UPDATE:

When I access the admin via this URL:
http://kultursprung.org/index.php?p=admin
i can provide an additional Craft styled error:

Any help?


texts: myFieldHandle error in Craft using Smart Map

texts:
I am getting a Twig runtime error on the below. The map and everything else works when I remove myFieldHandle(params).orderBy('distance').
Error:
Calling unknown method: craft\elements\db\EntryQuery::myFieldHandle()

Code:
{% set target = '90210' %}
{% set params = {
    target: target,
    range: 100
} %}

{% set entries = craft.entries.section('contractors').myFieldHandle(params).orderBy('distance') %}

{% set options = {
    height: 700,
    draggable: false,
    markerInfo: '_includes/mapInfoBubble',
    infoWindowOptions: {
        maxWidth: 250
    }
} %}


texts: Fetch target entries that have been linked through an Entries field

texts:
I have a section Posts that has an Entries-type field called Authors that can be linked to one or more entries in section called People. To make a filter for my posts index, I need to fetch all the People entries that have been linked to any post via the Authors field, but I can't wrap my head around how to do this.

Any ideas appreciated!


texts: How do I search craft.entries with multiple parameters?

texts:
I'm filtering entries based off a searchbar with multiple parameters, and I'm building up an entries filter based off of them. Everything works great except for having more than one .search functions.

{% set req = craft.request %}

{% set results = craft.entries.section("properties") %}

{% set params = ['location', 'min-price', 'max-price', 'status'] %}
{% set query = {} %}

{% for param in params %}
  {% set key = param | camel %}
  {% set value = req.getParam(param) %}
  {% set query = query | merge({ (key):(value) }) %}
{% endfor %}

{% if query.location %}
  {% set results = results.search(query.location) %}
{% endif %}

{% if query.minPrice or query.maxPrice %}
  {% set min = query.minPrice ? query.minPrice : '' %}
  {% set max = query.maxPrice ? query.maxPrice : '' %}
  {% set results = results.search("price:" ~ '500000') %}
{% endif %}

{% if query.status %}
  {% set results = results.search('statusCategory:' ~ query.status) %}
{% endif %}

{% for entry in results %}
...

I've removed the whole min/max part just to simplify things, but it seems that if there is both a location and min/max price parameter, whichever one is last overrides the first. How can I combine these search parameters?


texts: MySql 5.7 error - field doesn't have a default value

texts:
We've just switched server for one of our sites and I am now encountering a MySql error on one of our plugins. The MySql version on the new server is 5.7 and throws an error as a field has no default value.

Do we now need to adjust our db model and records to add Null when we define the attributes to any fields that don't have a default value set?

Strange thing is when I look at the database table some fields have been set up with 'Allow Null' set and others haven't and these fields are exactly the same type for example in both model and record file I have these 2 fields one has been set to Allow Null the other hasn't??

'profession' =>  array(AttributeType::Name, 'maxLength' => 255, 'required' => false),
'city'       =>  array(AttributeType::Name, 'maxLength' => 255, 'required' => false),

Any ideas or suggestions?

Running latest craft 2.6.3016 on php 7.1

Cheers


texts: How to output an Entries Field value within a Matrix Field block

texts:
I'm trying to code up a Matrix field for a homepage slider, and it contains a single 'Slide' block type. It has fields for Image (Assets), Heading (Plain Text), Sub-Heading (Plain Text), and Slide Link (Entries). I've got everything working, except for the Slide Link field (where I want to output the entry URI for the entry that was selected in that field).

Whenever I add {{ block.slideLink }} to my template, I get the following error:

  Object of class Craft\ElementCriteriaModel could not be converted to string

So I'm obviously not meant to output a link to an entry (I only have one link being selected in the field) in this way, so can someone help me out with the syntax that I need please? There weren't any Entries examples in the Matrix Field docs that I could copy from, and I couldn't figure out how to adapt the Entries Field examples to fit in with a Matrix field.

Thanks in advance for any help, and here's my code. The incorrect {{ block.slideLink }} code is on line 11:

{% extends "_layout" %}

{% block content %}

      {% for block in entry.homepageSlideshow %}

            {% set largeImage = {
              mode: 'crop',
              width: 1180,
              height: 450,
              quality: 80
            } %}

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

            {% endif %}

{{ block.heading }}

{{ block.subHeading }}

      {% endfor %}

{% endblock %}


texts:
I'm having trouble registering a CP route. What I have is a "working" SiteAdministrator_UserController.php (other form save actions already work through this controller, so its functional). Inside the controller I have a function :

public function actionCurrent()
{
    die ('Works!');
}

In my Plugin I have the following:

public function registerCpRoutes()
{
    return array(
        'siteadministator/currentusers' => array('action' => 'siteAdministrator/user/current')
    );
}

trying the uri http://cms.craft.dev/admin/siteadministrator/currentusers

Craft says its a  404.

What am I doing wrong and/or is there a way to debug this?

Thanks in advance


texts:
{% set entryIds = craft.entries ({
                    section: 'locations'
                }).ids() %}

                {% set cities = craft.categories ({
                    descendantOf: category,
                    groupId: 1,
                    level: 2,
                    orderBy: 'title asc',
                    relatedTo: {sourceElement: entryIds}
                }) %}

Restaurants and Their Menus in Nearby Cities

                    {% for city in cities.all() %}

{{ city.title }}

                    {% endfor %}

Throws SQLSTATE[HY000]: General error: 7 number of parameters must be between 0 and 65535 error. PGSQL. What is the workaround?


texts: how to fetch entries with custom field data matches or else that field is empty

texts:
$queryElement = Entry::find()
    ->section('posts')
    ->country(['abc', ':empty:'])
    ->location(['xyz', ':empty:'])
    ->orderBy('postDate desc')
    ->limit(null);

here country, location are custom fields added to the section
this code will return empty array when executed


texts: Using MySQL With just InnoDB storage engine

texts: What are the implications if I create all the Craft database tables on the InnoDB storage engine? Will there be any performance problem?


texts: How can I update a checkbox from a plugin?

texts:
I have a plugin that is listening for a form submit.
Within that form are two fields firstName and agreeToTerms.

When the form is submitted, I am updating an existing entry with the values that were posted.

I can get all fields to update except my checkbox. I'm not sure what I need to send to craft if the user has checked the checkbox.

Here is what I have so far:

MyController

$postDateTime = ...

...
$entry->setContentFromPost(array(
    'agreeToTerms' => craft()->request->getPost('fields.agreeToTerms'),
    'firstName' => craft()->request->getPost('fields.electronicSignature'),
    'signatureDate' => $postDateTime
));
...

This returns "1" which is the value of the checkbox.

craft()->request->getPost('fields.agreeToTerms') // returns 1

But that isn't what I need to send to Craft. If I were using jquery, I am looking for something like

$.prop('checked', true);

EDIT

To help clarify in case someone else comes across this thread, as @carlcs stated I was in fact talking about a checkbox field.

The plugin I am using allows users to create entries in a section. When an entry is created, one of the fields is a checkbox. I was attempting to set the checkbox field as checked if the user had checked the corresponding checkbox when the entry was created.


texts: ERROR 1370 (42000) alter routine command denied to user

texts:
I am trying to upload my DB using MySQL Workbench but am getting this error:

ERROR 1370 (42000) at line 4534: alter routine command denied to user 'detectalocal'@'%' for routine 'detectalocal.checkLicensesExpiration'

How do I troubleshoot this? My root account has all of the correct permissions.


texts:
I am wondering if I have structured my data badly and was hoping someone could advise on an alternative. Essentially I have a structure with two types, a catalogue and the catalogues children. Some catalogues may have up to 400 children.

When I began importing the data using Feed Me I didn't have any problem, but after a while it was becoming nearly impossible to use and I'm only half way through. I checked the logs in the debug bar and found this was holding things up. Perhaps it's of some help?

Any advice here would be really appreciated!

Edit:

For more clarification, this log is from the screen where you map the fields. There may be around 15,000 entries so far, most of which are the children entries. I am just wondering if there is something wrong with using structures this way or is this just because of the large amount of entries in the database? I have read that people are running Craft sites with over 100,000 entries so I didn't think this would be a problem.


texts:
I'm quite new to server config, so this might be a simple mistake. I have a local environment setup on my computer that works just fine. I uploaded my project to my staging server at AWS and the only thing that loads is the index.html in my craft folder. For some reason it gives me a "The requested URL /css/bootstrap.min.css was not found on this server" error for every folder or file I have inside of public folder.

<?php

/**
* General Configuration
*
* All of your system's general configuration settings go in here.
* You can see a list of the default settings in craft/app/etc/config/defaults/general.php
*/

return array(
);

My craft folder in my staging is at: /var/www/craft-portfolio/

My Public folder is at: /var/www/craft-portfolio

The web root is the public folder that is /var/www/craft-portfolio/public


texts: How do I add meta data and a page title through ajax?

texts:
I have looked a lot through this StackExchange but I guess I am not too advanced in using AJAX/Json.

My aim is to have page transitions using Ajax. This was rather easy to accomplish following this article:
https://designbycosmic.com/journal/craft-cms-ajax-page-transitions-with-history-pushstate

Now what this article is missing out is the updating of the page title and meta tags. I have done a lot of searches and from what I understand I need to build json files for each page/entry.

So I installed ElementAPI and tried to get the basics working

    <?php
namespace Craft;

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

But I am getting stuck at this point.
I know that I can get the jquery through

  $.ajax({
      type: 'get',
      url: 'news.json',
      data: {
        format: 'json'
      },
      success: function(result){
        $main.html(result);
      },
      error: function(){
        console.log("error.");
        location.reload();
      }
    });

But if I do that I am getting an empty body that loads nothing.

I kind of am stuck here as my knowledge ends.

I would be very grateful for any information on how to progress. I am really looking to understand how this works but without having at least a working model it's hard for me to analyze and reverse-engineer the code.


texts: Front-end form submission feedback on buttons

texts:
I have some front-end forms including login and sign up which are modal windows. Currently I have no feedback for the user if they are successful or not.

What's the best method to return something in the modal?

In an ideal world I'd like to update the buttons somehow, like these:

http://demo.tutorialzine.com/2013/10/buttons-built-in-progress-meters/
or
http://lab.hakim.se/ladda/

Any ideas or help would be appreciated.


texts:
I am setting up a vagrant development environment and I was wondering if it is possible to somehow pass the installation configuration when running ./craft setup command to avoid any user interaction?

Checking the help output of the setup/index says --interactive: boolean, 0 or 1 (whether to run the command interactively.). When executing ./craft setup --interactive 0 nothing happens. Am I doing something wrong? I tried searching for an explanation and usages of setup parameters but to no avail.


texts: User profile form, repeat new password and check if they match

texts: So there's the function to set a new password, but is there also the possibility to create a second password field to check if both new passwords matches and only then set the new password?


texts: Get discount data from adjustment object

texts: Is it possible to get, from one of the cart.adjustments of type discount, whether the discount was added with a coupon code, and if so, what that coupon code is?


texts: In the Element API plugin, how can I get only tags that are related to a particular section?

texts:
I tried to get all tags that are related to an section.
Everything I tried failed. Is there a way to get all assigned tags for a particular element type by using element criteria model.
In this case travelImages? I want to avoid to display not related tags.

'elementType' => 'Tag',
'criteria' => ['relatedto' => 'travelImages']


texts: Loading email templates in a Craft 3 plugin

texts:
I've been struggling to make this work within a plugin. I have a html file in my templates folder called _email.html. I try to load it in my plugin but then I get an error. This is my code:

Craft::$app->mailer->compose('_email.html', ['body' => $emailBody])
            ->setFrom($fromMail)
            ->setTo($toMail)
            ->setSubject($subject)
            ->send();

The problem is that the Yii mailer is looking in the vendor folder instead of the templates folder.

This is the error I get:

The view file does not exist: /Applications/MAMP/htdocs/project/vendor/craftcms/cms/src/mail/_email

Even when I try going back to the templates folder it doesn't seem to work and I get the following error:

The view file does not exist: /Applications/MAMP/htdocs/project/vendor/craftcms/cms/src/mail/../../../../../../templates/_email

I found out that if I copy and paste the contents of the _email.html file and do the following it does work, but this obviously is a pretty bad workaround

->setHtmlBody("<!DOCTYPE html......")

Any advice?

Thanks!


texts: Specifying administrators for localized sites?

texts: From what I've gleaned from other q&a, it's possible to set up multiple localized sites under one installation of Craft, but can you assign separate administrators to each? I'd like to set up multiple sites under one domain for a company with several global offices, but each office needs to have control over only their site's content— and ideally some admins could have access to more than one. Possible?


texts: Craft pieces accessed by people on domain only

texts:
How would you make portions of Craft available to only people that are "on the domain" and then let the rest of it be public facing? Would you need two instances of craft on 2 servers? One which is accessible only from "inside" and another that the public can access?

Would this entail running Craft on one webserver and the front-end on another? This way the webserver with craft on it is only accessed internally but the front-end can be accessed outside?

edit: I only want CP to be accessed by people who are logged in and on the work network. For security reasons a simple login is not enough.


texts:
How do I change the default font (Trebuchet) of Redactor II to Arial, for instance?

I don't know how to override the default CSS of Redactor. Please help.

Tnx in advance!


texts: Configuring assets error - Could not resolve host: s3.amazonaws.com

texts:
I'm running a craft project (ver. 2.4.2684). When I try to upload assets, the progress bar fills and the spinner continues to spin. It looks like it just stalls out and doesn't go beyond that point.

When I go into my settings and into my AWS setup, I get this image when I try to refresh my bucket:

S3::listBuckets(): [6] Could not resolve host: s3.amazonaws.com

Not sure what the issue is since I did not have issues uploading assets before (they still appear loaded into the CMS and are still displaying when I visit the page). For some reason it just won't allow me to upload more assets.

Any and all help is greatly appreciated. Thanks!


texts: How can I print the name of every template being rendered in HTML comments, when in devMode?

texts:
Is there a plugin or setting that prints the name of every template being rendered in HTML comments? I noticed this type of feature in a Drupal project and it was useful for debugging.

This is useful if you add it to every template you make, but I'd like to be able to turn it on/off globally for all templates in dev mode:
How can I make a template output its own filename?


texts: Custom element index page (cp) sortable on dateCreated?

texts:
I have a plugin with custom elements that can be sorted on a handful of fields in my CP element index page. I can get the DATECREATED displaying correctly that Craft generates automatically but I cannot sort by it. I am getting an ambiguous column error in SQL and not sure how I am supposed to include these native columns so they can be sorted like in the CP entries section. The other field, SCORE, is an example of one of my fields that I adjust the html display a bit (add a '%' sign) when it's rendered and sorting doesn't seem to work. Anybody with some tips? I tried referencing the craft app EntryElementType file but still could not quite figure it out. Thanks

public function defineSortableAttributes()
{
    $attributes = array(
        'id'            => Craft::t('ID'),
        'userId'        => Craft::t('User'),
        'testId'        => Craft::t('Test ID'),
        'score'         => Craft::t('Score'), // no errors but not sorting properly
        'dateCreated'   => Craft::t('Date Created'),
    );

    return $attributes;
}

/**
 * Returns the attributes that can be shown/sorted by in table views.
 *
 * @param string|null $source
 * @return array
 */
public function defineAvailableTableAttributes()
{
    $attributes = array(
        'id'                => Craft::t('ID'),
        'userId'            => Craft::t('User'),
        'testId'            => Craft::t('Test'),
        'results'           => Craft::t('Results'),
        'score'             => Craft::t('Score'),
        'ipAddress'         => Craft::t('IP Address'),
        'dateCreated'       => Craft::t('Date Created'),
    );

    return $attributes;
}

The error for dateCreated (when trying to sort by the field) is below. When trying to sort by SCORE I don't notice an error but the order doesn't seem to change, so I'm not terribly sure what's not quite right there. Maybe something to do with sorting on fields where I customize the html output?

CDbException
CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'dateCreated' in order clause is ambiguous. The SQL statement executed was: SELECT `elements`.`id`, `elements`.`type`, `elements`.`enabled`, `elements`.`archived`, `elements`.`dateCreated`, `elements`.`dateUpdated`, `elements_i18n`.`slug`, `elements_i18n`.`uri`, `elements_i18n`.`enabled` AS `localeEnabled`, `ts`.* FROM `craft_elements` `elements` JOIN `craft_elements_i18n` `elements_i18n` ON elements_i18n.elementId = elements.id JOIN `craft_testcenter_submissions` `ts` ON ts.id = elements.id WHERE (elements_i18n.locale = :locale) AND (elements.archived = 0) GROUP BY `elements`.`id` ORDER BY `dateCreated` ASC LIMIT 50. Bound with :locale='en_us' (/volume1/storage/___/HTML/01/craft/app/framework/db/CDbCommand.php:543)

Here is my modifyElementsQuery

public function modifyElementsQuery(DbCommand $query, ElementCriteriaModel $criteria)
{
    $query
        ->addSelect('ts.*')
        ->join('testcenter_submissions ts', 'ts.id = elements.id');

    if ($criteria->userId)
    {
        $query->andWhere(DbHelper::parseParam('ts.userId', $criteria->userId, $query->params));
    }

    if ($criteria->testId)
    {
        $query->andWhere(DbHelper::parseParam('ts.testId', $criteria->testId, $query->params));
    }
}


texts: Problems Displaying Label and Instructions in Forms

texts:
I am trying to learn how to create plugins using craft and am having a small problem.

On the templates/settings.html page I have the following code:

{% import "_includes/forms" as forms %}

{{ forms.lightswitchField({
    label: "Lightswitch Label"|t,
    instructions: "Lightswith Instructions"|t,
    name: 'lightSwitchName',
    on: settings.lightSwitchName,
}) }}

{{ forms.radioGroup({
    label: "Radio Group Label"|t,
    instructions: "Radio Group Instructions"|t,
    name: 'radioGroupName',
    options:{ "option_1" : "option_1", "option_2" : "option_2"},
    value: settings.radioGroupName
}) }}

What is interesting is that on the settings page for this plugin (in the admin control panel) the label and instructions only show up for lightswitch field and not for the radio group.  Here is a screen shot:

Am I doing something wrong?  Is there a way to display a title and instructions for a radiogroup?  If so, can someone please tell me how?

Thanks,

Moshe


texts: php.ini crashes CP with "Craft requires the PDO extension to operate."

texts:
I'm trying to use php.ini to increase memory_limit etc on my site. An empty php.ini causes the front end to crash throwing a "Service Unavailable" error and the CP to throw the error "Craft requires the PDO extension to operate."

The server allows for php.ini files to be used. There is no craft/storage/logs/phperrors.log file and the PHP and apache logs don't seem to show anything.

Another user had the similar issue here but there doesn't seem to be a fix posted that works: Adding php.ini file to root crashes site

Thanks!


texts: Is there a social sharing plugin ready for Craft 3? There is no listing in the new plugin store nor do the V2 offer a revision.


texts:
I use the following code:

$sourcePath = $assetRecord->source->sourceType->getBasePath();
$folderPath = $assetRecord->getFolder()->path;
$path = $sourcePath.$folderPath.$assetRecord->filename;

if (IOHelper::fileExists($path)) {
    $content = IOHelper::getFileContents($assetRecord->url);
    craft()->request->sendFile($test, $content, array('forceDownload' => true));
}

The fileExists always return false. I use the image all over the site without any problems. Also the $path variable return normal path from inside the public folder.

This code lives inside a custom plugin.


texts: Shipping Adjustment not being added to Total Price

texts: I have an adjuster that calculates shipping cost which I can see when I view the order in the backend. The problem is that the shipping adjustment is not being added to the total price. Any help would be GREATLY appreciated.


texts: I have a global that consists of 1 rich text field and the content is displayed on every page. Does it make sense to cache that? If so, I am assuming it should be cached globally?


texts: Is it possible exclude an entry type from result of craft.entries?

texts:
I would like to fetch all entries apart from those of a specific type: 'chapter'. How do I achieve this with a standard call to 'craft.entries'?

{% set results = craft.entries({
  'search': query,
  'order': 'score'
}) %}


texts: Get field Matrix field label inside template

texts:
I have Matrix field containing block with various fields. How can I output into template label of single field?

Can I get type of that field? (for example - textfield, dropdown field, etc.)


texts: Loop through all sites in multisite installation

texts:
Who knows how to loop through all sites in multisite installation? I want to create kind of drop down menu to switch between websites.
I've found this code inside the backend template but looks like it doesn't works in frontend

{% for site in allSites %}

                {{ site.name|t('site') }}
                {{ site.handle }}
                {{ site.language }}
                {{ site.baseUrl }}
                {% if multiple %}

                {% endif %}

        {% endfor %}

UPD:
Now I can fetch names of websites by their Ids:

      {% set allSitesIds = craft.app.sites.getAllSiteIds() %}
  {% for site in allSitesIds %}
  {% set siteName = craft.app.sites.getSiteById(site) %}
  {{siteName}}
  {% endfor %}