Quantcast
Channel: Yii Framework Forum
Viewing all 18717 articles
Browse latest View live

Facing error when running Master-Slave setup with PCNTL

$
0
0
I am facing error when running Master-Slave setup with PCNTL.

exception 'CDbException' with message 'CDbCommand failed to execute the SQL statement: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away' in /home/mailwizzbuynbag/public_html/mail/apps/common/framework/db/CDbCommand.php:631

If PCNTL is off. Master/Slave setup works perfectly.

Following is the configuration of Master/Slave setup
return array(
'components'=>array(
'db'=>array(
'class'=>'system.db.CDbConnectionRwMaster',
'connectionString'=>'mysql:host=<MasterHost>;dbname=<dbname>',
'charset'=>'utf8',
'username'=>'<dbuser>',
'password'=>'<dbpassword>',
'slaves'=>array('db_readonly1'), // List of read-only slaves
'enableRwSplitting'=>true, // Enable read-write-splitting for this connection
'tablePrefix' => 'mw_',
),
'db_readonly1'=>array(
'class'=>'CDbConnection',
'connectionString'=>'mysql:host=<SlaveHost>;dbname=<dbname>',
'charset'=>'utf8',
'username'=>'<dbuser>',
'password'=>'<dbpassword>',
'tablePrefix' => 'mw_',
),
)
);


Thanks

Get data from two columns in database

$
0
0
I'm currently trying to run an API call that grabs all the emails + names and fire them off back into the system. I pass through the list_id through a button and it'll insert all database values that match into the database

I can succesfully get this working with single values but when I try to insert all the values by grabbing the data and putting into an array it comes back NULL.

The line I think is causing an issue is the following

$emailArr[] = CMSubscribers::model()->findAll('email_address');
$nameArr[] = CMSubscribers::model()->findAll('forename');


The full code can be found below if any other suggestions want to be made


public function actionImportSubscribers($cm_list_id){

        //need to pass through cm_list_id instead 
        $cm_list_id = Yii::app()->getRequest()->getQuery('cm_list_id');

        $model =$this->loadModelList($cm_list_id);

        $listID = $model->cm_list->cm_list_id;

        //$email[] = array($model->email_address);
        $emailArr[] = CMSubscribers::model()->findAll('email_address');
        $nameArr[] = CMSubscribers::model()->findAll('forename');
        //$name[] = array($model->forename . ' ' . $model->surname);

        $customFieldArray = array();

        $addFieldsToList = array();
        foreach (array_combine($nameArr, $emailArr) as $name => $email) {
            $addFieldsToList[] = array('Name' => $names,'Email Address' => $emails,'CustomFields' => $customFieldArray);
        } 

        require_once 'protected/extensions/createsend-php-5.0.1/csrest_subscribers.php';

        $auth = array('api_key' => '');


        $wrap = new CS_REST_Subscribers($listID, $auth);
        $result = $wrap->import(array($addFieldsToList), false);

            if($result->was_successful()) {
                echo "Subscribed with results <pre>";
                var_dump($result->response);
            } else {
                echo 'Failed with code '.$result->http_status_code."\n<br /><pre>";
                var_dump($result->response);
                echo '</pre>';

                if($result->response->ResultData->TotalExistingSubscribers > 0) {
                    echo 'Updated '.$result->response->ResultData->TotalExistingSubscribers.' existing subscribers in the list';        
                } else if($result->response->ResultData->TotalNewSubscribers > 0) {
                    echo 'Added '.$result->response->ResultData->TotalNewSubscribers.' to the list';
                } else if(count($result->response->ResultData->DuplicateEmailsInSubmission) > 0) { 
                    echo $result->response->ResultData->DuplicateEmailsInSubmission.' were duplicated in the provided array.';
                }

                echo 'The following emails failed to import correctly.<pre>';
                var_dump($result->response->ResultData->FailureDetails);
            }
            echo '</pre>';
        // }

    }

Diferencia De Dias Entre Dos Fechas

$
0
0
Buenos Dias!! Estoy comenzando a explorar este mundo de Yii, espero me sean de gran ayuda..
Tengo dos campos en mi form, fecha_inicial y fecha_culminación tipo Date en mi base de datos postgres.. y necesito que al usuario elegir la fecha_culminación me calcule automaticamente el la diferencia de dias entre una fecha y otra.. Le agradecia de antemano la ayuda.. Ah! ambos campos usan cjuidatepicker..

CDBException displaying PHP internals

$
0
0
Much like in this post, http://www.yiiframework.com/forum/index.php/topic/72143-cdbexception/

Instead of routing to the site/error, it's displaying the PHP code to the end user. Ideally, I'd like to, if my IP show the PHP code error so I can resolve/debug and when they encounter it, I can 404 them and send myself an email with the requested URL.

My local development machine doesn't reproduce this issue! It goes to the site/error and shows 404. I thought it had to do with error_reporting() but unless it's not for some reason accepting my settings, it's still displaying. I'm not sure how to write a good google search for this scenario. Sorry if it's something obvious, I'd hoped that someone could say definitively, that it is XYZ or error_reporting or an apache (.htaccess) setting or....

Thank you in advance for your time. This is a legacy 1.1.x project

Ошибка "Module 'dom' already loaded"

$
0
0
Всем привет!
Суть проблемы такова:
Залил сайт на Yii 2.0.8 на хостинг с apache 2.х + php 5.6, при загрузке сайта в футере показывается следующая ошибка:

PHP Core Warning – yii\base\ErrorException
Module 'dom' already loaded

2. yii\base\ErrorHandler::handleFatalError()


Нарыл по данной ошибке предполагаемое решение(http://www.somacon.com/p520.php) которое состояло в отключении вызова модуля DOM в файле php.ini, хостер модуль отключил, но, видимо, второй раз модуль таки не вызывался т.к. вылетела ошибка у зависмого от DOM модуля, название которого, к сожалению забыл..

Хостер вернул все обратно, а я полез в runtime/cache и обнаружил там папку 96, которую ради интереса удалил. После чего сайт один раз прогрузился на ура, но при повторном обновлении страницы проблема снова появилась..

Я провобал в конфиге yii менять тип кеширования на DbCache, DummyCache(как я понял это отключает кеширование), но проблема не ушла. Напротив, при удалении записи таблицы cache эквивалентной файлу кеша в папке 96 сайт даже 1 раз нормально не прогружался..

На одном форуме посоветовали отключить enable_dl, но на старом хостинге он был тоже включен и проблем не возникало.. Может проблема в каком-нибудь другом неподключенном расширении PHP? Есть ли список обязательных для работы YII2 модулей php?

full calendar extension

$
0
0
Hi,
I am using efullcalendar extension for showing attendance of a student,but its not showing the events when i set it for different days(multi day events) and it will show the event when i set it only for a day.please help me .


here a part of my view page
$.ajax({
success: function(events)
{
$('#yw0').fullCalendar('removeEvents');
$('#yw0').fullCalendar('addEventSource', events);
},
type: 'get',
url: '<?php echo $this->createUrl('renderattendance');?>',
cache: false,
data: {
year: year,
month: month,
},
dataType: 'json',
});

Akcje

$
0
0
Witam forumowiczów,

Może ktoś z Was wie jak rozwiązać następujący problem.

Chcę, aby po odwiedzeniu konkretnej akcji w kontrolerze, nie była ona więcej dostępna w bieżącej sesji. Tzn. po ponownym uruchomieniu nastąpiło np. przekierowanie do innej strony.

Ktoś z Was kojarzy jakiej klasy użyć? Pytam bo podejrzewam, że jest taka funkcjonalność we framework’u, ale nie za bardzo się orientuje, gdzie tego szukać.

Dzięki za pomoc i pozdrawiam

Yii2 and PHP 7

$
0
0
Hello Friends,

I know it's too early to discuss but I think better this community start discussing on the near future.

I have already done many projects with Yii 1.1.x and a few with Yii 2 and when I look for my future projects I still find Yii 2 as better option. But still when I have PHP 7 with major performance overhauls and changes I definitely look for my applications to be PHP 7 compatible so that we all can take performance boosts expected.

I know YII Devs must have been thinking on this but I wish if you could share your future insights on the topic would be a great moral booster for YII community.


Regards,
Jai

PHP/Yii2 developers with 5 years experience [Poland]

$
0
0
Innobit.pl is Poland based web-apps development company. We are small team of experienced PHP programmers and we specialize in development of web applications, especially written in Yii2.

In our work we use:
- Yii2 for 3 years,
- JavaScript (Ajax,jQuery, CanJs - SPA framework),
- Responsive Web frameworks (bootstrap, zurb)


We are prepared for long-term projects and looking for clients.
Contact: kontakt@innobit.pl

SafeResponse component

$
0
0
I've prepared extended Response component for additional security headers. Let me know what you think about this.

SafeResponse component at GitHub

Additional headers:
  • Content-Security-Policy
  • X-Frame-Options
  • X-XSS-Protection
  • Strict-Transport-Security
  • X-Content-Type-Options
  • Public-Key-Pins


Remember to configure the component options to suit your needs because the default ones might be too restrict.

To use the component add it to your application, change the namespace to fit the file location and replace the default Response component with this one in configuration:

'components' => [
    'response' => [
        'class' => 'your\namespace\here\SafeResponse',
        // configuration here
    ],
],


For HTTPS Cookies remember to set safe Cookies in configuration as well i.e.:

'components' => [
    'user' => [
        // configuration here
        'identityCookie' => [
            'name' => '_identity',
            'httpOnly' => true,
            'secure' => true,
        ],
    ],
    'request' => [
        // configuration here
        'csrfCookie' => [
            'httpOnly' => true,
            'secure' => true,
        ],
    ],
    'session' => [
        // configuration here
        'cookieParams' => [
            'httpOnly' => true,
            'secure' => true,
        ],
    ],
],

utilizas yii 1.* o utilizas 2.* en español

$
0
0
Porqué usas el framework? Que versión utilizas? Que te gusta, que te desagrada son cosas que me interezaria saber de la comunidad. A mi realmente me gusta el framework en su versión 2 la versión 1 me desagrada XD y creo que muchas personas se quedan con la impresión de esa versión :/. Si no te gusta, me gustaría saber porque?

yii2-rbac-plus PHP fatal error yii\base\ErrorException

$
0
0
I'm using yii2-rbac-plus module. Everything seems to be working fine in the web app, but I just noticed this error in the console:

PHP Fatal error:  Class 'Yii\base\Exception' not found in /var/www/vhosts/.../vendor/johnitvn/yii2-rbac-plus/src/Module.php on line 74
PHP Fatal Error 'yii\base\ErrorException' with message 'Class 'Yii\base\Exception' not found'
in /var/www/vhosts/.../vendor/johnitvn/yii2-rbac-plus/src/Module.php:74


I'm not sure if this is a problem with the module or a configuration error on my end. I've tried adding
use yii\base\Exception;
to Module.php, but that has no effect.

change database before starting secion

$
0
0
good afternoon really hope and help me thank you very much for your comments

in the main Yii1, the database is configured. but I would choose to Database want to go without going to main Yii as it could do?

Что бы такого написать...

$
0
0
Здравствуйте.
Хотел поинтересоваться т.к. в голову ничего пока не лезет, что можно было бы написать для Yii 2, чем бы пользовались люди :)
Речь идет о чем-то компактном и модульном. Какой-нибудь полезный виджет, модуль, тему...
В работе yii не использую и реальных задач нет, но хотелось бы его изучить.

Спасибо.

db/Query и поздапросы

$
0
0
имеется сложный запрос с несколькими innerJoin:
$query = new Query();
...
$query->innerJoin(['phs' => '{{%vg_price_hotel_service}}'], 'phs.PriceId = prices.Id');
...

Все нормально работает.
Но необходимо добавить leftJoin, в ON условии которого имеется подзапрос вида:
LEFT JOIN [dbo].[HotelQuotas] as hqs ON hqs.Id =
(
    SELECT  TOP 1 Id
    FROM [dbo].[HotelQuotas]
    WHERE   BuildingId = blds.Id
    AND RoomCategoryId = rmcts.Id
    AND RoomTypeId = rmtps.Id
    AND TourOperatorId = prices.TourOperatorId
    AND (TypeVisit = 0 AND NOT ((DATEADD(DD, hs.Nights, prices.Date) < Date) OR (DATEADD(DD, Duration, Date) < prices.Date))
      OR TypeVisit = 1
      AND prices.Date >= Date
      AND prices.Date <= DATEADD(DD, Duration, Date)
      )
    ORDER BY Id DESC, FreeAccess ASC

все связи, blds, rmcts, rmtps, prices, hs определены в innerJoin-ах выше.
с какой стороны лучше подлезть... есть варианты? что-то не могу осилить

Http://www.humhub.org/

Yii2 experienced

$
0
0
I write not fast, but testing immediately and therefore almost without mistakes. I love to write code, but do not write without a full structural algorithm - old school and do not like to rewrite. Reasonable, logical, train, sanguine - easy working in a team. I do not work with NoSQL databases, but build good schemes and logic in SQL. Looking for remote work backend / fullstack on Yii2. I write frontend logic too. Not doing frontend design, excluding "out of the box", but can "pull" the finished design on a project or can fasten something from jQuery UI, for example. Bootstrap - and in wrappers and clean sometimes, however - this also applies to SQL. I know Linux (Ubuntu, Mint, Suse) - can not rebuild the kernel, but like user is experienced and of shared Linux hosting too. Now writing under the control of Windows 10. Do not dock, but I understand the logic of the scaling, especially in PHP projects. All existing basic Web services using at the primary level - with some help I'll deploy properly on them, especially under HHVM. I do not write on demand "necessary yesterday". Commonly - I am not young, meticulous, experienced, structural PHP Programmer.

Job application test task
Repository https://github.com/r...ra/KL_id20_test , working example - http://id20test.mafiaonlinegame.com . I don't fulfill any test tasks more - there are everything what are need: MVC, PHP, Yii2, CRUD, HTML, CSS, Responsive design, jQuery UI, clean the SQL, framework caching, Faker - filling database by fake values, array processing, migrations, GIT - deployed somehow)), instructions on how to deploy a WAMP -LAMP, already deployed pattern. Thank you in advance.

My main project http://mafiaonlinegame.com/

__________________________________________________________________________________________

Пишу не быстро, но тестирую сразу и поэтому практически без ошибок. Люблю писать именно код, но вообще не пишу без полного структурного алгоритма - старая школа и не люблю переписывать. Вменяем, логичен, обучаем, сангвиник - спокойно работаю в команде единомышленников. Не работаю с NoSQL базами, но неплохо строю схемы и логику на SQL. Ищу удаленную работу backend/fullstack на Yii2. Laravel как-то не пошла мне. Давно перешел бы на фейсбуковский Hack, но Yii2 люблю больше )). Вполне приемлемо пишу логику и frontend`а. Не занимаюсь frontend дизайном, кроме как "из коробки", но "натянуть" готовый дизайн могу или прикрутить чего-нибудь из jQuery UI, например. Bootstrap пользую и в обертках и в чистую иногда, впрочем - это касается и SQL. Знаю Linux (Ubuntu, Mint, Suse) - ядро не пересоберу, но пользователь опытный и shared Linux хостингов тоже. Как не странно - сейчас пишу под управлением Windows 10. Не дока, но понимаю в логике масштабирования, особенно касаемо PHP проектов. Все существующие основные веб сервисы юзал на начальном уровне - с определенной помощью корректно разверну и там, особенно под HHVM. Принципиально не пишу по запросам "надо вчера" - вообще я не молодой, въедливый, довольно опытный, структурный программист PHP.

Репозиторий с тестовым заданием: https://bitbucket.or...ru/kl_id20_test рабочую версию можно посмотреть http://id20test.mafiaonlinegame.com/ . Других тествых заданий больше не пишу - там есть все что надо: MVC, PHP, Yii2, CRUD, HTML, CSS, Responsive design, jQuery UI, чистый SQL, кеширование базы, Faker - заполнение фейковыми значениями, обработка массивов, миграции, GIT - выложено же как-то)), инструкции как развернуть под WAMP-LAMP, уже развернутый образец.

Мой проект http://mafiaonlinegame.com/

Formulario create/update manualmente

$
0
0
Hola estoy retomando nuevamente Yii2 para un proyecto personal. Soy realmente nuevo. Hice la base de datos y generé todos los modelos, vistas y controladores usando el gii. Sin embargo el proyecto me exige cambiar mucho del diseño de los formularios y de las vistas en general, por ello quisiera saber si hay alguna manera en que pueda hacer los formularios manualmente pro que se me quede todas las validaciones que trae por defecto el YII2, me explico un poco mejor:

en _form.php está el siguiente código
$form->field($model, 'ciud_ciudad')->textInput(['maxlength' => true])


Esto automáticamente me trae, el siguiente código

<div class="form-group field-ciudades-ciud_depa_id required has-error">
<label class="control-label" for="ciudades-ciud_depa_id">Ciud Depa ID</label>
<input type="text" id="ciudades-ciud_depa_id" class="form-control" name="Ciudades[ciud_depa_id]" value="">
<div class="help-block">Ciud Depa ID cannot be blank.</div>
</div>


Además al comenzar el formulario tengo también un campo oculto:
<input type="hidden" name="_csrf" value="bC5ieThULnYhHDdOWzh0DiFDFTh5JRZPVXc2PQ9iXlteWQstFTcbEQ==">


Como el diseño vamos a cambiarlo enormemente, por ejemplo el mensaje de error, deberá salir en otr parte y el label se desplegará de manera diferente (Con unos icónos), tendría mucho mas control desde CSS si puedo tener cada uno de estos elementos de manera individual en la vista. Pero no se hacerlo. ¿Me pueden ayudar por favor?

Algunas dudas concretas son:
1.Como hago para que funcione apropiadamente la validación con ajax
2. Cómo hago para desplegar el error en otra parte diferente

Muchas gracias

Emergency Help - Yii application Migration Error (From VPS to Shared Host)

$
0
0
Dear All Active Users , Please Help Me
We have developed a REST Client in yii framework for our admin Side.
our previous server was a VPS , now we migrated our application to a shared host.
all our applications are working very well
our rest app ( in phalcon ) is OK
our user side app ( which is a rest client ) is OK
our admin side app which is a rest client in yii 2.0, has got problems.
(note : in our vps , we had composer but in shared host, we don't have it )
so we copy the vendor folder to our yii admin app directory ,the ui rendered , we can also login to admin app ( so our rest is sound to be ok ) but we cant do anything in our admin app we always get this error (see the attachment)
for example when we click to see users list we get errors , the error is always the same.
please see the attachment (screen shot)

what should I do , is it because of composer? we just copy the vendor folder to our new shared host ,
is there any change that we should do , the login and authentication is working good...but others not !
please help me

Problems with enablePrettyUrl

$
0
0
Hi!

If I set the parameter "enablePrettyUrl" to true, I get into the Firebug-Console this error: http:**/debug/ default/toolbar?tag= 78f6476c0381 - TypeError: toolbarEl is null

What could be the Probem?
Viewing all 18717 articles
Browse latest View live