How to integrate ckfinder with yii2 - yii2

I am trying to integrate ckeditor and ckfinder to a project using yii2.
I have placed both ckeditor and ckfinder folder in root/vendor and made necessary adjustments, ckeditor is working fine, ckfinder also showing the file browser popup with 'Browser server' button. But whenever I click on the browse button its not opening the file selector popup, instead showing a page not found error.
I have tried to integrate ckfinder writing following lines of code in ckeditor/config.js:
config.filebrowserBrowseUrl = 'hostname/vendor/ckfinder/ckfinder.html';
config.filebrowserImageBrowseUrl = 'hostname/vendor/ckfinder/ckfinder.html?type=Images';
config.filebrowserFlashBrowseUrl = 'hostname/vendor/ckfinder/ckfinder.html?type=Flash';
config.filebrowserUploadUrl = 'hostname/vendor/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files';
config.filebrowserImageUploadUrl = 'hostname/vendor/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images';
config.filebrowserFlashUploadUrl = 'hostname/vendor/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash';
But I haven't found a solution.
Can anyone please help me fix that issue?

I was create Custom CKEditorAsset in yii2 like this:
namespace vendor\yiif\ckeditor;
use iutbay\yii2kcfinder\KCFinder;
use iutbay\yii2kcfinder\KCFinderAsset;
class CKEditorAsset extends \dosamigos\ckeditor\CKEditorAsset
{
public $depends = [
'yii\web\YiiAsset',
'yii\web\JqueryAsset',
//'iutbay\yii2kcfinder\KCFinderAsset'
];
public function init()
{
$register = KCFinderAsset::register(\Yii::$app->view);
$kcfinderUrl = $register->baseUrl;
\Yii::$app->view->registerJs(<<<js
CKEDITOR.config.filebrowserBrowseUrl="$kcfinderUrl/browse.php?opener=ckeditor&type=files";
CKEDITOR.config.filebrowserUploadUrl="$kcfinderUrl/upload.php?opener=ckeditor&type=files";
js
);
// kcfinder options
// http://kcfinder.sunhater.com/install#dynamic
$kcfOptions = array_merge(KCFinder::$kcfDefaultOptions, [
'uploadURL' => \Yii::getAlias('#web/uploads/modules/ckfinder'),
'uploadDir'=>\Yii::getAlias('#app/web/uploads/modules/ckfinder'),
'access' => [
'files' => [
'upload' => true,
'delete' => false,
'copy' => false,
'move' => false,
'rename' => false,
],
'dirs' => [
'create' => true,
'delete' => false,
'rename' => false,
],
],
]);
// Set kcfinder session options
\Yii::$app->session->set('KCFINDER', $kcfOptions);
parent::init();
}
}

Related

yii2 file required custom validation

I have a form where the required validation rules for the fields can be configures and stored in the model.
When rendering the form, I create the validation rules as follows (simplified) which works fine.
$view_parameters = $competition_article->view_parameters;
if (!empty($view_parameters) && is_array($view_parameters)) {
foreach ($view_parameters as $parameter_key => $parameter_value) {
$field_name = $parameter_value['name'];
$field_required = $parameter_value['required'];
if ($field_required) {
Validator::createValidator('required', $model, [$field_name]);
}
}
}
For the form submission, I use a custom validation rule. This works for all but the file attachment.
public function rules()
{
$rules = [
[['firstname', 'surname', 'closeststore', 'email', 'phone', 'response', 'attachment'],
'dynamicValidator',
'skipOnEmpty' => false
],
[['attachment'], 'file',
'extensions' => 'pdf, jpeg, jpg, doc, docx',
'checkExtensionByMimeType'=>false
],
];
return $rules;
}
On the custom validation method, I handle the file separately.
I tried
a) addError() and return false
b) createValidator() and validateAttribute() pair , which works for the text fields.
public function dynamicValidator($attribute, $params, $validator )
{
$view_parameters = $this->view_parameters;
if ($view_parameters[$attribute]['required'])
$validator = new Validator();
if ($attribute == 'attachment') {
if (empty($_FILES['CompetitionForm']['name']['attachment']))
[$attribute]);
$this->addError( $attribute, 'Please include your attachment to enter.');
// NOTE : Adding the validator has no effect
// $validator = $validator->createValidator('required', $this,
// $validator->validateAttribute($this, $attribute);
return false;
}
$validator = $validator->createValidator('required', $this, [$attribute]);
$validator->validateAttribute($this, $attribute);
}
}
Despite the code being reached, an error is not raised when the attachment is require and the either the addError() or createValidator() is called.
How can I fail the validation when no file is attached and the attachment is required?
You can try with this validation rules for attachment using skipOnEmpty.
[['attachment'], 'file',
'skipOnEmpty' => false,
'extensions' => 'pdf, jpeg, jpg, doc, docx',
'checkExtensionByMimeType'=>false
],

How to add custom new field in yii2 gii generated crud

I have made one CRUD in YII2 using Gii having 10 fields. In my mysql table there was logo column so Gii generated text field for it. I converted it to file field using the following code.
$form->field($model, 'manufacturer_logo')->fileInput()
Now I am not getting any clue where I can write controller side code so that I can save logo in folder and DB like other fields. There is no saving code in Gii generated controller. I tried to follow this but it also did not work.
In my model rules, I have written following line for valid image file.
public function rules()
{
return [
[['manufacturer_description', 'manufacturer_status','manufacturer_logo'], 'string'],
[['manufacturer_name','manufacturer_status','manufacturer_logo'], 'required'],
[['manufacturer_logo'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg'],
[['created_at', 'updated_at'], 'safe'],
[['manufacturer_name'], 'string', 'max' => 255],
];
}
Now when I fill all fields and browse image as well and press submit then it gives me error "Please upload a file", here you can see so I am not able to upload image and save its name in DB column like other fields.
For further doing RND, Now image is saving in folder but not in database, Here I changed controller code.
public function actionCreate()
{
$model = new Manufacturers();
if ($model->load(Yii::$app->request->post())) {
//upload logo
$base_path = Yii::getAlias('#app');
//$model = new UploadForm();
$imageFile = UploadedFile::getInstance($model,'manufacturer_logo');
$logoName = "";
if (isset($imageFile->size)) {
$imageFile->saveAs($base_path . '/web/uploads/' . $imageFile->baseName . '.' . $imageFile->extension);
$logoName = $imageFile->baseName . '.' . $imageFile->extension;
}
if(trim($logoName)!='') {
$model->manufacturer_logo = trim($logoName);
}
$model->save(false);
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('create', [
'model' => $model,
]);
}

Yii2 - Class 'mPDF' not found

As I tried to Export to PDF from my Application, but I got this error:
I don't really know what is causing the error. I have tries several means to no avail. This is the component:
<?php
namespace backend\components;
use Yii;
use yii\base\Component;
use yii\base\InvalidConfigException;
use common\models\Organization;
use yii\helpers\Html;
use yii\web\NotFoundHttpException;
use mPDF;
class ExportToPdf extends Component
{
public function exportData($title='',$filename='Jkkesrms Pdf',$html=NULL)
{
$mpdf = new mPDF('utf-8', 'A4',0,'',15,15,25,16,4,9,'P');
$mpdf->autoScriptToLang = true;
$mpdf->autoLangToFont = true;
$org = Organization::find()->asArray()->one();
$src = Yii::$app->urlManager->createAbsoluteUrl('site/loadimage');
$org_image=Html::img($src,['alt'=>'No Image','width'=>90, 'height'=>70]);
$org_name=$org['org_name'];
$org_add=$org['org_address_line1']."<br/>".$org['org_address_line2'];
$mpdf->SetHTMLHeader('<table style="border-bottom:1.6px solid #999998;border-top:hidden;border-left:hidden;border-right:hidden;width:100%;"><tr style="border:hidden"><td vertical-align="center" style="width:35px;border:hidden" align="left">'.$org_image.'</td><td style="border:hidden;text-align:left;color:#555555;"><b style="font-size:22px;">'.$org_name.'</b><br/><span style="font-size:10.2px">'.$org_add.'</td></tr></table>');
$stylesheet = file_get_contents('css/pdf.css'); // external css
$mpdf->WriteHTML($stylesheet,0);
$mpdf->WriteHTML('<watermarkimage src='.$src.' alpha="0.33" size="50,30"/>');
$mpdf->showWatermarkImage = true;
$arr = [
'odd' => [
'L' => [
'content' => $title,
'font-size' => 10,
'font-style' => 'B',
'font-family' => 'serif',
'color'=>'#27292b'
],
'C' => [
'content' => 'Page - {PAGENO}/{nbpg}',
'font-size' => 10,
'font-style' => 'B',
'font-family' => 'serif',
'color'=>'#27292b'
],
'R' => [
'content' => 'Printed # {DATE j-m-Y}',
'font-size' => 10,
'font-style' => 'B',
'font-family' => 'serif',
'color'=>'#27292b'
],
'line' => 1,
],
'even' => []
];
$mpdf->SetFooter($arr);
$mpdf->WriteHTML('<sethtmlpageheader name="main" page="ALL" value="on" show-this-page="1">');
$mpdf->WriteHTML($html);
$mpdf->Output($filename.'.pdf',"I");
}
}
?>
I have tried tried several means but the error persists. Please how do I resolve this error?
You need to include the full namespace with the use statement. Looking at the code it looks like that you are using this library. If that is correct then include it like
use Mpdf\Mpdf;
and then use it like below
$mpdf = new Mpdf('utf-8', 'A4',0,'',15,15,25,16,4,9,'P');

Yii2 - Update database field when switchinput widget is clicked

I am using the switchinput Kartik widget which I have related to a database true/false field (field1). What I want to do is to be able to update this database field value when I change the switch.
Here is the view code:
<?php
echo $form->field($model, 'field1')->widget(SwitchInput::classname(), [
'type' => SwitchInput::CHECKBOX,
'name' => 'status_11',
'pluginOptions' => [
'size' => 'medium',
'onColor' => 'success',
'offColor' => 'danger',
'handleWidth'=>80,
'onText'=>'ACTIVE',
'offText'=>'INACTIVE'
]
]);
?>
and here is the controller code that tries to update the database:
.................
if (isset($_POST['status_11']))
{
if ($model->field1 == False)
{
$model->field1 = True;
}
else
{
$model->field1 = False;
}
}
if(!$model->save())
{
throw new Exception('Could not save to database. Trnasaction aborted.');
}
..................
The switch can read from the database the value of field1 and show on or off respectively. But the change (onclick) action does not update the database...
Should I try using PHP or should I implement it with js ('pluginEvents' widget option) and how?
Any suggestions would be highly appreciated. Thank you in advance.
You should use the pluginEvents array with the switchChange event, to trigger an ajax call to your php script, which updates the database:
pluginEvents = [
"switchChange.bootstrapSwitch" => 'function() {
$.ajax({
method: "POST",
url: "'.Url::to(['/controller/action']).'",
data: { status_11: state}
})
}',
];

How to update customer in braintree payment method

I have integrated braintree method in yii2 rest api Using this reference.. I want to update the customer but I am getting following error:
Missing argument 2 for Braintree\Customer::update()
Below is my code :
$braintree = Yii::$app->braintree;
$response = $braintree->call('Customer', 'update','15552090',[
'firstName' => 'test-1545',
'lastName' => 'asdf',
'company' => 'New Company',
'email' => 'new.email#example.com',
'phone' => 'new phone',
'fax' => 'new fax',
'website' => 'http://new.example.com'
]);
print_r($response); die;
I am stack here how to pass the arguments?
It's a problem of this particular extension. See this issue on Github.
Issue OP recommends this fix:
public function call($command, $method, $values, $values2 = null)
{
$class = strtr("{class}_{command}", [
'{class}' => $this->_prefix,
'{command}' => $command,
));
if ($values2) {
return call_user_func(array($class, $method), $values, $values2);
else {
return call_user_func(array($class, $method), $values);
}
}
while extension author recommends this:
if (is_array($values)) {
call_user_func_array(...);
} else {
call_user_func(...);
}
Either way you need to override this component with your own and apply a patch.
Note that the amount of code in application is small (64 lines in one file) so you can create your own wrapper or find better one because this issue is still not fixed.
And maybe is better to directly use braintree_php methods which will be more clear than magical call.
Update: To override component, create own class extending from bryglen's, place it for example in common/components folder in case of using advanced app.
namespace common\components;
class Braintree extends \bryglen\braintree\Braintree
{
public function call($command, $method, $values)
{
// Override logic here
}
}
Then replace extension class name with your custom one in config:
'components' => [
'braintree' => [
'class' => 'common\components\Braintree',
'environment' => 'sandbox',
'merchantId' => 'your_merchant_id',
'publicKey' => 'your_public_key',
'privateKey' => 'your_private_key',
],
],