Insert data inner join Cakephp 3.0 - mysql

I'm new to CakePHP, I just finished the blog/article tutorial and now I am trying to add the comment system to it.
In my comments table I have, Id, article_Id, name, email, text and created. In my articles table I have Id, user_id, title, text, created.
I'm trying to add the comment according to the article ID by using Insert Inner join Query. So let's say a user views a specific article like /view/1, before he add comments, the article ID is already passed so he can comment accordingly to that specific article ID he is viewing. How can I do that? I hope I'm clear.
This is my add function for my comment:
public function leavemessage()
{
$comment = $this->Comments->newEntity();
$articles = $this->loadModel('Articles');
$leavemessage = $articles->find()
->hydrate(false)
->join([
'table' => 'comments',
'alias' => 'c',
'type' => 'LEFT',
'conditions' => 'c.article_id = articles.id',
])
->insert(['id'])
->where(['c.article_id = articles.id'])
->execute();
if ($this->request->is('post')) {
$comment = $this->Comments->patchEntity($comment, $this->request->data);
if ($this->Comments->save($comment)) {
$this->Flash->success('The comment has been saved.');
return $this->redirect([
'controller' => 'Articles',
'action' => 'index',
'c.article_id'
]);
} else {
$this->Flash->error('The comment could not be saved. Please, try again.');
}
}
$articles = $this->Comments->Articles->find('list', ['limit' => 200]);
$this->set(compact('comment', 'articles'));
$this->set('_serialize', ['comment']);
}
My add comments view
<div class="comments form large-10 medium-9 columns">
<?= $this->Form->create($comment); ?>
<fieldset>
<legend><?= __('Add Comment') ?></legend>
<?php
echo $this->Form->input('article_id', ['value' => $articleId]);
echo $this->Form->input('name');
echo $this->Form->input('email');
echo $this->Form->input('text');
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
</div>

Related

Strategi must be a string

please help me..
when data input arises such problems "Strategi must be a string."
this is my controller :
$isistrategi = $_POST['FormNarasi'];
$fn = FormNarasi::find()->where([
'kriteria_id' => $model->id,
'form_spmi_id' => $formSpmi->id,
])->one();
if(empty($fn))
$fn = new FormNarasi;
$fn->kriteria_id = $model->id;
$fn->form_spmi_id = $formSpmi->id;
$fn->strategi = $isistrategi;
this is my _form :
<?php
$fn = FormNarasi::find()->where([
'kriteria_id' => $model->id,
'form_spmi_id' => $formSpmi->id
])->one();
echo $form->field($fn, 'strategi')->widget(CKEditor::className(), [
'options' => ['rows' => 6],
'preset' => 'advance'
])
?>
<div class="form-group">
<?= Html::submitButton('Save', ['class' => 'btn btn-success','value'=>'1','name'=>'btn-submit']) ?>
</div>
<?php ActiveForm::end(); ?>
please help, master
Here you are assigning an array to the model
$isistrategi = $_POST['FormNarasi'];
...
$fn->strategi = $isistrategi; // HERE
and in the following code you are accessing it. There is an array assigned. So you should assign there a string (the content of the CKEditor)
echo $form->field($fn, 'strategi')->widget(CKEditor::className(), [ // HERE
...
])
As #Sfili_81 mentioned, do not access the $_POST directly and rather use $model->load(Yii::$app->request->post())

How to create a dropdown dependent on another dropdown in yii2?

I have two api's:
1: returns all the industries,
2: returns all the industry category(based on industry id).
I need two dropdowns, one dependent on other. On selecting industry 2nd dropdown should show only relevant categories.
Thanks in advance.
I got it. I have simply used ajax which posts the value from one dropdown and sends the data to an action which returns the data and i am simply putting those values to my other drop down. :)
<?= $form->field($model, 'industryId')->dropDownList($industry,
['prompt'=>'Select Industry',
'onchange'=>'
$.get( "'.Url::toRoute('/site/category').'", { id: $(this).val() } )
.done(function( data ) {
$( "#'.Html::getInputId($model, 'industryName').'" ).html( data );
}
);
','class' => 'form-control'
]
); ?>
<?= $form->field($model, 'industryName')
->dropDownList(
['prompt'=>'Select category','class' => 'form-control']);
?>
_form.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use app\models\Category;
?>
<?php $form = ActiveForm::begin(); ?>
$model = Category::find()->select('id,name')->orderBy('name asc')->all();
$listData = ArrayHelper::map($model, 'id', 'name');
<?= $form->field($model, 'industryId')->dropDownList($listData,
['prompt'=>'Select Category',
'onchange'=>'
$.get( "'.Url::toRoute('/category/subcats').'", { id: $(this).val() } )
.done(function( data ) {
$( "#'.Html::getInputId($model, 'sub_category').'" ).html( data );
}
);
','class' => 'form-control'
]
); ?>
<?= $form->field($model, 'sub_category')
->dropDownList(
['prompt'=>'Select sub cat','class' => 'form-control']);
?>
----
You can use this extension. You can find explanation of plugin on its guide page.

Yii2-user, dektrium-yii2-user, Yii2 Populate a dropdown in yii2

I am pretty sure that there is a better way to populate the array, needed for the dropdown:
<?php
$items2 = [Yii::$app->user->identity->id => Yii::$app->user->identity->username ]; ?>
<!--...some html -->
<?= $form->field($model, 'idUser')->dropDownList($items2,['Item' => ''])?>
already try:
$item2 = ArrayHelper::map(Yii::$app->user->identity::find()->all(), 'id', 'name');
reason, I want to display 'name' but submit 'value'='id'.
Should be this
<?= $form->field($model, 'idUser')->
dropDownList(ArrayHelper::map(Yii::$app->user->identity->find()->all(),
'id', 'username'), ['prompt'=>'Select...'])?>

Yii2: getting error while page load '$model not defined'

I have developed form to allow owner to create team. code is:
<?php $form = ActiveForm::begin(['id' => 'team-create-form', 'action' => ['site/create-team-form'], 'options' => array('role' => 'form')]);
<div class="col-lg-10 form-group" id="createTeamForm" style="margin-top: 15px;">
<div class="col-lg-4">
<?= $form->field($model, 'team_name',['template' => "{label}\t{input}\n{error}"])->textInput(array('placeholder'=>'Enter team name....')); ?>
</div>
<div class="col-lg-4">
<?= $form->field($model, 'team_description',['template' => "{label}\t{input}\n{error}"])->textInput(array('placeholder'=>'Enter team Description....')); ?>
</div>
<div class="col-lg-2">
<?= Html::submitButton('Submit', ['class' => 'btn btn-danger', 'id' => 'tsubmit', 'style' => 'margin-top: 22.5px; margin-right: 15px;']) ?>
</div>
</div>
I have tried loading the page with the above code but it is showing me error "$model not defined". How to resolve that. Am i need to add something in the main-local.php???
public function actionLogin()
{
$model = new LoginForm();
$session = Yii::$app->session;
if ($model->load(Yii::$app->request->post()) && $model->login()) {
$collection1 = Yii::$app->mongodb->getCollection('users');
$teamid = $collection1->findOne(array('username' => $model->email_address));
$session->set('id', $teamid['_id']);
$session->set('name', $teamid['name']);
$session->set('username', $model->email_address);
$collection2 = Yii::$app->mongodb->getCollection('teamdashboard');
$teams = $collection2->find(array('admin' => $model->email_address));
$model1 = new TeamCreateForm();
return $this->render('dashboard', ['model'=>$model1, 'teams'=> $teams]);
} elseif($session->isActive){
$username = $session->get('username');
$collection = Yii::$app->mongodb->getCollection('users');
$teams = $collection->findOne(array('username' => $username));
return $this->render('dashboard', ['teams'=>$teams]);
}else{
$this->layout = 'index';
return $this->render('login', ['model' => $model]);
}
}
I have renamed the productpage as dashboard for better understanding.
Now when i run this & logs in, The address bar url shows url:..../web/index.php?r=site/login whereas it should show me url:..../web/index.php?r=site/dashboard & shows me the view of dashboard.
When i refresh the page, i brings me back to the login...
Did you use $model in dashboard view? If you do - you need to pass it (the same way as the login).
You have to send the $model to the view. The view only knows variables if you send it to it.
I have no idea what you mean with the address bar. The address bar has nothing to do with what you send to the view.
EDIT
Your entire way of thinking is strange. Why would u show different views depending if the person is registered or not?
return $this->render('dashboard', ['teams'=>$teams]);
return $this->render('login', ['model' => $model]);
User redirect with parameters to move the customer to another page. Having an URL like /login that actually shows a dashboard is not logical.

CakePHP onChange event

I have no idea why this onChange event is not working. Maybe I got so used to the code that I can't see my mistake. I'd appreciate your help:
<td class="cellInput">
<?php
$options = array('200'=>'200', '500'=>'500', '1000'=>'1000', '2000'=>'2000', '5000'=>'5000', 'Outro'=>'Outro');
$attributes = array('legend' => false);
echo $form->select('capacidade', $options, array(
'class' => '',
'label' => '',
'default' => '200',
'onchange' => "javascript:checkForOther(this);",
));
?>
</td>
As others suggested, place the attributes in the correct parameter position. The other thing i would do is remove the javascript and just have the function name in there like:
From: 'onchange' => "javascript:checkForOther(this);"
To: 'onchange' => "checkForOther(this)"
Try
Putting the attributes as the fourth argument instead of the third:
echo $form->select('capacidade', $options, null,
array(
'class'=>''
,'label' => ''
,'default' => '200'
,'onchange' => "javascript:checkForOther(this);"
)
);
Does the source of the generated page have the onChange attribute?
See the documentation
According to CakePHP documentation on select method, the third argument is used to choose which option is selected by default.
You must use the fourth argument to pass HTML attributes to a select element:
<td class="cellInput">
<?php
$options = array('200'=>'200', '500'=>'500', '1000'=>'1000', '2000'=>'2000', '5000'=>'5000', 'Outro'=>'Outro');
$attributes = array('legend'=>false);
echo $form->select('capacidade', $options, '200', array('class'=> '', 'label' => '', 'onchange' => "checkForOther(this);"));
?>
</td>