Yii2 disable every fields label from activeform - php

I want to disable all the label of activeform fields but my code is not working
<?php $form = ActiveForm::begin(['enableLabel'=>false]); ?>
<?= $form->field($model, 'modeid')->textInput() ?>
<?= $form->field($model, 'projectid')->textInput() ?>
<?= $form->field($model, 'projecttype')->textInput() ?>
<?php ActiveForm::end(); ?>

There is no property enableLabel in ActiveForm.
If you want to remove labels from the field widgets add
->label(false)
after ->textInput().

You should use fieldConfig from ActiveForm to do this:
use yii\bootstrap\ActiveForm;
<?php $form = ActiveForm::begin(['fieldConfig' => ['enableLabel'=>false]]); ?>

I found another option.
In your model class. public function attributeLabels().
Set your properties labels to empty strings.
public function attributeLabels()
{
return [
'modeid' => '',
'projectid' => '',
'projecttype' => '',
];
}

Related

inserting values for each of items of an enum field using Yii2 activeform

I have a user model and an attachment model.
User:
id name email password_hash
--------------------------------------
1 Reza reza#web.af xxxxxxx
Attachment:
user_id type(enum) name
--------------------------------------
1 resume fk4k34kdfmkg3.pdf
1 photo 59rg3kerfn3ju.jpg
1 nid 34kf2wkefclh0.jpg
I need to create the activeform for it and I am wondering what is the appropriate (best) way to create model fields for them. each time a new user is registered three rows of attachments will be inserted to the attachments table too. Of course the following activeform is not doing what i want. please help.
<?php $form = ActiveForm::begin(); ?>
<?=$form->field($user, 'name')->textInput(['maxlength' => true]) ?>
<?=$form->field($user, 'email')->textInput(['maxlength' => true]) ?>
<?=$form->field($user, 'password_hash')->passwordInput(['maxlength' => true]) ?>
<?= $form->field($attachment, 'type')->fileInput()->label('photo') ?>
<?= $form->field($attachment, 'type')->fileInput()->label('resume') ?>
<?= $form->field($attachment, 'type')->fileInput()->label('nid') ?>
..
..
In your model define three public variable like
public $typePhoto;
public $typeResume;
public $typeNid;
then define rules like
public function rules()
{
return [
[['typePhoto', 'typeResume', 'typeNid'], 'required'],
];
}
and then create ActiveForm like this
<?php $form = ActiveForm::begin(); ?>
<?=$form->field($user, 'name')->textInput(['maxlength' => true]) ?>
<?=$form->field($user, 'email')->textInput(['maxlength' => true]) ?>
<?=$form->field($user, 'password_hash')->passwordInput(['maxlength' => true]) ?>
<?= $form->field($attachment, 'typePhoto')->fileInput()->label('photo') ?>
<?= $form->field($attachment, 'typeResume')->fileInput()->label('resume') ?>
<?= $form->field($attachment, 'typeNid')->fileInput()->label('nid') ?>
..
..
Refer Creating Forms
I think for that purpose you should use yii model form extended from yii\base\Model. It can provide columns different from database ones.
Here is the simplified example of form model that you need:
class LoginForm extends \yii\base\Model
{
public $name;
public $email;
public $password_hash;
public $type_resume;
public $type_photo;
public $type_nid;
public function rules()
{
return [
// define validation rules here
];
}
public function saveData()
{
$userModel = new User();
$userModel->name = $this->name;
//and so on, save all user properties
$userModel->save();
$attachModel = new Attachment();
$attachModel->type = 'resume'; //it better to use constant
$attachModel->user_id = $userModel->id;
$attachModel->name = ' '; //set the necessary value
$attachModel->save();
//and so on, save your attachment models for all types
}
}
So your ActiveForm should be something like this:
<?php $form = ActiveForm::begin(); ?>
<?=$form->field($loginForm, 'name')->textInput(['maxlength' => true]) ?>
<?=$form->field($loginForm, 'email')->textInput(['maxlength' => true]) ?>
<?=$form->field($loginForm, 'password_hash')->passwordInput(['maxlength' => true]) ?>
<?= $form->field($loginForm, 'type_photo')->fileInput()->label('photo') ?>
<?= $form->field($loginForm, 'type_resume')->fileInput()->label('resume') ?>
<?= $form->field($loginForm, 'type_nid')->fileInput()->label('nid') ?>
..
In code above the $loginForm is object of LoginForm class. Use saveData method of LoginForm to save the data properly.
For more information about yii form models visit http://www.yiiframework.com/doc-2.0/guide-input-forms.html

Cannot load form yii2

I am newbie to yii2. I am trying to create my simple form in yii2 to retrieve password. Here is class code:
<?php
namespace app\models;
use yii\base\Model;
class RetrievePasswordForm extends Model
{
public $email;
public function rules()
{
return [
['email', 'required'],
['email', 'email'],
];
}
}
Here is action code:
$model = new RetrievePasswordForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()){
return $this->render('retrievepassword-confirm', ['model' => $model]);
} else {
return $this->render('retrievepassword', ['model' => $model]);
}
My form looks like this:
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
$this->title = 'Retrieve password';
$this->params['breadcrumbs'][] = $this->title;
?>
<h1><?= Html::encode($this->title) ?></h1>
<p>We will send link to retrieve your password to the following email:</p>
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'email')->textInput(['style'=>'width:200px'])?>
<div class="form-group">
<?= Html::submitButton('Send', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
The problem is that $model->load(Yii::$app->request->post()) always returns false, so when I am clicking "submit" button, page just reloads.
I am currently working without database. I am just creating form and trying to go to another form, when valid data received in model. Thanks for help.
Try explicitally assign the method and the action to the active Form
Then Assuming that your target action is named actionRetrivePassword
<?php $form = ActiveForm::begin([
'method' => 'post',
'action' => Url::to(['/site/retrivepassword']
); ?>
I'll go with I feel it's wrong, if this doesn't help, please give more information.
It's a registration form, so I assume you need email and password for that (since you have those columns in database). But you also declared public member $email in your model. This removes any value associated to $email from database. Therefore, remove this line:
public $email;

Yii2 - automatically generate placeholder attribute

I'm trying to create an 'auto-placeholder' element using Yii2 and since I couldn't find an actual answer to my question, I thought I'd try it here.
For example, I have this field:
<?= $form->field($model, 'username',
[
'template'=>'{input}{label}{error}'
])
->textInput(['placeHolder'=>'{name}')
->label(false);
?>
However this case would obviously render "name" in the placeholder attribute.
But I would like to generate the placeholder attribute automatically depending on the model's variable I'm using, causing it to render the following:
<input type="text" id="loginform-username" class="form-control" name="LoginForm[username]" placeholder="Username">
Is there a known way of accessing and inserting the form->field's attribute and displaying it inside its own element?
Yes we can do by defining the attributes labels in model file like below.
public function attributeLabels() {
return [
'username' => 'Username',
];
}
then you can fetch the label automatically based on fields like following.
<?= $form->field($model, 'username',
[
'template'=>'{input}{label}{error}'
])
->textInput(['placeholder' => $model->getAttributeLabel('username'))
->label(false);
?>
I hope this will sort it out your problem.
If you are in for some extra hassle you can extend ActiveField class for that.
class MyActiveField extends \yii\widgets\ActiveField
{
public function textInput($options = [])
{
if (empty($options['placeholder'])) {
$options['placeholder'] = $this->model->getAttributeLabel($this->attribute);
}
return parent::textInput($options);
}
}
Now just need to use your class instead of default one.
You can do every time in view:
<?php $form = ActiveForm::begin([
'fieldClass' => 'fully\qualified\name\of\MyActiveField'
]); ?>
Or extend ActiveForm:
class MyActiveForm extends \yii\widgets\ActiveForm
{
$fieldClass = 'fully\qualified\name\of\MyActiveField';
}
and use it instead of default ActiveForm widget:
<?php $form = MyActiveForm::begin(); ?>
Now you can use <?= $form->field($model, 'attribute')->textInput() ?> (or just <?= $form->field($model, 'attribute') ?> since textInput is default) and placeholder should be there.

Yii2 Insert multiple records of a same table

I Have my model with 2 fields Product.php:
[['ID_PRODUCT'], 'integer'],
[['NAME_PRODUCT'], 'string'],
my Controller ProductController.php:
public function actionCreate()
{
$model = new Product();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->ID_PRODUCT]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
And i want insert many times the same table with ActiveForm:
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'ID_PRODUCT')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'NAME_PRODUCT')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'ID_PRODUCT')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'NAME_PRODUCT')->textInput(['maxlength' => true]) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
But when i save the information the fields are overwritten and only the last record is inserted
What you are trying to do is collect, validate and save tabular data. The reason it doesn't work is that in the form, Yii generates a name tag based on the field name and model, e.g. name="[Product]["ID_PRODUCT"]. When the form is sent to the server, the first fields get overwritten by the last ones, as they have the same name. The correct way to collect tabular input in a form is to add brackets at the end of the name, like this; name="[1][Product]["ID_PRODUCT"].Using this method, Yii gives ways of loading and validating multiple models.
Modify your controller code to use multiple models;
<?php
namespace app\controllers;
use Yii;
use yii\base\Model;
use yii\web\Controller;
use app\models\Product;
class ProductController extends Controller
{
public function actionCreate(){
//Find out how many products have been submitted by the form
$count = count(Yii::$app->request->post('Product', []));
//Send at least one model to the form
$products = [new Product()];
//Create an array of the products submitted
for($i = 1; $i < $count; $i++) {
$products[] = new Product();
}
//Load and validate the multiple models
if (Model::loadMultiple($products, Yii::$app->request->post()) && Model::validateMultiple($products)) {
foreach ($products as $product) {
//Try to save the models. Validation is not needed as it's already been done.
$product->save(false);
}
return $this->redirect('view');
}
return $this->render('create', ['products' => $products]);
}
}
Now you have all the data you need to populate the form, including any error messages generated for individual instances of you product model. The view file for the form needs to be altered like this, to use the multiple models;
foreach ($products as $index => $product) {
echo $form->field($product, "[$index]ID_PRODUCT")->label($product->ID_PRODUCT);
echo $form->field($product, "[$index]NAME_PRODUCT")->label($product->NAME_PRODUCT);
}
All of this is covered in the Yii2 documentation

placeholder attribute in zf2 problems

I cant get the value in the placeholder,the placeholder is empty
<div class="form_element">
<?php
//$name = $form->get('name');
$this->placeholder('name')->data="text value";
$name= $form->get('name');
echo $formLabel->openTag().$name->getOption('label')." ";
echo $this->formInput($name);
echo $formLabel->closeTag();
?>
</div>
In your code you used placeholder view helper (more about), and I don't see where you trying to get placeholder's value. It seems you asked about form input field placeholder attribute. If it true, then you must specify it as attribute. View helper placeholder is for different tasks.
Your form view helpers usage a little strange. May suggest my version of your code.
<div class="form_element">
<?php $name = $form->get('name'); ?>
<?php $name->setAttribute('placeholder', 'placeholder text'); ?>
<?php echo $formLabel($name); ?>
<?php echo $formInput($name); ?>
</div>
The better solution is to set placeholder in form element definition. For example:
<?php
use Zend\Form\Form;
class MyForm extends Form
{
public function __construct()
{
parent::__construct('<FORM_NAME>');
$this->add(array(
'name' => 'name',
'type' => 'Zend\Form\Element\Text',
'attributes' => array(
'placeholder' => '<PLACEHOLDER_TEXT>',
),
));
}
}

Categories