texts:
This seems so simple, but after reading over the docs, I couldn't find an answer:

Is there a way to have a field have a default value in Craft?

In my case, I have a Lightswitch field that I want to be on by default, so my client doesn't have to turn it on every time they publish an asset.  But they still do need the ability to turn it off in exceptional cases.

I realize I could just reverse the logic of the field, but it raises a broader question of default field values (which would be useful to me).


texts: apply transform to image uploaded into Redactor?

texts: Is it possible to allow the selection of an image transform on an image that's been uploaded into a Redactor field?


texts: Images added with transform in Redactor field causing Internal Server Error

texts:
Adding images with a named transform in a Redactor rich text field is causing an Internal Server Error on save:

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

Typical html generated by Redactor reads:

`<img src="http://craft-tryout:8888/assets/images/_thumbnail/afternoon_tea.JPG#asset:41:thumbnail">`

When I manually delete #asset:41:thumbnail this seems to fix the problem.

Images added in normal Craft image fields are all working OK.

What is this extra bit of Redactor generated code?
Might I have set up something incorrectly with my transforms?

Any suggestions?


texts: Plugin access and control panel navigation

texts:
I have created a plugin.  It works fine for admins.  The plugin is in the CP nav and the admins urls work as expected, but when I login as a user who is not admin, the plugin will not display in the CP nav and the user cannot view the urls.  You get the error message:

 You don’t have the proper credentials to access this page.

What can I do to fix this?


texts:
I want to check if it's winter. What is the best way to write a "between dates" conditional?

{% set saison = now|date('m-d') %}
{% if saison (saison >= '11-22' and saison <= '03-21') %}
  Jep it's winter
{% endif %}

This absolutely does not work.
I also tried somthing like:

{% set saison = now|date('m-d') %}
{% if saison > '03-21' %}
  Now it's Spring
{% elseif saison > '06-21' %}
  Now it's Summer
{% elseif saison > '09-23' %}
  Now it's Fall
{% elseif saison > '12-22' %}
  Now it's Winter
{% endif %}

That doesn't work. I guess because twig doesn't recognize the strings as dates?
How do I have to write this?


texts: How do I print the number of entries assigned to a category?

texts:
Okay, all I want to do is list all categories AND the # of entries associated with each category.

{% set numofEntries = craft.entries.section('posts').relatedTo(category).total() %}

    {% for categoryName in craft.categories.group('markets') %}
        {{ categoryName.title }}-{{numofEntries}}
    {% endfor %}

No error is thrown (and I am in dev mode), but the number that appears (49) is the same for all categories (and doesn't even equal the number of total entries).

A few things...

market group = markets ...
the category field handler = marketName


texts: How can I correctly set the time of a dateTime field from a front-end form?

texts:
I am using jQuery-timepicker to give the user an option to pick a starting time and ending time.

My init looks like this:

$('.timepicker').timepicker({
    scrollDefault: 'now'
});

When I save the entry as attached (screen below) it is displaying the time + 6 minutes.

My template looks like this:

<input type="text" name="fields[myTimes][{{ block.id }}][fields][startDateTime][date]" class="form-control datepicker" value="{{ block.startDateTime|date('m/d/Y') }}">

<input type="text" name="fields[myTimes][{{ block.id }}][fields][startDateTime][time]" class="form-control timepicker" value="{{ block.startDateTime|date('h:m') }}">

<input type="text" name="fields[myTimes][{{ block.id }}][fields][endDateTime][time]" class="form-control timepicker" value="{{ block.endDateTime|date('h:m') }}">

When I save my form, everything looks like it is saving correctly, its always +6 min. I'm not sure what I am doing wrong.

Thank you for any suggestions!

EDIT

Here is another example. I have saved for 9:00PM - 10:00PM
It saves correctly, but the template shows +6 still. :)


texts: Include results in "Object of class Craft\ElementCriteriaModel could not be converted to string"

texts:
I have a template with just this code:

{% include 'amenities/_types/amenities' %}

This results in a template error:

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

Never encountered this one before. What is causing this?


texts: Force redirect from HTTP to HTTPS via htaccess with multisite installation

texts:
I'm using Craft CMS 3 multisite installation with more than 20 website based on subdomains.
There are websites:

website.com
one.website.com
two.website.com

with identical url paths but different content.
I need to redirect each website from http to https.
Root website htaccess:

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

    RewriteCond %{HTTP:X-Forwarded-Proto} !=https
    RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R=302,L]

</IfModule>

But this adds index.php to URL while redirects. So http://one.website.com/test become into https://one.website.com/index.php?p=test


texts: Getting HTTP 500 error at end of update process when going from Craft 2 to Craft 3 with MAMP

texts:
When I try to perform an update from Craft 2 to Craft 3 I am getting a 500 error at, what appears to be, the end of the process. No other info is given.

I am using MAMP Pro V4 for Mac.


texts: Redirect to another EntryType template if no Children exist

texts:
I have a Structure Section called 'products' which uses two EntryTypes, one for 'Product Type Overview' and one for 'Individual Products', where 'Individual Products' are the children of 'Product Type Overview'.  Some 'products' have children and some do not.

I have a menu which then lists the top level entries, so in most cases the user selects 'Product A' they see a list of items (variations) belonging to 'Product A', they then click on an item to see more information about that particular product variation. -  This I have done without a problem using this method.

Here's my problem...  If the user selects a product that DOES NOT have variations (children) I need them to go straight to the child template and miss the parent 'Overview' template.

I hope that makes sense?

Any help very much appreciated.


texts:
How can I duplicate an existing multi-language entry with all the translated content?

When I choose 'Save as new items' when editing an entry, only the content in the language I selected is copied to the new entry. All the translations are lost.

Is this a bug or am I doing something wrong?

Update:

I don't know much about the inner workings of Craft, but from the http request of the action 'Save as a new entry' I can see that the entryId field is overridden by an empty value. This makes me believe that this action does not really duplicates the entry with all it's translations, but simply add's a new entry with the content of the old entry in the language from which you are viewing the entry.

Is this correct? If so, I guess I have to make a special plugin that adds an option to duplicate an entry with all it's translations.


texts:
I'm a Craft first-timer building a simple blog site. I want to include breadcrumbs at the top of each page like so:

  siteurl.com: [Blog]

  siteurl.com/category/example-category: [Blog > Example Category]

  siteurl.com/post/2015/entry-title: [Blog > Entry Title]

I've found this snippet which correctly outputs the breadcrumb for the entry permalink page:

Blog

    {% if craft.request.segments %}
        {% for crumb in entry.getAncestors() %}

{{ crumb.getLink() }}

        {% endfor %}

{{ entry.title() }}

    {% endif %}

But I also need something that will include a crumb for when the visitor is on a category page.

So far, my templates are structured like so:

templates/
 | index.html
 | _layout.html
 | posts/
    | index.html
    | category.html
    | _entry.html

Where the breadcrumb snippet is included in '_layout.html'.

In EE, I would just check my segments and use Low Seg2Cat to grab the category title. Is there an equivalent to this process in Craft? Or is it handled completely differently?


texts: Is there a way to programmatically clean/Redactorize HTML?

texts:
I'm writing a plugin to import posts from a WordPress blog. The source post formats are inconsistent, some coming with full HTML (<p> tags wrapping each paragraph, etc.), while others seem to just have tags added for formatting and emphasis—newlines but no paragraphs or <br>'s.

 $entry->setContentFromPost(array(
     'body' => $post['content'],
 ));

 $success = craft()->entries->saveEntry($entry);

So without any adjustment, many of the imported posts look crappy on the front end when they're just dropped into a template with {{ entry.body }} (Rich Text). The missing paragraph tags look less than stellar, and they're semantically uncool as well.

Redactor handles this just fine, so viewing and saving the imported entry in Craft is a breeze. It's not ideal, however, to go back and manually re-save each entry. Is there a way to re-save a cleaned Rich Text field via Craft's API, or do I need to standardize post HTML prior to my Craft import process?


texts: Image Transform in template 'Auto' errors

texts:
The docs state:

  format can be set to 'jpg', 'gif', 'png', or 'Auto'.

*Why is it 'Auto' not 'auto'?!

https://craftcms.com/docs/image-transforms#possible-values

I'm using a variable to define the transform settings:

{% set small = {
    mode:       'fit',
    width:      800,
    height:     600,
    quality:    80,
    position:   'center-center',
    format:     'Auto'
} %}

But Craft errors with:

  Imagine\Exception\InvalidArgumentException Saving image in "auto"
  format is not supported, please use one of the following extensions:
  "gif", "jpeg", "png", "wbmp", "xbm"

Is this a bug or is my code incorrect?


texts: Is it possible/recommended to use Solspace Freeform for a front-end user login form?

texts: I would like to build a front-end user login form using Freeform. Is it possible or even recommended? Right now all my form input styling/markup lives inside the Freeform render templates and it would be nice to be able to use this for the login form, instead of manually using the provided example form here.


texts: SQL error when trying to use sortOrder on Matrix related block (Craft 2)

texts:
I'm getting the following SQL error when trying to simply order related entries in a Matrix block. Anyway around this?

  CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'sortOrder' in order clause is ambiguous. The SQL statement executed was: SELECT elements.id, elements.type, elements.enabled, elements.archived, elements.dateCreated, elements.dateUpdated, ...

This is what's throwing the error:

{% set package = craft.entries({
relatedTo: block,
order: 'sortOrder'}) %}


texts: Is there any way of distinguishing whether a Date field's "time" is set or not?

texts:
Date fields can have an optional "time" box. This works nicely in the admin, but I can't figure out whether there's any way to access date and time separately when accessing that field via a template.

The use case I'm thinking of is an "Event Date" field on an "Event" entry type, which may or may not have a time (because an event may be all day, or may be at a particular time). The way you'd format the date would likely differ depending on whether the time field was filled in or not.

I realise there are other ways of achieving this effect (eg. adding an extra "show time" switch), but I'm wondering specifically whether this is currently doable using just a standard Date field's optional time field?


texts:
The following code is throwing an error for me.

{% set eventEntries = craft.entries.find({
    section: 'events',
    event_startDateTime: '<= {{ now }}',
    limit: '4'
}) %}

{% for entry in eventEntries %}

Fatal error: Call to a member function getTimestamp() on a non-object

What I'm trying to do is pull 4 events where a date field (event_startDateTime) is before the current time.  My suspicion is that the {{ now }} variable isn't parsing inside the single quotes, but I'm not entirely sure.  Can anyone correct my code?


texts: Limit the entries element API will return based on the post date

texts: I'm looking to only return entries that were published in the last 90 days.


texts: Using {% cache globally %} inside {% cache %}

texts:
I am currently building a website that consist almost entirely of blocks.

There are quite a few pages that use the same blocks, but sometimes with slightly different content and not always in the same order.

I have built a matrix field to construct each page out of these blocks and most of these blocks have their own template.

Basically I do this:

{% for block in matrix %}

  {% if block.type == 'type1' %}
    {% include 'type1.twig' %}

  {% elseif block.type == 'type2' %}
    {% include 'type2.twig' %}

  {% endif %}
{% endfor %}

Some of these blocks however, also have for loops in them accessing matrix fields.

I was wondering if it is possible to use {% cache %} tags around my for loop that loops through all the basic blocks, and then within my block templates another {% cache %} tag but with the globally parameter.

So in short, can I safely use cache tags inside other cache tags?


texts: Worldpay Offsite Gateway not redirecting to Customer Order screen on successful transaction

texts:
I am having issues with Craft Commerce and Worldpay's Offsite Payment Gateway.  The way my clients accounts are set up with Worldpay, I cannot use the Worldpay JSON option so this I have to use the offsite method.

Basically, I have it working that its coming through as successful transaction on Worldpay's end - however I get left on the offsite thank you page, it doesn't redirect back to my local craft install.

Is there something that I need to do to trigger this? Because of this the order sits in my Orders under the Active cart tab, it does not fully complete.

Any suggestions appreciated.

Thanks


texts: How to setup the Craft Commerce store both front and back end

texts:
We've a requirement to setup Craft Commerce store as part of our testing, in this process we've gone through the documentation and found that we need to use HTML, CSS or JS code to complete the store setup.

Could anyone please help us how to setup the store?


texts:
I have a snippet within a template which I want to pass a variable into:

page.twig

{% set lightswitchTest = entry.aktivesProjekt('1').find() %}

{% include '_snippets/thingy' %}

thingy.twig

<div class="panel{% if lightswitchTest == null %} notActive{% endif %}">
   {# bla bla #}
</div>

I tried to add pass in the variable with the with keyword but I guess my syntax is wrong?

{% include '_snippets/thingy' with lightswitchTest %}

If i use the varibale now in the snippet there is just the Array to string conversion error.

What am I missing? Is there a better way?


texts:
I need to install Craft under a laravel sub-directory http://example.com/corp/ where example.com is a laravel site.

Does anyone have a clean way to install craft in a directory below an existing app?

Here is my config from /corp/public/index.php

// Path to your craft/ folder
$craftPath = '../../../craftsite/craft';

// Do not edit below this line
$path = rtrim($craftPath, '/').'/app/index.php';


texts:
I have a Craft application in an intranet behind a proxy.
I'm struggling to find a way of configuring the application so it can access the internet via the proxy, in particular for the auto updating and license check.

I tried using PHP's stream_context_set_default() but cannot get it to work in the admin section. Here's what i did so far:

I created a connect.php file in my public folder just to check if my script works.
It does as i can get the headers for any site.

$PROXY_HOST = "url.to.my.proxy";
$PROXY_PORT = "8080";
$PROXY_USER = "username";
$PROXY_PASS = "password";

$auth = base64_encode("$PROXY_USER:$PROXY_PASS");
stream_context_set_default(
  array(
    'http' => array(
      'proxy' => "tcp://$PROXY_HOST:$PROXY_PORT",
      'request_fulluri' => true,
      'header' => "Proxy-Authorization: Basic $auth"
    )
  )
);

$url = "https://elliott.buildwithcraft.com/actions/elliott/app/ping";

print_r( get_headers($url) );

From there, i'm stuck. I have no idea what to do next to try and inject that into the auto updating part of Craft. I know it's bad to mess with the core, and don't want to, but i have no idea where to go from here.

Anyone been in a similar situation ?
Am i missing something obvious where all of this wouldn't be needed ? (hope so)

Following @BradBell answer i searched for Guzzle information and found this in the documentation for Guzzle 3.x:

  Requests options can be specified when creating a request or in the request.options parameter of a client. These options can control various aspects of a request including: headers to send, query string data, where the response should be downloaded, proxies, auth, etc.

$request = $client->get($url, $headers, array('proxy' => 'http://proxy.com'));

Maybe this can be put to some use in the current Craft install?
If so, some guidance will be greatly appreciated.


texts:
I am very new to Craft CMS and going through the introduction videos on Mijingo.  I am new developer also so please answer in easy terms if you can. I need to know what the difference is between an image I might drop straight into the assets file (if I choose) or the uploaded ones through Craft. I understand that you want to use images in the CMS they NEED to be uploaded through Craft. BUT why would you use "static" images straight into the assets file? My colleague said if you want to use interface pictures you drop them straight in. But I don't understand what that means. Thanks very much and have a great day.

Jason

P.S. Please say why if this was a bad question so I can become better at asking on Stack Exchange. Thanks again!


texts:
I'm creating a site that works now at www.mysite.com/public/

I would love to get to drop the /public off the url so it is:

www.mysite.com

Does anyone know how to do this?

Thank you!


texts: Contact Form plugin - Error loading 404 Pages

texts:
So I have a contact form in my layout (just using the contact form plugin from the Craft guys) and on 404 pages I'm getting the following:

  Impossible to invoke a method ("getErrors") on a string variable ("") in "_layout"

What's the best way around that and to still get the contact form to show up on an 404 page?

Many thanks in advance!

Template code is in the footer of _layout.html and looks like this:

    {% set asset = globalContact.contactBackground.first() %}

                {{ globalContact.contactPreHeader }}

                {{ globalContact.contactHeader }}

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

                        {% for error in errors %}

{{ error }}

                        {% endfor %}

                {% endif %}
            {% endmacro %}

            {% from _self import errorList %}
            <form method="post" action="" class="contact-form" accept-charset="UTF-8">
                {{ getCsrfInput() }}
                <input type="hidden" name="action" value="contactForm/sendMessage">
                <input type="hidden" name="redirect" value="thanks">

                    <input type="text" id="fromName" name="fromName" placeholder="Name" />
                    {% if message is defined %}{{ errorList(message.getErrors('fromName')) }}{% endif %}

                    <input type="text" id="fromEmail" name="fromEmail" placeholder="Email" />
                    {% if message is defined %}{{ errorList(message.getErrors('fromEmail')) }}{% endif %}

                    <input type="text" id="phone" name="message[Phone]" placeholder="Phone" />

                    <textarea rows="8" cols="40" id="message" name="message[body]" placeholder="Message">{% if message is defined %}{{ message.message }}{% endif %}</textarea>
                    {% if message is defined %}{{ errorList(message.getErrors('message')) }}{% endif %}

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

                    <input type="submit" value="Submit" />

            </form>


texts:
I just want to create a modal and play with it, but can't find a way to do so. I already checked other questions on the subject, but I still can't figure why my modal isn't showing correctly.

Here is my code :

            some text I'd like to be shown...

var $modal = new Garnish.Modal($('#my-modal'));

$('#show-modal-btn').click(function() {
    $modal.show();
});

When I load the page, the big shader appears instantly, and my modal is nowhere to be found, and it moved in the dom tree. Clicking the button doesnt make it appear again.


texts:
I have pagination twig component that needs to inject seo links into  of page (rel canonical).

I tried to use {% block %} twig tag for this, but problem is that pagination component is already included in another {% block %} tag containing main content of page.

In short, im trying to do this:

layout.twig:

<html>
<head>
{% block seo %}{% endblock %}
</head>
<body>
{% block main %}{% endblock %}
</body>
</html>

page.twig:

{% extends 'layout.twig' %}

{% block main %}

some content..
{% include 'pagination.twig' %}

{% endblock %}

pagination.twig:

... pagination links

{% block seo %}
<link href="url" rel="canonical">
{% endblock %}

When im using this code, block seo is empty.
Can this be achived some other way?


texts: Triggering the start of a task from a CRON job

texts:
I have a site setup which is for subscribers only. I have added a user expiry date field to the users section and everything is working perfectly on the front end in that I can restrict access to accounts that have already passed their expiry date.

However I need to send notification emails to accounts that expire today or will expire in 7 days time.

I am using the mailer plugin in combination with a basic plugin I have made. I have setup a basic plugin with a controller which calls the following function from the plugins service:

public function sendNotificationEmail()
{
    //Create an EmailModel
    $email = new EmailModel;

    //Set the necessary attributes
    $email->fromName = 'Joe Blogs';
    $email->fromEmail = 'joe.blogs@example.com';
    $email->subject     = 'Email subject';
    $email->htmlBody    = 'The message';

    //RecipientsModel
    $recipients = new Mailer_RecipientsModel();
    $recipients->recipients = array(
        array(
            'to' => 'jane.doe@example.com'
        )
    );

    if( $recipients->validate()){
        //Create mailer
        craft()->mailer_main->newMailer($recipients, $email); //This will start the MailerTask
    }

}

As you can see, at the moment I'm just sending a single test email each time. Everything works as expected but I've noticed that the task does not get triggered until I refresh the CP. This is a problem in my case, I think, because I want to trigger everything from a CRON job.

If anyone has any solution as to how to automatically trigger the task or if there are any alternative methods to solve this problem, I'd love to here them :)

btw, the reason I went down the task route was that the system could be sending to 100s of email addresses at a time and I didn't want to be (a) treated as spam or (b) get a timeout from the request


texts:
i want to develop a windows phone application and receive notification from my CMS opencart
So to send notification from my CMS, i must develop a module !

what's the steps can i follow to develop module for send notification from CMS OP to windows phone application?


texts: Getting "Invalid verification code." on password reset

texts:
I've had a few users on our site have trouble resetting their password. They go through our "Forget password" flow on the front-end of our site, receive the reset email, which allows them to create a new password. But when they try sign in, they receive the following error:

Based on this thread, I thought the issue might have been our email parsing… but here's the weird thing… same thing happens when I grab the reset link directly from the control panel using this dialog then pasting it directly in a different (signed-out) browser:

I'm getting the exact same error every time I try it with either method (this was definitely working a few months ago on the same server, PHP version, etc).  Any ideas? Thanks!


texts: Add new translation app.php file in Craft

texts:
I'm trying to add a new language file in Craft Control Panel admin site. I have created app.php inside translations/vi folder like this:
-my app folder
|-- translations
|----- vi
|-------- app.php

The translation will only appear when i create a vi folder in vendor/craftcms/cms/src/translations.
Is there any solutions other than adding a folder inside vendor?
what I have tried:

Adding this to the config/app.php

    return [
        'components' => [
            'i18n' => [
                'translations' => [
                    'app' => [
                        'class' => craft\i18n\PhpMessageSource::class,
                        'sourceLanguage' => 'vi',
                        'basePath' => dirname(__DIR__) . '/translations',
                        'allowOverrides' => true,
                    ],
                ],
            ],
        ],
    ];


texts: How to add active class to homepage nav list item

texts:
Someone provided a solution, via the Craft Google community, but it was suggested that I also post it here for others to use.

Home

Work

About

The above was adapted from the demo site install (I think) and although 'work' and 'about' work fine 'homepage' did not.  I used 'homepage' as this is the 'handle' in the craft sections part of the cms so I thought that would be correct.

I initially found this How can I add a dynamic "active" CSS class to the navigation on any given page? but not being that dev focused found the many alternatives a bit confusing.

It was suggested that I add a 'section' to the homepage template and so I added {% set section = "home" %} after {% extends "_layout" %} in the homepage  index.html.

I then amended my first
 from above to be just

Home

which worked as required.

I hope that helps.

If anyone can explain why my original doesn't work, in layman's terms that would be much appreciated.

Thanks

Laurence


texts:
Is it possible to use craft multilanguage capabilities without locale url segments?

Example:

German: domain.com/wetter

English: domain.com/weather

I know this is pretty dangerous. If one forgets to translate the url everything will fall apart. But I wonder if it would be possible theoretically :)


texts:
I am trying to initiate multiple Google Map instances on a page.

I need to set a dynamic ID for each one. I've tried doing it with loop.index but no joy.

{% for marker in event.eventMap.getMarkers() %}
    <div class="google-maps">
        {% set options = {
            id: 'map',
            width: '100%',
            height: '150px',
            options: {
                disableDoubleClickZoom: true,
                maxZoom: 15,
                minZoom: 5,
                scrollwheel: false
            }
        } %}

        {{ craft.googleMaps.map() }}

        {{ craft.googleMaps.data('map', event.eventMap) }}

    </div>
{% endfor %}


texts: Front end form with Matrix won't add more than one row

texts:
I have Notification entry with sendTo field and nViewed matrix:
- viewedBy = Users field, limit of 1
- viewedDateTime = Plain Text

User's don't see whole front end form, just a 'Mark as Read' link. The link uses js to populate viewedDateTime and submit form. My form:

<form id="update-{{ msg.id }}" method="post" accept-charset="UTF-8">
   {{ csrfInput() }}
   <input type="hidden" name="action" value="entries/save-entry" />
   <input type="hidden" name="redirect" value="{{ theredirect }}" />
   <input type="hidden" name="sectionId" value="{{ msg.section.id }}" />
   <input type="hidden" name="entryId" value="{{ msg.id }}" />
   <input type="hidden" name="fields[nViewed]" />
   <input type="hidden" name="fields[nViewed][new1][type]" value="viewed" />
   <input type="hidden" name="fields[nViewed][new1][enabled]" value="1" />
   <input type="hidden" name="fields[nViewed][new1][fields][viewedBy][]" value="{{ currentUser.id }}" />
   <input type="hidden" name="fields[nViewed][new1][fields][viewedDateTime]" value="" />
   <button type="submit" class="tx-11 btn bd-0">Mark as read</button>
</form>

When the first user from sentTo clicks the 'Mark as Read' link, they get added to the matrix. All good.

When the second user from sentTo (testing on a different browser) clicks the 'Mark as Read' link it overwrites the first users row instead of adding another row to matrix.

I've also tried using field name="fields[nViewed][new{{ currentUser.id }}]... to make them unique but still overwrites.

What am I missing?
Amanda


texts: How can I add headings using the Rich Text field

texts: How can I add the functionality for my clients to make text not just bold or italic, but have h2, h3, h4 headings too?


texts: Craft CMS plugin with AJAX gives 404 error

texts:
I have created a small craft cms plugin to pull some information from the DB, and everytime I execute the plugin I get a 404.

Here is the controller

namespace Craft;

class UserExists_UserControllerController extends BaseController
{
    public function actionGetUser()
    {
        $this->returnJson($response);
    }
}

And this is the jquery:

$.ajax({
    url: "{{ url("actions/userexists/usercontroller/getUser") }}",
    dataType: "json",
    success: function(data){
        console.log(data)
    }
});


texts: Why do I get Access denied on s3 asset source images?

texts:
I have created an s3 bucket in aws and added the correct permissions and user group etc. I have added the below policy:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "s3:PutObject",
                "s3:GetObjectAcl",
                "s3:GetObject",
                "s3:ListAllMyBuckets",
                "s3:ListBucket",
                "s3:DeleteObject",
                "s3:GetBucketLocation",
                "s3:PutObjectAcl"
            ],
            "Resource": "*"
        },
        {
            "Sid": "VisualEditor1",
            "Effect": "Allow",
            "Action": [
                "s3:ListBucket",
                "s3:GetBucketLocation"
            ],
            "Resource": "arn:aws:s3:::bucketname"
        }
    ]
}

I uploaded the assets from a local folder via ftp to the bucket using transmit ftp client which was fine. I have then set the bucket up on craft cms as an asset source. I can upload files to s3 via the cms fine with no issues and view the image fine but when I try to access an image on the front end that was uploaded via the ftp I get access denied error 403:

<Error>
AccessDenied
<Message>Access Denied</Message>
<RequestId>96E15AB155C47209</RequestId>
<HostId>
our-hist-id-here
</HostId>
</Error>

edit here

So after some research I found out that you needed to add the policy directly to the bucket. You used to have to create a policy away from the bucket page itself in the IAM area but now(I think) it needs to be in the bucket.

Is this a policy issue?

Thanks


texts: Does anyone know if I can output the number of children the current entry (structure) has?


texts: Craft 3 : What are the advantages to use PostgreSQL and when should I use it instead of MySQL?

texts:
Craft 3 now supports PostgreSQL.

I know this a very general question, but:

I have absolutely no experience with PostgreSQL
I don't know when should I use it instead of MySQL

To quote Bob Olde Hampsink:

  PostgreSQL is the most innovative and hot database engine at the
  moment. It has better UTF-8 support and better overall performance.

  Also, for example, on Heroku it is much cheaper to host with Postgres
  than with MySQL. Thus it becomes more attractive for people to pick a
  CMS/framework with Postgres support.

Is there another good reasons to know, to choose one instead of the other when starting a new project? For example, in general what would be the gains in terms of performance, compared to MySQL?


texts: Sprout Form redirect after submit not working correctly

texts:
All my forms on sprout form won't use the redirect they get assigned via the Form builder. Whenever a form is succesfully submited it redirects to my homepage instead of my thank-you page.

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

    <input type="hidden" name="action" value="sprout-forms/entries/save-entry">
    <input type="hidden" name="handle" value="{{ form.handle }}">
    <input type="hidden" name="redirect" value="{{ form.redirectUri }}">
</form>

Even if I write the redirect URL manually it keeps redirecting me to the homepage.

The only way I can get the redirect to work is when I let sprout forms render the fields.


texts:
I’m moving new project from Wordpress to Craft, which has the hierarchy in URLs.

I’m try to compose URL for this new project:

New category field have an option "Limit the number of selectable categories."

I change to 1, because this category is part of URL structure: blog/{state.first.slug}/{myCategory.last.uri}/{postDate|date("Y")}/{postDate|date("m")}/{slug}

{myCategory.last.uri} can be nested, but, as I limited to 1, and I select any category of level 2 is automatically selected level 1.

I can't able to select only one category keeping levels? (I know it sounds weird) Like: /blog/stateCategory/myCategoryLevel1/myCategoryLevel2/2016/07/slug ?

In the end, I just wanted to limit the “one" inside the hierarchy...

Selecting “myCategoryLevel2” automatically place the “MyCategoryLevel1" in the url. I know this sounds very strange, but this new project, I need to leave identical url structure.

How could I solve this?

Thanks!


texts: How to view a draft page in live view without publishing it

texts: I am creating a news item page for a future release but I can't figure out how to preview it in Live View without Enabling it.  Is there a way to view a page in progress without publishing it live?


texts: CDbException: The DB query must contain the "from" portion

texts:
Seeing the above error, somewhat sporadically, and can't seem to track it down.

Here's the full log entry:

2014/07/03 15:17:22 [error] [exception.CDbException] exception 'CDbException' with message 'The DB query must contain the "from" portion.' in /var/www/topsecret.co.uk/craft/app/framework/db/CDbCommand.php:566
Stack trace:
#0 /var/www/topsecret.co.uk/craft/app/framework/db/CDbCommand.php(160): CDbCommand->buildQuery(Array)
#1 /var/www/topsecret.co.uk/craft/app/framework/db/CDbCommand.php(484): CDbCommand->getText()
#2 /var/www/topsecret.co.uk/craft/app/framework/db/CDbCommand.php(415): CDbCommand->queryInternal('fetch', Array, Array)
#3 /var/www/topsecret.co.uk/craft/app/etc/behaviors/AppBehavior.php(410): CDbCommand->queryRow()
#4 /var/www/topsecret.co.uk/craft/app/etc/behaviors/AppBehavior.php(146): Craft\AppBehavior->getInfo('edition')
#5 [internal function]: Craft\AppBehavior->getEdition()
#6 /var/www/topsecret.co.uk/craft/app/framework/base/CComponent.php(261): call_user_func_array(Array, Array)
#7 /var/www/topsecret.co.uk/craft/app/services/LocalizationService.php(111): CComponent->__call('getEdition', Array)
#8 /var/www/topsecret.co.uk/craft/app/services/LocalizationService.php(111): Craft\WebApp->getEdition()
#9 /var/www/topsecret.co.uk/craft/app/services/LocalizationService.php(141): Craft\LocalizationService->getSiteLocales()
#10 /var/www/topsecret.co.uk/craft/app/services/LocalizationService.php(154): Craft\LocalizationService->getPrimarySiteLocale()
#11 /var/www/topsecret.co.uk/craft/app/etc/web/WebApp.php(824): Craft\LocalizationService->getPrimarySiteLocaleId()
#12 /var/www/topsecret.co.uk/craft/app/etc/web/WebApp.php(291): Craft\WebApp->_getTargetLanguage()
#13 /var/www/topsecret.co.uk/craft/app/framework/i18n/CMessageSource.php(83): Craft\WebApp->getLanguage()
#14 /var/www/topsecret.co.uk/craft/app/framework/YiiBase.php(585): CMessageSource->translate('yii', 'The DB query mu...', NULL)
#15 /var/www/topsecret.co.uk/craft/app/framework/db/CDbCommand.php(566): YiiBase::t('yii', 'The DB query mu...')
#16 /var/www/topsecret.co.uk/craft/app/framework/db/CDbCommand.php(160): CDbCommand->buildQuery(Array)
#17 /var/www/topsecret.co.uk/craft/app/framework/db/CDbCommand.php(484): CDbCommand->getText()
#18 /var/www/topsecret.co.uk/craft/app/framework/db/CDbCommand.php(415): CDbCommand->queryInternal('fetch', Array, Array)
#19 /var/www/topsecret.co.uk/craft/app/etc/behaviors/AppBehavior.php(410): CDbCommand->queryRow()
#20 /var/www/topsecret.co.uk/craft/app/etc/behaviors/AppBehavior.php(371): Craft\AppBehavior->getInfo('maintenance')
#21 [internal function]: Craft\AppBehavior->isInMaintenanceMode()
#22 /var/www/topsecret.co.uk/craft/app/framework/base/CComponent.php(261): call_user_func_array(Array, Array)
#23 /var/www/topsecret.co.uk/craft/app/etc/web/WebApp.php(145): CComponent->__call('isInMaintenance...', Array)
#24 /var/www/topsecret.co.uk/craft/app/etc/web/WebApp.php(145): Craft\WebApp->isInMaintenanceMode()
#25 /var/www/topsecret.co.uk/craft/app/framework/base/CApplication.php(180): Craft\WebApp->processRequest()
#26 /var/www/topsecret.co.uk/craft/app/index.php(196): CApplication->run()
#27 /var/www/topsecret.co.uk/web/index.php(17): require_once('/var/www/topse...')
#28 {main}

Looking through that I'm not seeing any references to any custom plugins or templates so wonder if it's a bug...

Any suggestions would be very much appreciated!


texts: Prevent adding users with same email addresses

texts:
I am adding new users inside of the Craft controller as part of the frontend user import script.
This is the code:
$user = new User();
$user->pending = true;
$user->username = $email;
$user->firstName = $firstName;
$user->lastName = $lastName;
$user->email = $email;
$user->passwordResetRequired = false;
$user->validate(null, false);
Craft::$app->getElements()->saveElement($user, false);

The problem is that if I try to import two users with the same email addresses they just get imported and that's obviously something I don't want to happen. How can I prevent that and silently skip the users with existing email addresses.
I could check the user's existence by querying it in the database but I would like to avoid any unnecessary db queries because there will be thousands of users imported at the same time. That validation line looks promising but I'm not finding any useful instructions in the docs.


texts: Getting "Internal Server Error: Function 'dump' does not exist" when accessing/creating custom fields

texts:
On my in-development version of a site I'm working on, I'm unable to access any of my custom fields without Craft displaying an error that reads:

  Internal Server Error Function "dump" does not exist

I can navigate to Settings > Fields but when I attempt to click on any of my fields to check/adjust settings or when I try to create a new field, I get the error screen. I'm able to access all other parts of the CP, create entries, adjust settings, etc.

The odd thing is that I have a working instance of the site running in my local environment. As part of my troubleshooting process, I dumped the database on the staging site and imported my local version. I also replaced the "craft" folder on my staging site with the one from my local site. The problem still persists.

I recently updated to the latest build (2.1.2569) so I first thought something in the update might need fixing, but my local instance is updated as well and completely functional.

In case it helps, I'm hosting my staging site on Arcustech and have had no issues up to now.

Any ideas what might be going wrong?


texts: Craft “Embedded Assets” Plug-in didn't save Embed in selected Asset Volume in CP

texts:
i have 3 asset volumes in my craft install (3.1.5). If i want to create an embedded asset(Embedded Assets Plugin 1.0.2) in the first volume (CP) in my volume List than it appears in the second. Every Embed Asset appears in the second Volume!
What am I doing wrong?


texts: How to get current site (locale) api / plugin

texts:
For my form plugin I'm using a global set of fields. These can be set in 2 languages default and en.

Problem is whenever I try to output them I cant dynamically make them use the current site locale/multi-site.

This is the current code:

$localeHandle = Craft::$app->getSites()->getCurrentSite()->handle;
    // form texts
    $entries = GlobalSet::find()
        ->siteId('*')
        ->site($localeHandle)
        ->handle('popupContact')
        ->asArray()
        ->one();

If $localeHandle is set to either default or en it works. I cant figure out how to get the handle though. Documentation doesn't state anything either.

Edit:
Craft::$app->getSites()->getCurrentSite()->handle; returns the default site handle.


texts: Description and logo at the very top of browser?

texts: All, After we switched from Wordpress to Craft our site description and logo at the very top of the browser tab have been disappeared as shown in the image. Could you please guide me how can I achieve this?


texts: Is there a way (or plugin) to organise headings alphabetically? You can drag and drop to rearrange but if its a contact list for example, being alphabetised is really useful.


texts: How to reference the current entry via twig in the control panel?

texts:
I'm trying to write a general use plugin for a calculation fieldtype that evaluates a twig expression (defined in the field settings) to display additional information about the current record in the CP (i.e. price * qty = amount). So far, everything is working perfectly — the generic expression 1 + 1 is evaluated and the result is properly displayed in the field.

The problem is, I don't actually know how to reference the current entry in the CP from within the CP via twig, to get access to the entry field values. Looking for something like {{ entry.price }} * {{ entry.qty }}, but don't know what to use instead of entry. Does anyone know a twig expression that I can use?


texts: How do I get the current user’s info over Ajax?

texts:
I created an Ajax-based login form based on this gist: https://gist.github.com/keithmancuso/29e8446ec5fa66fb2b01.

After the user has logged in, how can I get some info about them over Ajax?


texts: Twig default filter or Null coalescing operator?

texts:
When testing for a variable in a template these two appear to do the same thing. I've read CruftlessCraft's article on How to check for undefined variables but can't see an explanation of why I should use one over the other. In his examples (below) I note that only the default filter includes "" in the list of results, is that correct or significant?
Is one faster or more efficient?

{% if twigVariable|default %}
    Value is set and not empty
{% else %}
    Value is either undefined, false, 0, null, "", [] or {}
{% endif %}

or

{% if twigVariable ?? false %}
    The value is set and not empty
{% else %}
    Value is either undefined, false, 0, null, [] or {}
{% endif %}

Does it make any difference if I don't need a fallback or the else and am just wrapping it around a div that shouldn't be shown if the variable doesn't have any usable content?


texts:
I've been searching all over for this and have been coming up short unfortunately. Does anyone know if it's possible with in Craft CMS 3 to allow custom sorting of categories on a per entry basis?

For instance, maybe one entry is:

Category 1
Category 2
Category 3
Category 4

And on another entry, the admin orders the categories as:

Category 3
Category 4
Category 2
Category 1

If not available in Craft's core functionality, does anyone know of a custom category field type that allows this?

Thank you!

Evan


texts:
Very new to Craft CMS...

My first route, which i think is very simple, is not working, i'm getting a 404 error.  How can I troubleshoot routing?

My settings:

If the URI looks like this:

databases/

Load this template:

library-database-demo-section/index.html


texts:
What's the best way to redirect to a trailing slash in Nginx with Craft CMS? I've seen some advice for Apache .htaccess, etc, but not Nginx. For those curious, here's why I might want to do this: To slash or not to slash.

NYStudio107 recommendations advise removing the trailing slash, but since we were formerly on Wordpress and had a trailing slash to begin with, I want to be consistent with the past history in Google Analytics.


texts: Display sub-category depended on selected category with related entries

texts:
I am not even sure, I can explain it.

I have a several sections, but I'll go with "Products" section. Than I have category group called "Filter". I'd like to use only this category group for all sections. ( if there is a better approach/start in this step, include it in your answer ).
When page "Products" is loaded, there should be a category list of top level categories only + entries related to "Products".
When a top level category link "Cat1" is clicked at "site.com/products", a page "site.com/products/cat1" should load. On "site.com/products/cat1" page should be a category list of top level categories + sub level categories + entries related to sub level category.
Then, when a sub level category link "cat1.1" is clicked, a page "site.com/products/cat1/cat1.1" should load with the same scenario as in previous step.
We will carry on up to, when we have url formed like this: "site.com/products/cat1/cat1.1/cat1.1.1/entry-title"

I hope, you have some image about, What I'm trying to draw here.
I only see this achievable through sections and categories.


texts: How do I make a service only runable by the server?

texts:
I've created an action that calls a service. The action will be called by a cron task. I want to set this up so that ONLY the cron task can call the action. It's important that it can not be run by any other means (via HTTP, CURL request etc.).

Any ideas on how to do that?

UPDATED (I think this will work):

public function actionMethod()
{
    $this->requireAjaxRequest();

    $key = craft()->request->getParam('key');

    if($key == 'random-string' && $_SERVER['REMOTE_ADDR'] == 'my-servers-ip-address') {
        craft()->plugin_name->actionMethod();
    }

}

Note, this is twinned with a cron tab that looks like:
curl -H "X-Requested-With: XMLHttpRequest" http://sitename.co.uk/actions/plugin_name/Method?key=random-string


texts: Special characters in `template->renderObjectTemplate` method

texts:
Having a problem with the Formerly plugin where it is throwing an error if CSS is passed into the Submission body. Not sure if this is a Craft of a Formerly problem but looking into it further, the issue seems to occur when ! or ; are being passed into the templates->renderObjectTemplate() service - this results in an Unexpected character error being returned.

Any thoughts on how best to sanitise the input for this method so that form submission doesn't break?


texts: Commerce 2 Adding tax to custom adjuster

texts:
I have created a custom adjuster, there is a surcharge per item if a customer has selected rush delivery. But i need to charge tax on that adjuster. Below is code:

public function adjust(Order $order): array
{
    $adjustments = [];

    foreach ($order->getLineItems() as $item) {
        $adjustment = new OrderAdjustment;
        $adjustment->type = 'rush-delivery';
        $adjustment->name = 'Rush Delivery';
        $adjustment->description = 'Rush Delivery';
        $adjustment->sourceSnapshot = ['data' => 'value']; // This can contain information about how the adjustment came to be
        $adjustment->amount = 1;
        $adjustment->setOrder($order);
        $adjustment->setLineItem($item);

        $adjustments[] = $adjustment;
    }

    return $adjustments;
}

But tax is not added to the £1 i am adding here. How can i get tax to be added or calculated as included?


texts: I'm trying to add a new event to the menu bar. I've created the page, but it's not showing up under the menu bar. Can you please help!?


texts:
We launched a site for a scientific publication and they use subscript and superscript in lots of their content. Now they'd like to use in entry titles too..

I know I can set the entry title to be a custom field, but that field would be a rich text field in this case, which is far far far from ideal for a title.

I'm using this plugin to add sub/superscript https://github.com/elliotlewis/Redactor-Extras

Looking to fix this without having to use a rich text field.

Any pointers are greatly appreciated!


texts:
I'm working on a plugin, and would like to add a new Record, I already have some records, and would like to keep the data.

Is there a way to activate a new record type, without re-installing the plugin, thus loosing the other records data?


texts: How to make a separate RSS feed for each entry type of a section?

texts:
I would like to make a separate RSS feed for each entry type of a section, for example:

http://mysite.com/posts/feed.rss

http://mysite.com/videos/feed.rss

...


texts:
Trying out Sprout Email on a fresh local (MAMP/PHP 7.1) install, and whenever I try and create a new Notification I get

PHP Warning – yii\base\ErrorException
get_class() expects parameter 1 to be object, string given

in /vendor/barrelstrength/sprout-base-email/src/controllers/NotificationsController.php

Tried a few different PHP versions in case that helps, but same. Anyone experienced this before and got any suggestions? Much appreciated.


texts:
I am use a load more button in place of pagination. I just using jquery and ajax using this post as a starting point.

The problem I'm having is how to hide the button when there is no more posts to show. I thought I could do this with pagination but its not working out.

Here is my blog index:

            {% paginate craft.entries.section('blog').limit(2) as pageInfo, blogEntries %}

            {% for entry in blogEntries %}

{{ entry.title }}

Posted on {{ entry.postDate.format('F d, Y') }}

Continue reading

            {% endfor %}

        {% if pageInfo.nextUrl %}

            <button id="more-button" data-page="{{craft.request.getPageNum()}}" data-batch="2">Load More</button>

        {% endif %}

Here is my javascript:

import $ from 'jquery';

$("#more-button").on('click', function () {
var btn = $(this),
    page = btn.data('page'),
    batch = btn.data('batch'),
    offset = page * batch,
    newPage = page + 1;

loadPosts(offset, batch);
// set the buttons page attribute to the new page it is on.
btn.data('page',newPage);

console.log('page');
console.log(newPage);
});

function loadPosts (offset, limit) {
$.get('/ajax/posts', { offset:offset, limit:limit }, function (data) {
    var postOutput = $('#post-output');
    postOutput.append(data);
});
}

and here is the ajax/_posts:

{% set offset = craft.app.request.getParam('offset') %}
{% set limit = craft.app.request.getParam('limit') %}
{% set moreitems = craft.entries.section('blog').limit(limit).offset(offset).all() %}

{% for entry in moreitems %}

{{ entry.title }}

Posted on {{ entry.postDate.format('F d, Y') }}

Continue reading

{% endfor %}


texts:
I have created a section called "Services" and an entry within called "seo".  When I click to view that entry in the admin area, it takes me to domain.com/services/seo, as expected, but that 404s.

Is there anything else required to use channels?

I have .htaccess in place working properly and the shipped sections ('News', and the home page) all load fine.


texts:
I'm a newbie with Craft. I want to host Craft 3 application (with TWIG templates) on Azure app services.
I couldn't find documentation of Craft's documentation. Any help will be appreciated.
Thanks in advance.


texts:
For a big client we are required to set up their blog on their Hubspot account. However we are developing everything else in Craft.

What is the easiest way to make the connection so the client can use Hubspot to post blog entries into our Craft site?


texts: Can you set the redirect path for system forgot password form?

texts:
At the moment when a user clicks on the forgot password link in an email the following happens:

User is redirected to the forgot password page.
User enters their new password.
User is redirected to the Craft admin login page.

Is there a way to set where they are sent to? For example, if they do not have admin access I don't want to be showing them the admin login page.

Thanks,

Gareth


texts: Can I setup multiple sites under one Craft install?

texts:
I have not used Craft much, but can I setup multiple sites under one Craft install?

If I can, which version of Craft is needed?

Thanks.


texts: Get the category into the url of the product page

texts:
I'm in the middle of learning Craft Commerce.  When I go to an individual product my URL says /shop/wella-shampoo/.  I'd like it to say /shop/**hair-care**/wella-shampoo/ because this is the category this product falls into.
I've tried adding shop/{categories.first().slug}/{slug} to the URL Format but I get the following error:

Internal Server Error
Craft\Commerce_ProductModel and its behaviors do not have a method or closure named "categories".


texts:
Im trying to figure out how to get Entries by date range, say I would like to get all Entries from one week back, or I would like to get all Entries from a specific month.

I find some Twig examples, but haven't successfully been able to translate them to php for use in my plugin.

Any help is much appreciated.


texts:
I have an Entry field (page) as part of my Matrix field (footer).

When the client selects 5 entries, I want to display them all in my list and not just the first. I can only seem to get my code working with .first or .last. Everything else I try gives me the old "Object of class Craft\ElementCriteriaModel could not be converted to string" error.

{{ block.navSection }}

        {% if block.type == "footerCategory" %}
        {% set page = block.page.first() %}

{{ page.title }}

        {% endif %}

My matrix for this list:


texts: Redactor migration might fail with allowAdminChanges & useProjectConfigFile false

texts:
One of the recent Craft updates (something close to 3.1.25) also brought a redactor migration (https://github.com/craftcms/redactor/blob/v2/src/migrations/m190225_003922_split_cleanup_html_settings.php), which fails when those 2 configs are disabled:

'allowAdminChanges' => false,
'useProjectConfigFile' => false,

The reason why it fails is that the migration tries to do something with projectConfig, which is read only when allowAdminChanges is disabled.


texts:
I'm new to Craft CMS and I'm trying to build a new website using Craft. I want my client to be able to change the order of displaying contents of a page by dragging and rearranging them in the Admin panel. So I created a Section called 'Home Page' with type Single and I created few fields with type Matrix and I updated the Entry Type for section Home Page with those new fields. Home Page appeared in the Entries under Single as expected and I was able to update the contents on the matrix fields as well.
Then I created a twig file and used the content entered via Admin to render the home page. So far so good but my client wants to rearrange the fields (I don't know whether I  can call them fields) in the Home Page via Admin by dragging them around and that should be reflected in the rendered homepage.
I thought of creating a subfolder and separate twig files for rendering the entry types in the home page but what I don't know is how I can query the entry types from the entry object in the order in which it's configured via the Admin panel.
My Home Page in Admin now looks like this
Banner
Why Choose Us
What We do
Our Clients
Testimonials

And my client wants to change this to say
Banner
What We do
Our Clients
Why Choose Us
Testimonials

Once they change this, it should be reflected in the rendered home page. Is this possible in Craft?


texts: using craft.request.getParam to filter by relations

texts:
I'm requesting entries through a search field like so:

{% set params = {
  section:      'tours',
  startloc:     craft.request.getParam('zoekplaats')
} %}

{% for entry in craft.entries(params) %}
...etc..
{% endfor %}

which works fine. However, as soon as the 'startloc' field type becomes an 'entry' (thus a relation) I can't simply state 'startloc:' anymore, as it has become an entire object. However, I'm quite limited to the syntax I can use within that params field.

I've tried many things but can't really figure it out. Anyone that knows what the correct way to do it would be?

Thanks a lot!!


texts: Get matrix entries related to an image asset via specific field

texts:
I have a Matrix field that has an Entries field. I want to get those entries, in the selected order, removing entries that don’t have an image asset assigned to the pageImage field.
Attempt 1
Gets correct entries but doesn’t maintain the selection order.

block.entries.relatedTo('and', {
  targetElement: craft.assets.kind('image'),
  field: 'pageImage'
})

Attempt 2
Same result as above. Correct entries but wrong order.
craft.entries.relatedTo('and', {
  sourceElement: block
}, {
  targetElement: craft.assets.kind('image'),
  field: 'pageImage'
})

Setting the field value in the first statement results in an empty result set.
Attempt 3
Seems to work but generates extra queries.
{% set ids = block.entries.ids() %}
{% set entries = craft.entries.id(ids).fixedOrder(ids).relatedTo({
  targetElement: craft.assets.kind('image'),
  field: 'pageImage'
}) %}


texts: Possibility to change where Image Transform folders are stored?

texts:
When using Inline Transforms in a template and also when the image transform is set in the Image Transforms section of the control panel then say my images folder is located at :

/images

And say I create an Image Transform called Square 100 [square100] (in either way mentioned above), the folder with the transformed images get saved to :

/images/_square100

Is there any way to prevent this because I'd like to be able to upload images to a certain folder but then have the URL not shown in any way so people can't find the original files. At the moment you can tell that they are in a folder called images and all you'd need to do to access them is to delete the /_square100 part from the URL.

I tried taking a look at the config variables but couldn't see anything pertaining to this sort of thing or perhaps I'm missing it somewhere?

Many thanks,

Mark


texts:
On my blog i need a load more button on the bottom of each section that simply loads more posts when clicked. Everything i look at people are using other javascript libraries. I just want to use ajax no external libraries

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

            {% for asset in entry.newsFeaturedImage %}

            {% endfor %}

            {% for category in categories %}

                    {{ category.title }}

            {% endfor %}

                {{entry.title}}

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

                Continue Reading

   {% endfor %}


texts:
I've been trying to follow the docs for creating a plugin migration (https://craftcms.com/docs/plugins/migrations) but any attempts to run yiic seem to die with:

CDbConnection failed to open the DB connection.

My Google-fu has not come up with any relevant answers. This is with Craft setup in a Vagrant box, if that makes a difference.


texts: Need difference sign up path for 2 groups

texts:
I see this thread about automatically activating/verify user accounts. However, I have 2 group of users, 1 group is open public which would like to have automatically activating/verify. The 2nd group is private, need activate email and verify. Should I write a plugin or just modify UsersService.php to split 2 directions on saveUser?

Thanks,
Angela


texts:
Just have a question on the way way to approach this: I have entire sections of a website that are per city and the number of cities might grow. I plan to create a city category and add the cities to it, then those cities appear when people add content. Then in the front-end, get those categories into a list and show them so a user can select them. Once selected it would write it to a cookie or localStorage.

Can I organise my content via url like /newyork/ and it would pick up the URL and fetch that data? Or when I visit the site and I have localStorage set, it would redirect me to /mychosencity/ ?

Just trying for the fastest, most efficient way both in terms of redirecting, but also implementing per city content on a whole site as well as in the templates.


texts: Edit multiple entries at once through the front-end

texts:
I am making/trying to make a reservation system with Craft. Logged-in members should be able to make a reservation for a hotel room on the front-end, and change it later.

I am keeping a stock for the available hotel rooms in entries. I have channel section called "rooms". In that section are 2 entries (= 2 different hotels). Every entry has information about the hotel (name, location,...) and has a matrix field with avaialble dates and stock for that date.

What I want to do: a logged-in user can choose a date and choose a number of rooms on that date. He should also fill in all his personal details. I was thinking about making entries of that info in a new channel (e.g. "reservations"). The hard part is: when a user selects a number of rooms, I want the stock of that night edited in the rooms entry. So if we heve 20 rooms available, and a member makes a reservation for 2, the stock should be set to 18.

I guess the first answer to this will be "write a plugin", but I have never written a plugin before, and I have no idea what's the best practice or where to start. Any ideas?


texts: How do you delete entries from a frontend form?

texts:
Part 2 of a 3 part question:

I am creating a proof of concept for a client in Craft where the client's customers can manage projects from the frontend of a Craft install.

I have a frontend form working correctly for creating a new project via it's own section. However the missing piece to the puzzle for full management is being able to delete an entry in the projects channel.

How do you delete entries from a front end form?


texts: Matrix entry causing last bootstrap column to be shunted down

texts:
I have a Matrix field which has one block type (1 asset field - I'm using a Matrix field as I'll be adding text fields later on to the same block). On the front end I am using Bootstrap's grid system to output the images in columns.

{% for block in entry.blockName %}

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

    {% endif %}

 {% endblock %}

For some reason when I test it the last column on the first row gets shunted down as shown in the image.

This only happens on the first row of items and if I test it out of the matrix field with placeholder images and static HTML it works fine. The CSS isn't changed for the last item so I can't seem to see what's causing this.

Anyone have any ideas?


texts: Cannot create entry when Entry Type has Title field hidden

texts:
I have created an Entry Type with the "Show the Title field" option not checked.

When creating an entry of this type, I am given a generic "Couldn't save entry" error message.

Looking in craft.log, I see the Title field is failing validation.

2015/08/18 18:07:29 [trace] [system.CModule] Loading "templates" application component
in /Users/Sites/craft-test/web/craft/app/etc/web/WebApp.php (584)
in /Users/Sites/craft-test/web/craft/app/services/EntriesService.php (157)
in /Users/Sites/craft-test/web/craft/app/controllers/EntriesController.php (450)
2015/08/18 18:07:29 [trace] [system.db.CDbConnection] Starting transaction
in /Users/Sites/craft-test/web/craft/app/services/EntriesService.php (160)
in /Users/Sites/craft-test/web/craft/app/controllers/EntriesController.php (450)
in /Users/Sites/craft-test/web/craft/app/etc/web/WebApp.php (784)
2015/08/18 18:07:29 [trace] [system.CModule] Loading "elements" application component
in /Users/Sites/craft-test/web/craft/app/etc/web/WebApp.php (584)
in /Users/Sites/craft-test/web/craft/app/services/EntriesService.php (176)
in /Users/Sites/craft-test/web/craft/app/controllers/EntriesController.php (450)
2015/08/18 18:07:29 [warning] [application] Craft\ContentModel->title failed validation: Title cannot be blank.
in /Users/Sites/craft-test/web/craft/app/models/BaseModel.php (510)
in /Users/Sites/craft-test/web/craft/app/models/ContentModel.php (89)
in /Users/Sites/craft-test/web/craft/app/services/ContentService.php (218)
2015/08/18 18:07:29 [trace] [system.db.CDbTransaction] Rolling back transaction
in /Users/Sites/craft-test/web/craft/app/services/EntriesService.php (183)
in /Users/Sites/craft-test/web/craft/app/controllers/EntriesController.php (450)
in /Users/Sites/craft-test/web/craft/app/etc/web/WebApp.php (784)

This is on Craft Pro 2.4.2684 on Apache/2.4.10 (Unix) PHP/5.5.24.

I've tried clearing caches to no avail, and confirmed that the same issue exists with newly created Entry types with the Title field hidden.


texts: Commerce 1: Different default order status based on product types

texts:
I want to assign different default order status based on product types.  Is this possible?

What I need to achieve is to send different email notifications based on product types.  Can this be configured or do I need to add logic to and customize the email templates?


texts:
This seems like it should be simple to find, but where does Craft store the status of entries (lightswitch for enabled/disabled)?  It doesn't seem to be a column in the entries table, and I can't figure out how the other tables are linked to the entry number.

Background: In a plug-in, I'm trying to filter a query to exclude only those that are disabled.


texts:
I created Search that uses entry slug, but it fails if the slug has more than one dash "-" in it. Has anyone come across this and/or have any ideas for getting around it?

I need to use the slug because they are unique within a section.


texts:
I have a Structure area where there will be 20-24 top level pages for degrees, each with similar (but different) subpages…

Masters in Accountancy

Courses by Year
Degree Requirements
…etc. x12 or so.

Masters in Business Administration

Courses by Semester
Degree Requirements
…etc. x12 or so.

…etc.

It would be super ideal (and save a lot of time) is if I could setup the tree for just on of the degrees, then duplicate it 20 times and use it as a starting point for the others degrees. Has anybody managed to pull something like this off? Guessing I'd have to do it directly in the DB?

(I should mention that because of the variety/flexibility in content around each degree, having a degree channel isn't a good fit for this case. In total, it's much more like a docs section.)


texts: Using services/records etc in migrations

texts:
The database migrations documentation does say:

  Please note that we do not recommend using records directly within a migration

Are there technical reasons for this recommendation, or is it something you'd just rather not support? I don't mind if I'm on my own as far as support goes, but it seems like I might be able to use migrations to deploy schema changes across environments if I was careful?

Of course this would be for private, site-specific plugins, not anything that was going to be publicly released, so I don't think the issue Brandon highlighted here would necessarily apply.

I have successfully created a new tag group using the following:

public function safeUp()
{
    $tagGroup         = new TagGroupModel();
    $tagGroup->name   = Craft::t('Tag Group');
    $tagGroup->handle = 'tagGroup';

    craft()->tags->saveTagGroup($tagGroup);
}

But obviously this is quite a simple example, and a migration that added fields, sections and entry types (like the InstallService does) would be more complicated and should probably check each record was saved properly before continuing with the next bit.

Are all of Craft's services available while a migration is being run?


texts: Guest Entries plugin - set parent entry if using section

texts: As the title suggests, is it possible to pass an entry ID in order to set a parent for the submitted entry?


texts: I am using the import plugin by Bob Oldehampsink to load entries. I have 47 fields that I'm uploading. The import shows as uploaded successfully in the admin and the file is my assets but the entries do not load.  If I reduce the number of fields the entry appears as it should. I can't find any errors related to the plugin. Any ideas as to what might be going wrong?


texts: Craft 3 RC Upgrade killed the WYSIWYG Editor

texts:
I just finished upgrading to Craft 3 RC and all text on the site is gone. The WYSIWYG Editor has been replaced with this message:

Unable to find component class 'craft\fields\RichText'.

What can I do?


texts: Including CSS/JS assets from template folder

texts:
I cannot seem to include my CSS and JS files from the craft/templates/ directory into my website.

I've looked at this answer - Serving CSS files from template folder - and it tells me I simply need to have a styles/styles.css folder and I use {% includeCssFile "/styles/styles.css" %} and it should work. But it doesn't. I have a similar problem with the javascript includes. {% includeJsFile "js/lodash.min.js" %} command works, but once I navigate to any other URL, it tries to include the file http://localhost/craft/news/2016/js/lodash.min.js.

My folder structure looks like this:

I'm trying to keep all my assets in this craft/templates/ folder because I created a git repo in the craft main folder.


texts:
I'm working on a new website for my student radio station but I've stumbled into a few key bugs which are stopping us from advertising the new site.

It's live right now over on Stormfm.com, you'll be able to see the problems for yourselves there.

The up coming shows section is supposed to display the next 3 shows, however there's a bug with it's limit, to get the section to display at least 3 shows I had to raise the limit to 30, this then means up to 30 shows display. I've copied the code below.

{% for entry in craft.entries.section('shows').order('showTime').limit(30)
    if entry.showDay.contains('now'|date('N')) and entry.showTime > 'now'|date('H:i') %}

{{ entry.showTime }} - {{ entry.showLength }}

{{ entry.Title }}

With {{ entry.hostname.first().title }}

&gt;

{% endfor %}

Also I want to display what the current show on air is, originally I was going to use a similar code to the above, limit it to 1 and have it minus an hour but I can't seem to work out how to do that. For the short term I can flip the greater than to less than, however this then displays only the closest show and I can't else out into a default display if nothing is currently timetabled as on air.

I hope this all makes sense and would appreciate any help you might be able to provide!

Tom


texts: Why is the parent slug showing up in the child slug in a structure?

texts:
Basic info

I have a structure with a handle about.
The Entry URI format is about/{slug}. EDIT: also tried it with just {{ slug }}
I created a child page called "Privacy Policy" with the slug privacy-policy. It has a parent of the page "About SAFS" (slug about-safs).
I can only access the page at mysite.com/about/about-safsprivacy-policy. If I go to mysite.com/about/privacy-policy, I get a 404.
If I include {{ entry.slug }} in the template, it prints privacy-policy.

Edit: This is my Settings > Sections > About after changing slug to just { slug }

My question

Why is the parent's slug being inserted into the URI, and how do I change that?

Possibly relevant info

All the top-level pages in the About structure display on a single page, using this template for the entries:

{% if entry.level == 1 %}
  {% redirect siteUrl|trim ~ 'about#' ~ entry.slug %}
{% else %}

  {# normal template #}

For the About index template, I include:

{% set link = siteUrl ~ "/about" %}

EDIT: I also tried removing the redirect from the template, and I'm getting the same routing issue for the privacy-policy entry.


texts:
I would like to override or include a custom redactor.css file so that I can match the typography of the rich text editor contents with the site's stylesheet.

The path to redactor.css is hard-coded into the application (craft/app/fieldtypes/RichTextFieldType.php - line 281), and obviously I don't want to change this file or the redactor.css file.

Is there at least a way to inject a custom css file into the admin pages so that the core/base styles can be overridden?

UPDATE: Both plugin solutions below worked, but because craft includes redactor.css after the plugin's css include is inserted, the trick is to make your css selectors more specific, i.e.:

.redactor_.redactor_editor h1 { font-size: 48px !important; }


texts: Radio button field no setting default checked

texts:
I have two radio buttons on a field. I check one of the options as default so it's checked automatically, but when I visit the entry it's on, both of them are unchecked.

I've tried deleting and remaking and it still doesn't select default.

Has anyone had this issue?


texts: Posting from controller to controllers with parameter gives an error

texts:
public function actionMyPluginActionControllerIndex(){
    $this->myPluginActionController($myVariable);
    return something;
}

public function actionMyPluginActionController($myVariable)
{
    return something;
}

This is giving me the error:

{"error": "Missing required parameters": myVariable"}

I did exactly this with a craft 2 plugin, but somehow this doesn's seems to work in craft 3 anymore, what am i missing?

any help will be appreciated :)


texts: Craft 3 - Recommended development environment for Windows?

texts:
I was wondering what people who are developing on Windows 10 are using as webserver environment in 2018? I have had ok results previously using ampps, but I'm having a lot of problems with Craft 3 as of lately. With 500 internal server errors etc. Also, I'm developing on several PCs, syncing the projects with Git.
A friend of mine recommended Laravel Valet and homestead, but he's on Mac. And installation on Windows seems to be a lot trickier. I've tried Mamp too, but have really bad experience with that one.


texts: Craft causing Apache2 to max out memory and swap

texts:
Background: Our Craft 2 site has been working for years. Now I want to upgrade to Craft 3. On a test machine, I have been having problems with the upgrade process. I have tried 3 classes of things:

Install Craft 3 from scratch. This is working, but I'd really like to bring the old database along.
Install Craft 3 and the old database, and try to do the upgrade.
Just duplicate the old Craft 2 system with the old database, to get something to work.

The problem: Anything I do with the old database (#2 or #3, above) is likely to cause Apache2 to go berserk, using up all memory and swap and bringing the system to a nearly complete halt. Not every page does this, but, for example, the CP Entries page does this when it attempts to list entries.

I haven't been able find any errors in logs, though I'm not especially adept at that.  Any thoughts?


texts:
Quick question: Is it possible to access the browser's local storage in Twig?

In JavaScript you would do something like:

localStorage.getItem('myItem');

Thanks!


texts: When developing plugins where should you store values that might not strictly be settings?

texts:
For instance I'm writing a plugin which is going to be periodically pulling stuff from Twitter, so I'd like to keep a hold of when the plugin was last run and maybe some Ids relevant to Twitter that sort of thing.

I know there is the settings array which you use for user defined values, should I also use it for other stuff that the user can't change, or is there a more sensible place to stick those?


texts: What are the best practices for using the {% cache %} tag?

texts:
I started using the {% cache %} tag and would like to know what the best practices are:

.

Regarding performance:

For example does it make sense..

..to cache the whole template, or is it better to enclose each query separately?
..to combine the cache-tag with other supported caches?
..to cache non-dynamic content?

.

Regarding development:

I saw the tip to use: {% cache unless craft.config.devMode %}. Is there anything else to consider during development?


texts: Reverse relationships with entries and users

texts:
I have a relationship between users and 'locations', and I'm using the code below to output some markers for a map.

This all works fine except for two things:

I'm repeating a couple of 'for' loops. When I try not to repeat
them, the 'markers' and 'markerInfo' return 'undefined'.
Within markerInfo, I'd like to list the names (e.g. 'user.firstName') of the users related to that location, but when I try, I get a list of ALL users that have a relationship with ANY location.

In plain language, what I'm trying to do is:

Find me all the users who are part of the 'family' group.
Find me all the locations which are related to those users and plot each
one (but only once for each location).
For each location, give me a list of the users that have a relationship with it.

--

My source elements are entries in the section 'locations', with the
field 'relatedPeople'.
My target elements are 'users' (from the group
'family').

How can I make this more performant (not repeat things), and get a list of users per location within 'markerInfo'?

{% set people = craft.users.group('family') %}

{% set markers %}
    {%- for person in people.all() -%}
        {% set relatedPlaces = craft.entries.section('locations').relatedTo({
            targetElement: person,
            field: 'relatedPeople'
        }) %}
        {%- for place in relatedPlaces.all() -%}
        ['{{ place.location.address }}', {{ place.location.lat }},{{ place.location.lng }}],
        {%- endfor -%}
    {%- endfor -%}
{% endset %}

{% set markerInfo %}
    {%- for person in people.all() -%}
        {% set relatedPlaces = craft.entries.section('locations').relatedTo({
            targetElement: person,
            field: 'relatedPeople'
        }) %}
        {%- for place in relatedPlaces.all() -%}
        ['
' + '
{{ place.title|e('js') }}
' + '{% if place.startDate|length %}{{ place.startDate | date('M Y') }}{% endif %}{% if place.startDate|length and place.finishDate|length%} to {% endif %}{% if place.finishDate|length %}{{ place.finishDate | date('M Y') }}{% endif %}' + '
'],
        {%- endfor -%}
    {%- endfor -%}
{% endset %}


texts: project.yaml stopped syncing changes in the staging process

texts:
I'am a bit helpless at the moment, because my project staging workflow using project.yaml stopped working and a) I don't know why and b) have no clue if I can solve it.

Problem:
Until some days ago my staging worked like that:

1.) We are 3 developers working in our office, sharing the craft db on a central mysql. Dev User files were synced using an internal dropbox. When we wanted to bring our Craft DB changes to the QS machine, we enabled projectConfig, craft wrote a project.yaml, we pushed it to our repo and the QS installation of Craft took the project yaml and imported them. This worked great.

2.) Now this stopped working. We had a couple of new globals, fields, etc.  but they were not taken over to QS

3.) When I look into my database I can see the fields, globals etc. in the corresponding tables (looking good). But when I look at the config column in the info table, the settings there do not match my database. e.g. I found the same fields and fieldgroups with different UIDs duplicated in there. So I know there is something wrong here, but I do not know what. And I also know that my project.yaml is the same as my config column so maybe this is the reason, why my QS installation does not take over any recent changes to my project db structure.

So my questions are rather general:
- Can this problem be solved?
- Can the config column in the info be rewritten according to the real existing structure on the source Craft installation?
- Can a broken Craft database in some way be repaired?

My problem is that we already have some (not too much tough) customer content in the QS system and unless I want to manually recreate the Craft installation I would definitely prefer a way of repairing it.

Thanks,
Matthias


texts: How can I get the same random array key?

texts:
I am creating a mad libs type of global. My global set is actually called madLibs.

Within that set, is a matrix field - that can have unlimited blocks. Each block only has two fields. actualRole and pretendRole.

What I have is working - but sometimes I might get the actualRole from one matrix, and the pretendRole from another. Ideally, I'd like to get the same fields from the same random matrix.

{# Get all of the matrix blocks for the global set #}
{% set globalSet = craft.globals.getSetByHandle('madLibs') %}

{% if globalSet|length %}

    {# Find out how many matrix blocks exist #}
    {% set madLibsCount = globalSet.madLib|length %} // 2

    {# Generate a random array key. Remember array is zero based #}
    {% set range = range(0, (madLibsCount - 1)) %}

{{ globalSet.madLib[random(range)].actualRole }}

{{ globalSet.madLib[random(range)].pretendRole }}

{% endif %}

Sometimes, this is happening:

{{ globalSet.madLib[0].actualRole }}

{{ globalSet.madLib[1].pretendRole }}

I would really like to have this each time:

{{ globalSet.madLib[0].actualRole }}

{{ globalSet.madLib[0].pretendRole }}

Thank you for any suggestions!


texts: When Asset is Located in Root of Asset Volume - asset.getPath() Does Not Return the Volume as Part of the File Path

texts:
Context
Asset Volume: staff
(I'm using an S3 bucket as the source type)
Image location: staff/john-smith.jpg
Version: Craft 2.7.8
Results
I expected that this query {{ staff.portrait[0].getPath() }} would output {{BaseUrl}}/staff/john-smith instead the query outputs {{BaseUrl}}/john-smith.jpg
It works on subfolders
If the staff asset volume contains a subfolder with john-smith.jpg (ex:(staff/portraits/john-smith.jpg)) then {{ staff.portrait[0].getPath() }} will return {{BaseUrl}}/staff/portrait/john-smith.jpg


texts:
Craft CMS 3.3.15

PHP 7.1.3

MySQL 5.5.42

I have a structure with 360 entries.

Right now in the CP it takes 3.5 - 10 seconds to load the first 50.
And another 3.5 - 10 seconds for every additional 50 when scrolling.

From what I can see in the yii profiler, there are a LOT of queries, and many of them takes around 100 - 150 ms.

These queries are basically a COUNT(...) query, 30-50 of them per request, each taking 100+ ms.

Example:

SELECT COUNT(*)
FROM (SELECT `elements`.`id` AS `elementsId`, `elements_sites`.`id`
AS `elementsSitesId`, `content`.`id` AS `contentId`
FROM `craft_elements` `elements` INNER JOIN `craft_entries` `entries`
ON `entries`.`id` = `elements`.`id` INNER JOIN `craft_elements_sites` `elements_sites` ON `elements_sites`.`elementId` = `elements`.`id`
INNER JOIN `craft_content` `content`
ON (`content`.`elementId` = `elements`.`id`)
AND (`content`.`siteId` = `elements_sites`.`siteId`)
INNER JOIN `craft_structureelements` `structureelements`
ON (`structureelements`.`elementId` = `elements`.`id`)
AND (`structureelements`.`structureId`=1)
WHERE (`elements_sites`.`siteId`='1')
AND (`elements`.`archived`=FALSE)
AND (((`elements`.`enabled`=TRUE)
AND (`elements_sites`.`enabled`=TRUE))
AND (`entries`.`postDate` <= '2019-11-15 12:15:04')
AND ((`entries`.`expiryDate` IS NULL)
OR (`entries`.`expiryDate` > '2019-11-15 12:15:04')))
AND (`elements`.`dateDeleted` IS NULL)
AND (`elements_sites`.`enabled`=TRUE)
AND ((`structureelements`.`lft` > '537')
AND (`structureelements`.`rgt` < '538')
AND (`structureelements`.`root`='1'))
AND (`elements`.`draftId` IS NULL)
AND (`elements`.`revisionId` IS NULL)) `subquery`
INNER JOIN `craft_entries` `entries`
ON `entries`.`id` = `subquery`.`elementsId`
INNER JOIN `craft_elements` `elements`
ON `elements`.`id` = `subquery`.`elementsId`
INNER JOIN `craft_elements_sites` `elements_sites`
ON `elements_sites`.`id` = `subquery`.`elementsSitesId`
INNER JOIN `craft_content` `content`
ON `content`.`id` = `subquery`.`contentId`
INNER JOIN `craft_structureelements` `structureelements`
ON (`structureelements`.`elementId` = `subquery`.`elementsId`)
AND (`structureelements`.`structureId`=1)

As you can see from the profiler, there is a lot of them going off:

I dont know if it has something to do with this beeing a structure, but the other channels are fast and problem free.

Right now the client waits for 10-20 seconds each time they edit or add entries to the structure, and that is understandable frustrating.

Is there any kind of index I can set to speed this up?


texts: How difficult would it be to replicate the control panel search on the frontend of a Craft site? I currently have a standard Craft search as shown in the documentation but it's a little slow as I have a large amount of entries.


texts: Counting section handle in TWIG with weighted search plugin

texts:
I am using the weighted search plugin to inplement a search functionality in my site. It works as it should but I am looking for a way to tell how much results were found of each type. Where type for example is blog and mapMarker.

This is how the search bar gets its results:

{% set query = craft.request.getParam('query') %}
{% set typesToSearch = ['mapMarker', 'blog'] %} <- This is what I want to count
{% set results = craft.weightedSearch.substringSearch(query, typesToSearch) %}

And then I have a block of code that shows all my results, and this is the place where I want to tell the end user how much results is from each typesToSearch.

How do I implement such feature in this code? :

{% for searchResult in results %}
    {{ searchResult.entry.type|length }} <- I tried this but this doesn't work.
{% endfor %}


texts: Nginx: index.php URLs still being served alongside pretty URLs

texts:
For whatever reason https://domain.com/index.php?p=path/to/whatever and https://domain.com/index.php/to/whatever both still work and are not being redirected or rewritten to https://domain.com/path/to/whatever/.

We are enabling these in our CraftCMS configuration:

'omitScriptNameInUrls' => true,
'usePathInfo' => true

But they have not rectified the issue. Does anyone have a solution to this? Here are the important parts of our current Nginx.conf. I appreciate any help I can get on this.

location ~ /.well-known {
    allow all;
}

location / {
    try_files $uri $uri/ @rewrites;
}

location @rewrites {
    rewrite ^(.*) /index.php?p=$1 last;
}

location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt  { access_log off; log_not_found off; }

error_log  /var/log/nginx/error_craft_https.log error;

error_page 404 /index.php;

location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass unix:/var/run/php-fpm.sock;
    fastcgi_index index.php;
    include fastcgi.conf;
    include fastcgi_params;
}

location ~* (?:\.(?:bak|config|sql|fla|psd|ini|log|sh|inc|swp|dist)|~)$ {
    deny all;
}

location ~* \.(?:manifest|appcache|html?|json|xml)$ {
    try_files $uri /index.php?$query_string;
    expires -1;
    access_log /var/log/nginx/access.log;
}

location ~* \.(?:rss|atom)$ {
    try_files $uri /index.php?$query_string;
    expires 1h;
    add_header Cache-Control "public";
}

location ~* \.(?:jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm|h$
    try_files $uri /index.php?$query_string;
    expires 1M;
    add_header Cache-Control "public";
}

location ~* \.(?:css|js)$ {
    try_files $uri /index.php?$query_string;
    expires 1y;
    add_header Cache-Control "public";
}

location ~* \.(?:ttf|ttc|otf|eot|woff)$ {
    try_files $uri /index.php?$query_string;
    expires 1M;
    add_header Cache-Control "public";
}


texts:
Super simple problem. I'm on a news item page (not a paginated overview page) and want to show a link to the next news item in the Channel; So I can't understand why this is outputting nothing at all:

{{ craft.entries.section('news').nextSiblingOf(entry).title }}

I can't seem to get either of the SiblingOf properties to do anything. What simple mistake am I making?

(I have also tried the following to no avail...)

{{ craft.entries.section('news').nextSiblingOf(entry).first().title }}


texts: Listing Sub Categories of a Category related to an entry

texts:
I've been scratching my head over this for awhile and I can't seem to solve it.

What I'm after is the following.

I have various categories with numerous sub categories. I'd like to be able to display the sub categories of a category that is related to an entry which is how my navigation  is set up.

The code at the moment look like this...

{% set entries = craft.entries.find({ section: 'landingPages' }) %}
   {% for entry in entries %}

{{ entry.title }}

           {% set drop = entry.category.find({ }) %}

               {% for category in drop %}

{{ category.title }}

               {% endfor %}

    {% endfor %}

At the moment it's just generating the category which is selected within the entry, i've tried various variations on descendant commands and nothing seems to work.

Any help would be greatly appreciated.


texts: Logging in Every Minute - Craft Admin Sessions (on Heroku)

texts:
I have Craft installed on Heroku using Memcached for sessions. Craft is kicking me out of the admin area every minute or two. It's deriving me crazy. I've also set the user session duration in general.php:

'userSessionDuration' => 'P2W'

Still kicking me out.

If I set it to dev mode, I get this error:

Undefined variable: _SESSION

I know that the session does work, because I can login. I can also check the currentUser variable and see people signed in. The thing is, it isn't lasting long and makes the admin area nearly unusable.

My composer file is really simple. Nothing complicated.

{
  "require": {
    "ext-mbstring": "*",
    "ext-imagick": "*"
  },
  "require-production": {
    "ext-memcached": "*"
  }
}

EDIT:

Also, here are my Memcached settings in the /public/.user.ini file (as recommended by Heroku):

session.save_handler=memcached
memcached.sess_binary=1
session.save_path="PERSISTENT=myapp_session ${MEMCACHIER_SERVERS}"
memcached.sess_sasl_username=${MEMCACHIER_USERNAME}
memcached.sess_sasl_password=${MEMCACHIER_PASSWORD}

SOLUTION:

For anyone interested, the Memcached extension in my composer.json file wasn't being picked up by Heroku on deploy. So I updated my composer.json file like this:

{
  "require": {
    "ext-mbstring": "*",
    "ext-imagick": "*",
    "ext-memcached": "*"
  }
}

Then ran composer update to update the composer.lock file.

When deploying to Heroku, the composer.lock file is very similar to the Gemfile.lock in Rails - telling Heroku exactly what to install with the deployment. Now the Memcached extension is being installed by Heroku and my session problem has been solved.


texts: Plugin Controller actions for entering data and redisplaying form or redirecting

texts:
I'm getting confused with how to submit forms to a plugin controller as shown briefly in the docs.

I'm making a multi-page form, which saves the data on each page to the session, sending it elsewhere at the end of the process. None of the data is related to things (Entries, etc) in Craft.

But I don't understand how to do the:

Display form
POST form
Either:

Validation passes, so save the data and redirect to the next page
Or, fail validation and display the same form again

Let's say the first page asks for firstname and surname, and the second for date of birth. I have a model per form page, for validation, so there's plugins/myform/models/myForm_NameModel.php:

<?php
namespace Craft;

class MyForm_NameModel extends BaseModel
{
    protected function defineAttributes()
    {
        return array(
            'firstname' => array(AttributeType::Name, 'maxLength' => 100),
            'surname' => array(AttributeType::Name, 'maxLength' => 100),
        );
    }
}

And I'll have a similar model for the form on the date of birth page.

Then I have plugins/myform/controllers/myForm_FormController.php

<?php
namespace Craft;

class MyForm_FormController extends BaseController
{
    protected $allowAnonymous = true;

    // Display name form.
    public function actionName()
    {
        $this->renderTemplate('myForm/forms/name');
    }

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

        $post = craft()->request->getPost();
        $nameModel = MyForm_NameModel::populateModel($post);

        if ($nameModel->validate()) {
            // TODO: Store in session.
            $this->redirectToPostedUrl();
        }
        else
        {
            craft()->userSession->setError('Error!');
            craft()->urlManager->setRouteVariables(array(
                'nameModel' => $nameModel
            ));
        }
    }

    // Display date of birth form.
    public function actionDob()
    {
        $this->renderTemplate('myForm/forms/dob');
    }
}

And in plugins/myform/templates/forms/name.html:

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

First name: <input type="text" name="firstname" value="{% if nameModel is defined %}{{ nameModel.firstname }}{% endif %}">

Surname: <input type="text" name="surname" value="{% if nameModel is defined %}{{ nameModel.surname }}{% endif %}">

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

I'm missing something at the moment because all I get is the name form, and submitting it simply refreshes the page; no errors, no submitted values displayed. I think I'm confused by the action and redirect in the form template, and exactly what the controller actions should be doing.

I'm also not sure if using AttributeType::foo is correct when defining these models, seeing as they're not things that will be saved in the database?


texts:
I have a notes field shown on the cart page. When a customer fills the field out and clicks "Checkout" the contents are not saved. Same goes for Quantity or other custom fields. If "Update Cart" is chosen the data is saved. Is there any way to prevent the checkout from continuing if these fields have content? Or would this need to be done via something like javascript validation?
<form method="POST">
    <input type="hidden" name="action" value="commerce/cart/update-cart">
    <input type="hidden" name="cartUpdatedNotice" value="The cart was updated.">
    {{ redirectInput('shop/cart') }}
    {{ csrfInput() }}
    ...
   <textarea type="text" name="lineItems[{{ item.id }}][note]" value="{{ item.note }}">{% if item.note %}{{ item.note }}{% else %}{% endif %} </textarea>


texts:
Is it possible to change the store currency from a plugin?

I know about COMMERCE_PAYMENT_CURRENCY, but I'm not sure how to set that one early enough.

It also seems like it doesn't affect the displayed price. Do I need to use the commerceCurrency in combination with the cart.paymentCurrency everywhere I display a price?


texts: Customize the field.html file for Sprout Forms

texts:
I've set up a Spout Form, and I can customize the form.html file after copying it and moving it to my own templates/_form/formHandle folder. But when I want to customize the field.html file (I do the exact same thing as with the form.html file) nothing happens. Does anyone know what I'm doing wrong? I only want to add some custom classes, nothing fancy :-).

Thanks!


texts: Craft Commerce ajax add to cart, missing information

texts:
I add items to my cart using ajax, following the code from this post

Update Commerce Cart using Ajax

But there are some things missing in the cart object returned on success, they are :

The URL of the page of the product added
The images, and all the fields from the product added
The name of the variant of the product added

Are these somewhere in the object returned ? Otherwise, how could I retrieve them ?


texts: How to create custom option/action for backend entry lists

texts:
Please excuse me for the title.. I have no idea how to describe my problem better - if someone knows a better description for this question feel free to edit it.

I made a screenshot to clarify what I want to know.. Is it somehow possible to hook a custom option there?

I made an excel export for our customer and I would like to add an "export to excel" button there that sends an ajax request to my controller. Could you please explain me in detail how to do this?

Thank you very much

Edit
So thanks to your answers I created this test (just to see if I can add something)

<?php

namespace Craft;

class SRExcelExport_ExportElementAction extends BaseElementAction
{
    /**
     * Get element action name.
     *
     * @return string
     */
    public function getName()
    {
        return Craft::t('Export Files');
    }

    public function isDestructive()
    {
        return true;
    }

    public function performAction(ElementCriteriaModel $criteria)
    {
        // Remove all the ingredients from the selected elements
        $elements = $criteria->find();

        foreach ($elements as $element)
        {
            //do something
        }

        // Success!
        $this->setMessage(Craft::t('success'));
        return true;
    }

    public function getTriggerHtml()
    {
        $js = 'new Craft.ElementActionTrigger({' .
            'handle: '.JsonHelper::encode($this->getClassHandle()).', ' .
            'batch: true, ' .
            'validateSelection: function($selectedElements){ return true; }, ' .
            'activate: function($selectedElements){ alert("Made you click"); }' .
            '});';

        craft()->templates->includeJs($js);
    }
}

With the Plugin Handle SRExcelExport with the folder structure
srexcelexport
--elementactions
-----SRExcelExport_ExportElementAction.php

But nothing happens, the file is ignored, even a die() in the constructor does nothing. Do I need to do something to "call" the class myself or is there just a stupid error I made? I bet its just an obvious minor error I can't see right now