I am tring to insert data in a table.
trying like this but it`s not working.
$sql = $queryBuilder->insert(' HRMS_candidateEducation', [
'HRMS_candidateEducationCandidateID' => $candidateID,
'HRMS_candidateEducationDegree' => $data['Degree'.$i],
'HRMS_candidateEducationUniversity' => $data['University'.$i],
'HRMS_candidateEducationCollege' => $data['College'.$i],
'HRMS_candidateEducationYear' => $data['Specilization'.$i],
'HRMS_candidateEducationSpecilization' => $data['Specilization'.$i],
], $params);
What is incorrect?
using
use yii\db\QueryBuilder;
use app\models\CandidateEducation;
This function seem only create the SQL statement see doc
insert() Creates an INSERT command
for executing the command i think you shoul try this way
Yii::$app->db->createCommand()->
insert(' HRMS_candidateEducation', [
'HRMS_candidateEducationCandidateID' => $candidateID,
'HRMS_candidateEducationDegree' => $data['Degree'.$i],
'HRMS_candidateEducationUniversity' => $data['University'.$i],
'HRMS_candidateEducationCollege' => $data['College'.$i],
'HRMS_candidateEducationYear' => $data['Specilization'.$i],
'HRMS_candidateEducationSpecilization' => $data['Specilization'.$i],
], $params)->
execute();
I found another solution to my question.
This is what i did. by following this link.
public function actionCreate()
{
$a=new A;
$b=new B;
if(isset($_POST['A'], $_POST['B']))
{
// populate input data to $a and $b
$a->attributes=$_POST['A'];
$b->attributes=$_POST['B'];
// validate BOTH $a and $b
$valid=$a->validate();
$valid=$b->validate() && $valid;
if($valid)
{
// use false parameter to disable validation
$a->save(false);
$b->save(false);
// ...redirect to another page
}
}
$this->render('create', array(
'a'=>$a,
'b'=>$b,
));
}
Related
I have problem for action view, update, and delete in index.php page, it always show bad request (#400) Missing required parameters: id_kategori and the address always go to localhost/training/frontend/web/index.php?r=kategori%2F(view/update/delete)&id=1, but when i change the address manually to localhost/training/frontend/web/index.php?r=kategori%2Fview&id_kategori=1 it's no problem, also i can create action but then it will redirect page to localhost/training/frontend/web/index.php?r=kategori%2Fview&id=1. Here's the code, its generate from Gii CRUD:
public function actionView($id_kategori)
{
return $this->render('view', [
'model' => $this->findModel($id_kategori),
]);
}
public function actionUpdate($id_kategori)
{
$model = $this->findModel($id_kategori);
if ($this->request->isPost && $model->load($this->request->post()) && $model->save()) {
return $this->redirect(['view', 'id_kategori' => $model->id_kategori]);
}
return $this->render('update', [
'model' => $model,
]);
}
public function actionDelete($id_kategori)
{
$this->findModel($id_kategori)->delete();
return $this->redirect(['index']);
}
Should i rename id_kategori column to id and other id_column just to id?
Version: Yii 2 (2.0.43)
Template: Advanced Template
define $id_kategori=null in function
public function actionView($id_kategori=null)
{
return $this->render('view', [
'model' => $id_kategori ? $this->findModel($id_kategori) : null,
]);
}
You need to do like this
public function actionView($id) {
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
my application used to working well with registration user but now it dont.
here a portion of my model User
protected $fillable = [
'prenom', 'nom', 'email','photo_path','password',
];
here my validation function :
protected function validator(array $data)
{
return Validator::make($data, [
'prenom' => 'required|string|max:255',
'nom' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'photo_path' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:10000',
'password' => 'required|string|min:6|confirmed',
]);
}
here my create function :
protected function create(array $data)
{
dd($data);
$photoInput = request('photo_path');
$userPhotoPath='users';
$storagePhotoPath = Storage::disk('images')->put($userPhotoPath, $photoInput);
return User::create([
'prenom' => $data['prenom'],
'nom' => $data['nom'],
'email' => $data['email'],
'photo_path' => $storagePhotoPath,
'password' => Hash::make($data['password']),
]);
}
- POST request working ( return 302 ) but return back with input value
- Auth Route are declared in web.php
- Validation working well
but the php interpretor didnt get inside create function...
i just see in debugbar that information :
The given data was invalid./home/e7250/Laravel/ManageMyWorkLife/vendor/laravel/framework/src/Illuminate/Validation/Validator.php#306Illuminate\Validation\ValidationException
public function validate()
{
if ($this->fails()) {
throw new ValidationException($this);
}
$data = collect($this->getData())
but my validation working because i have error message near my InputTexte.
so i dont understand that error message ...
Do you have any clue ?
Well, you need to remove the dd(); function before you run something. Other wise it will end the execution of all other operations.
Check if your User Model has a constructor, if so remove it and check if the problem still accours. This fixed it for me.
i try to save multilanguaged content
My About model
...
public function rules() {
return [
[['status', 'date_update', 'date_create'], 'integer'],
[['date_update', 'date_create'], 'required'],
];
}
...
public function getContent($lang_id = null) {
$lang_id = ($lang_id === null) ? Lang::getCurrent()->id : $lang_id;
return $this->hasOne(AboutLang::className(), ['post_id' => 'id'])->where('lang_id = :lang_id', [':lang_id' => $lang_id]);
}
My AboutLang model
public function rules()
{
return [
[['post_id', 'lang_id', 'title', 'content'], 'required'],
[['post_id', 'lang_id'], 'integer'],
[['title', 'content'], 'string'],
];
}
My About controller
public function actionCreate()
{
$model = new About();
$aboutLang = new AboutLang();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,'aboutLang'=>$aboutLang]);
}
}
and my view (create form)
...
<?= $form->field($model, 'status')->textInput() ?>
<?= $form->field($aboutLang, 'title')->textInput() ?>
<?= $form->field($aboutLang, 'content')->textInput() ?>
enter code here
And when i put $aboutLang in create form i get an error "Call to a member function formName() on a non-object"
It looks like the views you are using were generated by Gii. In that case, Gii generates a partial view for the form (_form.php) and two views both for create and update actions (create.php and update.php). These two views perform a rendering of the partial view.
The problem you might have is that you are not passing the variable $aboutLang from create.php to _form.php, that must be done in create.php, when you call renderPartial():
$this->renderPartial("_form", array(
"model" => $model,
"aboutLang" => $aboutLang, //Add this line
));
Hope it helps.
Check your $aboutLang type.
It looks like it is null.
if ($aboutLang) {
echo $form->field($aboutLang, 'title')->textInput();
echo $form->field($aboutLang, 'content')->textInput();
}
i am using an self-defined func that encapsu findBySql() to return rows .but got the error showed in the title. but if i test to use self-defined func that encapsu find() ,it worked,why?
Here is my action:
public function actionList()
{
$model = new Loan();
$dataProvider = new ActiveDataProvider(
[
'query' => $model->findValid($_GET['type']),//error comes here
'pagination' => [
'pagesize' => '2',
],
]);
return $this->renderPartial('list', ['model' => $model, 'dataProvider' => $dataProvider]);
}
Here is the object loan's findxx function:
public function findValid($type=null)
{
if($type==null){
return static::findBySql("select * from loan where wmstat&1=1 and (wmstat>>2)&1=0")->all();
}else{
return static::findBySql("select * from loan where wmstat&1=1 and (wmstat>>2)&1=0 and origin="."'".$type."'")->all();
}
}
Futher more,can i change the bit operatin using find() and where() and achieve the same effect ?
The error is clear, query expects valid query instance, while you are passing results of query and not the query itself.
Remove ->all() calls in findValid() method and it should work.
P.S. I strongly recommend to refactor your code to better condition.
Official docs:
ActiveDataProvider $query
ActiveQuery
findBySql()
Here is one with basic code example; not using ->all()
$query = User::find();
$dataProvider = new ActiveDataProvider([
'pagination' => ['pageSize' =>5],
'query' => $query,
]);
return $this->render('index', [
'dataProvider' => $dataProvider,
]);
I am working on multilingual posts. I have added beforefind() in the PostsTable so I can list posts for current language
public function beforeFind(Event $event, Query $query) {
$query->where(['Posts.locale' => I18n::locale()]);
}
In order to allow users duplicate posts in different languages i wrote following function:
public function duplicate(){
$this->autoRender = false;
$post_id= $this->request->data['post_id'];
$post = $this->Posts
->findById($post_id)
->select(['website_id', 'category_id', 'locale', 'title', 'slug', 'body', 'image', 'thumb', 'meta_title', 'meta_description', 'other_meta_tags', 'status'])
->first()
->toArray();
foreach($this->request->data['site'] as $site) {
if($site['name'] == false) {
continue;
}
$data = array_merge($post, [
'website_id' => $site['website_id'],
'locale' => $site['locale'],
'status' => 'Draft',
'duplicate' => true
]);
$pageData = $this->Posts->newEntity($data);
if($this->Posts->save($pageData)) {
$this->Flash->success(__('Post have been created.'));;
} else{
$this->Flash->error(__('Post is not created.'));
}
}
return $this->redirect(['action' => 'edit', $post_id]);
}
In order to check if the posts are already duplicated. I am doing a check in 'edit' functino:
$languages = TableRegistry::get('Websites')->find('languages');
foreach($languages as $language)
{
$exists[] = $this->Posts
->findByTitleAndWebsiteId($post['title'], $language['website_id'])
->select(['locale', 'title', 'website_id'])
->first();
}
$this->set('exists',$exists);
but as the beforefind() is appending query to above query. I am not getting any results. Is there any way I can ignore beforefind() for only cerrtain queries. I tried using entity as below:
public function beforeFind(Event $event, Query $query) {
if(isset($entity->duplicate)) {
return true;
}
$query->where(['Posts.locale' => I18n::locale()]);
}
but no luck. Could anyone guide me? Thanks for reading.
There are various possible ways to handle this, one would be to make use of Query::applyOptions() to set an option that you can check in your callback
$query->applyOptions(['injectLocale' => false])
public function beforeFind(Event $event, Query $query, ArrayObject $options)
{
if(!isset($options['injectLocale']) || $options['injectLocale'] !== false) {
$query->where(['Posts.locale' => I18n::locale()]);
}
}
Warning: The $options argument is currently passed as an array, while it should be an instance of ArrayObject (#5621)
Callback methods can be ignored using this:
$this->Model->find('all', array(
'conditions' => array(...),
'order' => array(...),
'callbacks' => false
));