Issue in posting hiddeninput in yii2 - php

I am trying to post a hidden value with yii2 active form, but it's not defined in my database table. Which is why the active record model from that table produces a "Getting unknown property" error.
Is there any way to post a value with active form without making its field in database table or defining it in the active record model to just post the value with the form?
This is my form:
<?php
$form = ActiveForm::begin([
'action' => ['twit/update-reply'],
]);
?>
<?= $form->field($model,'twit')->textarea(['value' => $twit]); ?>
<?= $form->field($model,'id')->hiddeninput(['value' => $id]); ?>
<?= $form->field($model,'rid')->hiddeninput(['value' => $rid]); ?>
<?= Html::SubmitButton('بروز رسانی',['class' => 'btn btn-success green']); ?>
<?php ActiveForm::end(); ?>
The $form->field($model,'rid') input in this form is not defined in model and causes the above mentioned error.
What am I doing wrong?

When you use ActiveForm, you can add Model property only as a field. For solve the problem, you have two solution:
Define a property on your model,
Post your hidden input without ActiveForm field, i.e. replace
<?= $form->field($model,'id')->hiddeninput(['value' => $id]); ?>
with
<input type="hidden" name="id" value="<?= $id ?>" />
ActiveForm as is in its name, show behavior of model actively, for example if you define a rule on your model for attribute called userEmail that must be an email, ActiveForm check your rule that userEmail be have a pattern like emailName#emailHost.emailDomain (More precisely ([A-Za-z0-9\_\-]+)#([A-Za-z0-9]+).([A-Za-z0-9\_\-]{2,3}) for example), then if your model, be an instance of a record on your table, ActiveForm populate your field on your HTML form with saved value.

Related

How to display values in listBox() for multiple selection using Yii2

I am creating a blog using Yii2. I have basic DB structure having tables:
Posts
Categories
Posts_Categories
I am using Yii2 ActiveForm to create post creation form. There are input fields for Title (text field), Content (text area), Categories (list box for multiple category selection).
I am not able to populate listBox with db values.
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'Title')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'Content')->textarea(['rows' => 6]) ?>
<?= $form->field($model, 'CategoryId')->listBox(\yii\helpers\ArrayHelper::map(\backend\models\Category::find()->all(),'CategoryId','CategoryName',['multiple' => true])); ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
It is throwing following error:
Unknown Property – yii\base\UnknownPropertyException
Getting unknown property: backend\models\Category::1
There is error in listbox line. Secondly, after populating the data in listbox, how can I handle data insertion with respect to posts and multiple categories relationship.
You have syntax error in listBox. so, complete end parenthesis ) before multiple property.
Like as,
<?= $form->field($model, 'CategoryId')->listBox(\yii\helpers\ArrayHelper::map(\backend\models\Category::find()->all(),'CategoryId','CategoryName'),['multiple' => true]); ?>
For the second part of your question on data insertion. You may need to traverse the array of the selected (posted) items in the list box. Here is an example that may be included in the actionCreate() or actionUpdate() functions of your controller file (I am assuming PostController.php):
$selectedList = $_POST['model_name']['CategoryId'];
if(isset($selectedList)) {
foreach($selectedList as $value){
$pcmodel = new Post_Categories(); //assumption on model name
//do neccessary check here
$pcmodel->post_id = $postmodel->id;
//assumption that value is being stored
$pcmodel->category_id = $value;
$pcmodel->save();
}
}

Yii2 set array form field as required in model

If I have the following form field (code below) how can I set the field as required within my model so that like other fields the form cannot be submitted without it containing information.
<?= $form->field($model, 'seo[seo_title]')->textInput(['maxlength' => 60])->label('SEO Title') ?>
Add the value for te textinput in the options eg:
<?= $form->field($model, 'seo[seo_title]')->textInput(['maxlength' => 60], 'value'=> $yourValue )->label('SEO Title') ?>
or if you only need these fields required mark required in the model

How to mark selected items as checked in laravel multiselect dropdown

I am using this multiselect dropdown plugin . I can get all the ids of the selected items in the dropdown during the store method. However during the edit method when ever i am trying to load the entity that has multiple values , i am unable to mark the items as checked in the dropdown.
so for example -
Suppose I am working with Contacts. Each contact can belong to many categories. There is a belongsToMany relationship between the contacts and the categories. Whenever I am adding a new contact (and if the user has selected many categories) i get the id of all the categories and assign it to the contact. Now when I am trying to load the contact again, i have to display the list of categories that were selected for this contact - which i have ben unable to do so till now.
Travis answers really helped me a lot. Hence I am marking this as the correct answer. However there were some updates that I had to do . Following is what I had to do ..
#if(isset($contact))
<?= Form::select(
'category_ids[]',
Category::lists("name", "id"),
$contact->categories()->select('categories.id AS id')->lists('id'),
[
'class' => 'form-control multiselect',
'multiple'
]
)?>
#else
{{ Form::select("category_ids[]", Category::lists("name", "id"), Input::old("category_id"), array( "class" => "form-control multiselect" , "multiple" => "multiple" )) }}
#endif
I am using the same form for the create and edit operations , so in the create form , it was throwing me an error on the contact->categories line which is true because in the create method the contact is null. Hence the check.
Here's how I accomplish multi-selects in Laravel 4:
<?= Form::select(
'category_ids[]',
App::make('Category')->lists('name', 'id'),
$contact->categories()->select('categories.id AS id')->lists('id'),
[
'class' => 'form-control',
'multiple'
]
)?>
The resulting select markup looks like this:
<select class="form-control" multiple="multiple" name="category_ids[]">
<option value="1" selected="selected">category 1</option>
<option value="2">category 2</option>
</select>
And then, when you update, you'll need to add this line after validating your model:
$contact->categories()->sync(Input::get('category_ids'));
Use this in both your create and edit forms. In your create action,
$contact->categories() will be empty, so the select will not be populated, but in the edit action, you will get the properly selected values.
Edit: In order to share the form like this, you'll need to pass in a new instance of the contact model in your create action like so:
public function create()
{
$contact = App::make('Contact');
return View::make('contact.create', concat('contact'));
}
In your shared form, $contact will always be available even if it's not yet persisted.

validator rules for a database select / dropdownmenu (in a form) laravel 4.1

I have a problem with laravel, and my form.
In my form (createBand.blade.php), i made a form with a dropdownlist wich call a database table: musicalGenre.
It should be noted that the dropdownmenu/list (select form) calls to another table in the database called MusicalGenre, and the form where I want the dropdownlist is to register a band in the database table Bands.
The select form works, i could choose in a dropdownlist all musicalGenre_name in my table after seeding them. Here's the blade page code (of course i have open, close the form and the section like laravel requires):
<p>
{{Form::label('name','Name of the Band: ')}}
{{Form::text('name',Input::old('name'))}}
</p>
#if ($errors->has('name'))
<p class='error'> {{ $errors->first('name')}}</p>
#endif
<br>
<br>
<p>
{{Form::label('email','Band Email: ')}}
{{Form::text('email',Input::old('email'))}}
</p>
#if ($errors->has('email'))
<p class='error'> {{ $errors->first('email')}}</p>
#endif
<br>
<br>
<p>
{{Form::label('musicalGenre','your style: ')}}
{{Form::select('musicalGenre_name', $genre_options = array('' => 'select your style') + musicalGenre::lists('name'), Input::old('musicalGenre_name')) }}
</p>
#if ($errors->has('musicalGenre'))
<p class='error'> {{ $errors->first('musicalGenre_name')}}</p>
#endif
<br>
<br>
I have a controller named createBandController, where i made some rules for validators for the blade form. The poblem is:
i can't pass the validators, that is to say, even if i choose a musical genre in my dropdownlist, for laravel there no choice made.
I have the error "musical genre is required". I don't understand the validator rules for a select form in my controller, or i don't know what i'm suposed to input in the rules for musical genre. Here's the controller code:
public function createBand() {
$result = MusicalGenre::all();
$genre = $result->lists('name');
$inputs = Input::all();
$rules = array(
'name' => 'required|between:1,64|unique:bands,name',
'email' => 'between:1,128|email|unique:bands,email',
'musicalGenre' => 'integer|required|in:musicalGenre'
);
$validation = Validator::make($inputs, $rules);
if ($validation->fails()) {
return Redirect::to('createBand')->withInput()->withErrors($validation)
->with('alert_error', 'you have some mistakes');
Don't pay attention to the names, (i'm french, i changed them in order to be clear for you), and i'm sure that is the validator of my dropdownlist who make problems when i fill out my form, because i can't pass it. In my original project code, there are no spelling mistakes.
All my validators and variable names work. I think i need to find the correct rules for a select form input and validators in order to laravel knows i made a choice when i choose in my dropdownlist.
At first i thought to specify that the dropdownlist use the database table musicalGenre. Like i specified that some fields are in the database table Bands, like this:
'name' => 'required|between:1,64|unique:bands,name'
Here, "name" is a field of the database table Bands. But it didn't work too.
If anyone have a solutions or wants to help, i'm interested.
Thank you (and sorry if my english seems so bad).
The validation rule in: on the field musicalGenre won't work the way that you have implemented it. It expects a comma delimited list of strings which the field value is scrubbed against.
For example if the field was 'Gender' the validation would be:
'gender' => 'in:male,female'
To validate against musicalGenre against a model you will need to write a custom Validator. See http://laravel.com/docs/validation#custom-validation-rules
I am currently writing a custom validator for this 'belongs_to' validation and when I have it working I'll post it here.
UPDATE
I have written a custom validation rule that should help. Firstly create a validators.php file and include it in global.php
require app_path().'/validators.php';
Within validators.php create the custom rule:
Validator::extend('exists_in', function($attribute, $value, $parameters)
{
$result = $parameters[0]::find($value);
return ($result == null) ? FALSE : TRUE;
});
In your validations you could now have:
'musicalGenre' => 'integer|required|exists_in:musicalGenre'
The exists_in validation takes a parameter of the Model Class name
And to give this validation an error message, add the following to the array in app/lang/en/validation.php:
"exists_in" => "The selected :attribute is invalid."
Does exists:musicalGenre instead of in:musicalGenre help?

Passing data from view to controller in yii

I have a text field in my view and I want to pass the value of textbox to the controller, but I don't know how to do it.
I have tried googling it but it only gives ides about passing data from conntroller to view in yii, so please give an example of doing this with ajax.
follow the steps:
in form:
<div class="form-group">
<?php echo $form->labelEx($model,'order_id', array('class' => 'control-label col-lg-4')); ?>
<div class="col-lg-8">
<?php echo $form->textField($model,'order_id',array('class' => 'form-control',
'ajax' =>
array('type'=>'POST',
'url'=>$this->createUrl('recieveValue'), // write in controller this action
'update'=>'#price',
'data'=>array('order_id'=>'js:this.value'),
)
)); ?>
</div>
<?php echo $form->error($model,'order_id'); ?>
In controller:
public function actionRecieveValue(){
echo $_POST['order_id'];
}
At the top of same controller:
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create','update','recieveValue'),
'users'=>array('#'),
),
Explanation:
Here text field id is order_id, controller action is recieveValuewhat I wrote in the ajax URL as 'url'=>$this->createUrl('recieveValue'),. Go to the controller and write action name as actionRecieveValue just add action before recieveValue. Now go to the top of the controller in the method accessRules and allow it recieveValue into array. Now check through firebug console. Type something into the text box and move the mouse from the textbox. You will find that your textbox value will be recieved into the controller.

Categories