Menu
  • HOME
  • TAGS

Yii2 - Make Form Validator For URL Type To Skip “http://” in the start

Tag: yii2

This is how my yii2 model looks like:-

namespace app\models;

use Yii;
use yii\base\Model;


class UrlForm extends Model
{
    public $url;
    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [            
            [['url'], 'required'],
            ['url', 'url'],            
        ];
    }

}

I want it to approve the url if use has not written 'http://' in the start.

Example:-

stackoverflow.com should work fine.

http://stackoverflow.com should work fine.

Current Status:-

stackoverflow.com not accepted.

http://stackoverflow.com is accepted..

Best How To :

You just need to add 'defaultScheme' => 'http' to your validation rule, so

public function rules()
    {
        return [            
            [['url'], 'required'],
            ['url', 'url', 'defaultScheme' => 'http'],            
        ];
    }

yii2 Pjax + java script prompt

yii2

instead of Html::a() use Html::button()where button id = some_item_id and then write this JS code $('.buttons_class').click(function(){ var selection; do{ selection = parseInt(window.prompt("Please enter a number from 1 to 100", ""), 10); } while(isNaN(selection)); if(!isNaN(selection)) { $.post("some",{id:45,prompt_value:selection}, function(response) { console.log(response); $.pjax.reload({container:'#pjax-orders_table'}); }); } }) ...

Yii2: Passing index page to breadcrumbs in view and update actions

gridview,yii2,breadcrumbs,yii2-advanced-app

It seems there is no LinkPager magic to do this by now but I managed to find a solution avoiding controller tweaking. Just edit view.php/update.php and add before breadcrumbs stuff: parse_str(parse_url(Yii::$app->request->referrer, PHP_URL_QUERY), $params); Then in breadcrumbs: $this->params['breadcrumbs'][] = ['label' => 'myLabel', 'url' => ['index', 'page' => isset($params['page']) ? $params['page'] :...

Yii2 - check if the user is logged in view

yii,yii2

In Yii2 the correct syntax is Yii::$app->user->getIsGuest(); or Yii::$app->user->isGuest; Look at the documentation for more details: http://www.yiiframework.com/doc-2.0/yii-web-user.html Hope it helps....

yii2 disable the rules if a checkbox is selected

yii2,rules,active-form

You could define the rules that way (using when): public function rules() { return [ ['cancelled', 'boolean'], ['checkNumber', 'required'], ['payee', 'required', 'when' => function ($model) {return !$model->cancelled;}], ['particulars', 'required', 'when' => function ($model) {return !$model->cancelled;}], ]; } You may want to add whenClient as well to let the browser check...

How to get all ActiveRecord objects in Yii2?

php,yii,yii2

If you are getting your objects, you are still able to iterate through them. Try to make following simple change (look at "+=" change to "0"): public function getAllCategories(){ $categoriesList = array(); $categories = Category::find()->orderBy("id")->all(); foreach ($categories as $category){ $categoriesList[] = $category->title; } return $categoriesList; } Here is some reference...

How to log in user to my web application when he click on some link in his email

php,mysql,email,login,yii2

I'd probably recommend login tokens (preferably one-time use only) generated when you create the link created as a long hash (see sha256/sha512/GUIDs). You could (and should) also add validity dates to those tokens if need-be to ensure that someone doesn't reuse them and invalidate them on login or logout from...

How do I get a list of key, value pairs from the database for a select list in Yii?

php,yii2

Get the list of values, perhaps in the controller $campaigns = Campaign::find()->select('name')->indexBy('id')->column(); Display the list <?= $form->field($model, 'campaign_id')->dropDownList($campaigns) ?> ...

Run string as static class function in Yii2

php,yii,yii2

eval() can be used to execute php code in a string. Eval() returns a value if the executed code returns a value. So, in the case above : $func = "\app\models\AddrModel::getText('A_00001724');"; $value = eval('return ' . $func); print_r($value); ...

Add comment to SQL table

migration,yii2

Currently there is no such functionality in Yii 2 migrations. You have to write it in plain SQL via execute() method: $this->execute("ALTER TABLE my_table COMMENT 'Hello World'"); ...

Order By count(*) from other table in yii 2

php,mysql,activerecord,order,yii2

First you should create ActiveRecord class for video and likes tables to make things easier. The aim is to create the two following classes class Video extends \yii\db\ActiveRecord and class Likes extends \yii\db\ActiveRecord. To do it easily, you should look at gii utility which will do it for you (available...

Yii2 client side validation for dynamically added multiple inputs

yii2

After adding dynamic input using jQuery use below code to validate jQuery('#form-id').yiiActiveForm("add", { "id": "input-id", "name": "input-name", "container": "#container-id or unique .container-class of this input", "input": "#input-id or unique .input-class", "validate": function (attribute, value, messages, deferred, $form) { yii.validation.required(value, messages, {"message": "Validation Message Here"}); } } ); ...

Spanish location for yii2-date-picker-widget

datepicker,yii2

Your translation doesn't work because of wrong syntax, You should move Your language param from 'clientOptions' to top level array: <?= $form->field($model, 'alta')->widget( DatePicker::className(), [ 'inline' => false, 'language' => 'es', 'clientOptions' => [ 'format' => 'yyyy-mm-dd', 'weekStart' => 1, 'todayBtn' => 'linked', 'clearBtn' => true, 'autoclose' => true, 'todayHighlight'...

“Undefined variable” error, when rendering data in a view

php,view,yii2

You are passing the $data to create.php.Render the same from your create.php to make it available in your form.php. In your create.php <?= $this->render('_form', [ 'model' => $model, 'data' => $data , ]) ?> ...

Yii2 required validation on update

php,validation,yii2

ActiveRecord does not set scenario automaticaly when you update or create items. You must override update() method in your model and set scenario that you need. E.g. in your case public function update($runValidation = true, $attributeNames = null) { $this->scenario = 'update'; return parent::update($runValidation, $attributeNames); } Also you can set...

Yii 2: Using module's image declared as asset

php,yii2,yii-modules

As soon as you register the AssetBundle it is possible to fetch its baseUrl. In the rest of the view you can then use that to get to your images: $assets = MyAssetBundle::register($this); $imagePath = $assets->baseUrl . '/img/delete-icon.png'; $this->registerJS(<<<JS $("#delete").attr("src", "$imagePath"); JS ); ...

how to run yii form validation before my js file

javascript,jquery,yii2

You can use afterValidateAttribute. Try following: $position = View::POS_END; $validatejs = <<< JS $('#formID').on('afterValidateAttribute', function(event, attribute, messages) { if(messages.length == 0){ // No errors ... } }); JS; $this->registerJs($validatejs, $position); Updated: $('#formID').on('beforeValidate', function (event, messages, deferreds) { // called when the validation is triggered by submitting the form // return...

datepicker yii2 kartik wrong format

yii2,datetimepicker

You are using php's data formatting characters. See plugin documentaion about correct date formatting. In your case instead of d-M-Y g:i A it should be dd-M-yyyy H:ii P

Yii2 - mailer - send message to email rows in database

arrays,string,yii2,send,mailer

To get array of email with numeric indexes call queryAll() method with $fetchMode parameter \PDO::FETCH_COLUMN, and then just pass returned array to mailer's setTo() method. Like this $enderecos = $command->queryAll(\PDO::FETCH_COLUMN); //$enviar = json_encode($enderecos); <- this line no needed Yii::$app->mailer->compose() ->setFrom('[email protected]') ->setTo($enderecos) //you pass an array of email addresses ->setSubject('Oferta de...

How to update/insert array of values to database using Yii2 ( many values for one id that repeats )

php,mysql,yii2

I see two ways: first one is to create 'batchUpdate' method - but it will not be the same for different database types. So I will describe second one, as it seems to be pretty simple. 1. Remove all user relations: UserCpv::deleteAll(['user_id' => $userId]); 2. Create array for batchInsert method:...

yii2 - Why use yii\helpers\Html instead of just typing

html,yii2

It's really up to you. But using the framework helpers, widgets and coding styles, you can keep code consistency, reduce errors, bugs and even lower the security risks. Using your example. Imagine that $this->title is set to the name of a user in your main layout file: <?php $this->title =...

Data is not getting from model - Yii2

yii2

You always need to have some validation rule for attribute you want to save via mass assignment. E.g. just add one more rule and your middlename will be saved: public function rules() { return [ [['firstname', 'lastname'], 'required'], ['middlename', 'string'], // rule for middlename ]; } ...

Setting ID attribute of input field when using ActiveField in Yii2?

yii,yii2

Just add id key to options array you've already passed in to hiddenInput method $form->field($model, 'some_id')->hiddenInput(['value' => $some_id, 'id' => 'some_id'])->label(false); ...

Button not working on Pjax Reload

javascript,php,jquery,yii2,pjax

I figured it out. Here's my updated code: HTML <div class="table-responsive all"> <?php \yii\widgets\Pjax::begin(['id' => 'reimbursement_grid']); ?> <?php echo $this->render('_index', ['dataProvider' => $dataProvider ]); ?> <?php \yii\widgets\Pjax::end(); ?> </div> JAVASCRIPT <script> //$(document).ready(function(){ $(document).on('ready pjax:success', function(){ $('input[type=radio]').prop('name', 'filter'); var showAll = $('input[name=filter]').val(); if(showAll == "Show All") {...

Multiple alias in one account

yii2,yii2-advanced-app,fortrabbit

your setup is possible at fortrabbit. Just put both folders in your git repo and push to forrabbit. After that you can route the subdomains (www., admin.) to the subfolders (frontend/www, backend/www). If your project requires a composer install during the deploy process it will not work our of the...

Create Url in Yii2

yii2

Your problem is that last rule ('site/GetNewTicketsTechnician' => 'site/get-new-tickets-technician'). It has site/get-new-tickets-technician as target route, so when you use it with Url::to() it will be used in reverse. If you need that url to be callable (you have incoming requests on it), but don't want to include it for createUrl-statements...

Change the button action in Gridview based on a model attribute value Yii2

php,yii2

Try with this.. [ 'class' => 'yii\grid\ActionColumn', 'template' => '{activate}{deactivate}', 'buttons' => [ 'activate' => function ($url, $model) { if($model->status==1) return Html::a('<span class="glyphicon glyphicon-eye-open"></span>', $url, [ 'title' => Yii::t('app', 'Activate'), ]); }, 'deactivate' => function ($url, $model) { if($model->status==0) return Html::a('<span class="glyphicon glyphicon-eye-open"></span>', $url, [ 'title' => Yii::t('app', 'Deactivate'), ]);...

yii2 join model as dataProvider

yii2

That is because an ActiveQuery instance is not a DataProvider, which the widget expects. You need to wrap it in an ActiveDataProvider for it to work: GridView::widget([ 'dataProvider' => new \yii\data\ActiveDataProvider(['query' => $model]), ' columns' => [ 'date', // sample field from first table to see if ok ], ]);...

Yii2 Active record query multiple where clause from array

yii2

Can be done like this: $query = ModelName::find()->where(['parentId' => $arr]); $dataProvider = new ActiveDataProvider([ 'query' => $query, ]); When you pass an array to where, Yii automatically transforms it into IN condition. So generated SQL conditional part will be WHERE parentId IN (1, 2, 4, 6);. It's equivalent to your...

Handling Guests in Yii2 to prevent constant checks

php,yii,yii2,yii2-user

Extending User is a good idea, but you'd better add there new method like getUsername() or getAttributes() returning identity/guest default data. Your way will destroy User's 'getIsGuest' method which is based on 'getIdentity' null/not null return. And I believe this method is essential and changing it's response could break a...

How to use custom css file for layout of a module in Yii2

php,css,layout,module,yii2

You should create your custom asset bundle file. For example: /frontend/module/admin/assets/AdminAsset.php Then define your css file in the $css array of your admin asset bundle: public $css = ['css/admin.css']; Put your admin.css file into /frontend/module/admin/web/css/admin.css. Register you admin asset bundle in your layout, view, etc.: use frontend\module\admin\assets\AdminAsset; AdminAsset::register($this); Update:...

Yii2 - create dropdown (select) with another model

php,yii2

Try this <?= $form->field($model, 'your_field')->dropDownList( ArrayHelper::map(Country::find()->all(), 'country_id', 'Country_description'),['prompt'=>'']) ?> change country_id, your_field and country_description for your need...

How to block an action or controller without using AccessControl in Yii2? [on hold]

yii2,access-control

You can try Using yii\web\CookieCollection - Refeer to http://www.yiiframework.com/doc-2.0/yii-web-cookiecollection.html Example: to save cookie: $cookies = Yii::$app->response->cookies; $cookies->add(new \yii\web\Cookie([ 'name' => 'nameOfCookie', 'value' => 'oreo', ])); to retrieve: $cookie = $cookies->getValue('nameOfCookie', 'biscuit'); if($cookie == 'oreo') throw new \yii\web\ForbiddenHttpException('Insufficient privileges to access this area.'); Enjoy Yii2!...

Yii2 : how to cache active data provider?

php,caching,yii2,dataprovider

It has little use caching the data provider after instantiating, since it's not actually doing any selecting on the database until it has been prepared. So you would actually be caching an empty object instance like it is now. If you have a very large set of records, call the...

Yii 2: Module class not found

php,yii2,yii2-advanced-app,yii-modules

Normaly the module is indicated in this way 'modules' => [ 'moduleName' => [ 'class' => 'vendor\vendorName\moduleName\Module', and rename your module class in Module and not Cropk This is a sample of Module.php /* * * */ namespace vendor\xxx\modulename; use \yii\base\Module as BaseModule; /** * */ class Module extends BaseModule...

No error message show in yii2

yii2,yii2-advanced-app

You need to remove <form class="col-md-12 col-sm-12 col-xs-12"> and </form> from your page, because <?php $form = ActiveForm::begin();?> generates proper form tag and csrf-token if needed. Also check if your model have validation rules. Yii2 provides js field validation before submit by-default (for default validators). If js validation somehow pass...

Getting an error Call to a member function getCount() on a non-object

yii2

Okey I see where what is wrong return $this->render('index', [ 'model' => $model, 'dataProvider' => $models, ]); getModels() returns just an array of elements. If You are trying to generate gridView or something like that You should give whole dataProvider. So it should be 'dataProvider' => $dataProvider, ...

MongoDB on Amazon EC2 - Configuring Mongo Client for Php

php,mongodb,yii,amazon-ec2,yii2

From the error message it seems that you haven't installed the PHP Mongo Driver in your server. To check if you have it, try a php_info() and check if the entry "mongo" is present If it's not present install it using the instructions found in the link above, or check...

Yii2 - Kartik Grid Extension Error

php,gridview,yii2

SOLVED, by running in the terminal (mac osx yosemite), and inside the website folder, the following command: SUDO COMPOSER UPDATE. Basically it updated the framework and all it's extension's to the latest versions. After the update the grid appeared, and everything was working ok inside it. Activated the toolbar with...

How to install DateTimePicker in Yii2

yii2,yii-extensions,yii-components

You need to install or update your composer. If you are using Ubuntu or Linux Operating System, open command prompt and run this command: composer require --prefer-dist yiisoft/yii2-jui This will create the jui folder which contains all the required plugins such as datepicker or any other you want to use...

Undefined offset: 0 in yii2

php,yii2,gammu

You have to try this way to find data from MODELs for NOT NULL clause. Do it for all your model that checks not null condition. Because your model has no element with key 0 in this case that why it returns Undefined offset 0 SibuPayment::find()->where(['not', ['Sibu_Payment.total_payment' => null]])->all(); For...

Yii 2: Load a module's view as a partial view on another application view

php,yii2,yii-modules

Looking at render's documentation you have a few options: The view to be rendered can be specified in one of the following formats: path alias (e.g. "@app/views/site/index"); absolute path within application (e.g. "//site/index"): the view name starts with double slashes. The actual view file will be looked for under the...

yii2 show hidden field

javascript,field,yii2

Because the value that you pass into js function with showOther(this.value) is not Lainnya its 9999. If you want to check for exact text and not the integer value try this return showOther(this.options[this.selectedIndex].innerHTML) UPD: to get onchange attribute, you need to place it into the same array where you place...

Yii2: How to add validation rules to the model class dynamically?

php,reflection,model,yii2

You can code the rules()-function to build an array of validation rules depending on the scenario and data input. It is not a requirement that this is a fixed array. Unfortunately doing it this way will leave you with validation issues on the frontend (should you need that), dynamic rules...

yii2 error when trying to install all generats files

php,frameworks,yii2

On linux, for security purposes, you have to refer to the current directory specifically. You will have to use ./init --env=Development --overwrite=n Also take a look here for a more extensive explanation....

Error deploying yii2-starter-kit Yii2 installation

web-services,yii2

The Yii2-Starter-Kit is not ready to work in a single-domain installation. You must enable, for example: backend.website.com, storage.website.com and the frontpage www.website.com The installation guide, specifies this. You can use this guide, to setup your single-domain installation (remember that the yii2-starter-kit also uses the storage folder!). Have a great week....

Codeception Acception: How to validate a changed Url

php,yii2,codeception,acceptance-testing

I think you don't need this "$I->amOnPage('/index.php');" because this does not check current url (for that purpose you should use "$I->seeInCurrentUrl(...)"), but leads you to that url. So what you are actually doing here is refreshing your index page and losing the welcome flash message. I believe all you need...

Form Not working in YII2

php,yii2

Add a return before render! return $this->render('userForm', ['model'=> $model]); ...

yii2 disable page cache on post request

php,caching,yii2,yii2-advanced-app

Since enabled is a boolean just pass the isGet variable from \yii\web\Request: 'pageCache' => [ ... 'enabled' => Yii::$app->request->isGet ] The Request class represents an HTTP request. Read more on it from the API page...

How do I create a complex left outer join in Yii2?

php,activerecord,orm,yii2

In relation to your remark of having to deal with ORM API, you can use the createCommand approach. You can just use your raw sql query with this method. The difference is that you don't get ActiveRecord[] as a result but just array[] (which is usually fine for complex queries)....

how to build Multiple File Upload in yii2 for the all types of files?

php,yii2

For Upload Multiple Files, follow the official tuto: https://github.com/yiisoft/yii2/blob/master/docs/guide/input-file-upload.md With files in folder, you can use Yii2 Galery or bootstrap\Carousel (in this post)....