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>',
),
));
}
}
Related
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.
I have this code Im trying to save the content and the title from a form I made..It has an id that autoincrement the id number adds in the database but the title and the content isn't/cant be save in the database. Can you please check my code if I've done something wrong? or what I'm lacking at.
Here is my model ContentForm.php
<?php
class ContentForm extends CActiveRecord{
public $content;
public $title;
public function tableName(){
return 'tbl_content';
}
public function attributeLabels()
{
return array(
'contentid' => 'contentid',
'content' => 'content',
'title' => 'title',
// 'email' => 'Email',
// 'usrtype' => 'Usrtype',
);
}
Here is my view content.php
<div>
<p>User: <a href="viewuserpost">
<?php
echo Yii::app()->session['nameuser'];
?>
</a>
</p>
</div>
<h1>Content</h1>
<?php
$form=$this->beginWidget('CActiveForm', array(
'id'=>'contact-form',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
));
?>
Title:
<div class="row">
<?php
echo $form->textfield($model,'title');
?>
</div>
</br>
Body:
<div class="row">
<?php
echo $form->textArea($model,'content',array('rows'=>16,'cols'=>110));
?>
</div>
<div class="row buttons">
<?php
echo CHtml::submitButton($model->isNewRecord? 'Create':'Save');
?>
</div>
<?php $this->endWidget(); ?>
and here is my content action in my sitecontroller.php
public function actionContent(){
$model=new ContentForm;
if(isset($_POST['ContentForm'])) {
$model->attributes=$_POST['ContentForm'];
if($model->save())
$this->redirect(array('content','contentid'=>$model->contentid));
$this->redirect(array('content','title'=>$model->title));
$this->redirect(array('content','content'=>$model->content));
}
$this->render('content',array('model'=>$model));
}
Please help.
Remove
public $content;
public $title;
from your class.
Yii uses PHP magic methods. And when you add attributes to your class, PHP doesn't call them but references to your explicitly written attributes.
Moreover, you should add some validation, if you use $model->attributes=$_POST['ContentForm'];. Another variant is to use unsecure $model->setAttributes($_POST[ContentForm], false) where false tells Yii to set all attributes, not only that are considered safe.
Note, that attributes is not real Model attribute, this is virtual attribute accessed through magic methods.
Also, you don't need three redirects. This is HTTP redirect to other page. This time, you just should just specify route to model view action and its parameter that is id, for example. Like this $this->redirect(array('content/view','id'=>$model->contentid));.
Of course, simplest way for you is to create new model and controller with actions using Gii.
you may missed rules , add this in your model ContentForm.php
public function rules()
{
return array(
array('content,title', 'safe'),
);
}
For more about model validation
http://www.yiiframework.com/wiki/56/reference-model-rules-validation/
I am trying to insert record using Cakephp.My model name is something like User.php.
And My working controller name is SignupsController.I want to insert record using this two but I cant.I am give my some codes below :
View :
<?php echo $this->Form->create('Signups',array('action' => 'registration'));?>
<div class="row-fluid">
<div class="span5">
<label class="">*First Name</label>
<?php echo $this->Form->input('first_name', array('type' => 'text','label' => false, 'class' => 'input-xlarge validate[required]', 'div' => false)); ?>
</div>
<div class="span5">
<label class="">*Last Name</label>
<?php echo $this->Form->input('last_name', array('type' => 'text', 'label' => false, 'class' => 'input-xlarge validate[required]', 'div' => false)); ?>
</div>
</div>
<?php echo $this->Form->end(); ?>
My controller code is given below :
class SignupsController extends AppController {
var $name = 'Signups';
var $uses=array("User");
public function registration()
{
$this->layout="reserved";
$this->Club->create();
if (isset($_POST['registration'])) {
echo "This is";
echo "<pre>";print_r($this->request->data);echo"</pre>";
$this->User->save($this->request->data);
//$this->Session->setFlash(__('Promoter registration has been done successfully'));
//$this->redirect('registration');
//$this->redirect(array('action' => 'registration'));
}
}
}
My model name is different which's name is User.php
I want to insert the record using this above code.Any idea how to insert?
you can do this by loading the users model in current controller just write the following line
$this->loadModel('Name of the Model').
then
$this->nameofmodel->save()
As you are unable to understand see this
Controller::loadModel(string $modelClass, mixed $id)¶
The loadModel() function comes handy when you need to use a model which is not the controller’s default model or its associated model:
$this->loadModel('Article');
$recentArticles = $this->Article->find(
'all',
array('limit' => 5, 'order' => 'Article.created DESC')
);
$this->loadModel('User', 2);
$user = $this->User->read();
Above pasted code is taken from CookBook of Cakephp, if you still do not understand just read it it has complete detailed explanation you can also see this to understand
you can use it with $uses variable in SignupController
class SingupController extends AppController
{
public $uses = array('User');
//rest of stuff
}
Or, if you want, you can load it on-demand inside a method:
$this->loadModel('User'); //now model is loaded inside controller and used via $this->User
EDIT: Your data array has to include the name of the model you're saving. So, replace:
$this->Form->create('Signups',array('action' => 'registration')
with:
$this->Form->create('User',array('url' => array('controller' => 'signups', 'action' => 'registration'));
I'm really new to Yii and as a starter, I want to know how to get the value from the textbox when the button is pressed.
<?php CHtml::textField($name,$value,array('submit'=>'')); ?>
<?php echo CHtml::submitButton('Greet!',array(
'submit' => 'message/goodbye')); ?>
Keep your view some thing like
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'aForm',
'htmlOptions' => array('onsubmit'=>"return false;"),
));
?>
<?php echo CHtml::textField('name', 'value'); ?>
<?php echo CHtml::submitButton('Greet!', array('onclick' => 'getValue()'));?>
<?php $this->endWidget(); ?>
And the Action Script for the onclick event is
<script type="text/javascript">
function getValue()
{
$text=$("#aForm").find('input[name="name"]').val();
alert($text);
//$formData=$("#aForm").serialize();
}
</script>
UNDERSTANDING THE BASIC CONCEPT
You have to remember that Yii is an MVC framework ( Model, View Controller ) and the best practice is to keep the entire structure like so. The best way to learn it is from the awesome forum that they have.
Hence, to define a scenario where you would like to save a data/textbox from the form, you would be following the following workflow :
A BASIC WORKFLOW
Assuming that you don't want to save the data in the Database. :
I would be assuming that a basic knowledge of the how the framework works is known. You can check out the guide and the other tutorials if not.
This is a basic workflow in which the data would be taken from the form and validated in the model.
Create a model file in your protected/models folder
Example : Lets name this file as FormData.php
<?php
class FormData extends CFormModel{
public $name;
public $email;
public function rules()
{
return array(
array('name , email','required'), // This rule would make it compulsory for the data to be added.
array('email','email'), // This will check if the email matches the email criteria.
);
}
public function attributeLabels()
{
return array(
'name' => 'Enter your name',
'email' => 'Enter your email',
);
}
}
?>
2. After this , in your protected/FormController.php
Add this :
<?php
class Formdata extends CController{
public function actionCoolForm()
{
$model = new FormData();
if(isset($_POST['FormData'])){
$model->attributes = $_POST['FormData'];
if($model->validate()){
// Do whatever you want to do here.
}
}
$this->render('someview',array('model'=>$model));
}
}
?>
3. Now to add the form in your page is easy :
<?php echo CHtml::form('formdata/coolform','post'); ?>
<?php
echo CHtml::activeTextField($model,'name');
echo CHtml::activeTextField($model,'email');
?>
<?php echo CHtml::endForm(); ?>
Now to add it in the database
The best and the easiest method of adding it in the database is to use the Gii.
But the code is nearly identical, except that the model extends CModel.
I hope that I was able to help.
First post here on stack overflow so I hope I do it right, I have searched but cannot find what I am looking for.
i am new to cakephp and fairly new to php. I was able to get up and running yesterday no problem and can send data to my database. to day I wanted to work on validation with ajax but I think I am going to leave the ajax out of it for a little while as I have a problem with the validation errors displaying.
The validation is set up for the first two form fields like this;
<?php
class people extends AppModel
{
public $name = 'people';
public $useTable = 'people';
public $validate = array(
'firstName'=>array(
'rule'=>'notEmpty',
'message'=>'Enter You First Name'
),
'secondName'=>array(
'rule'=>'notEmpty',
'message'=>'Enter Your Second/Family Name'
),
);
}?>
and it works fine if those fields are empty it wont write to the database so far so good. However, when I hit submit on the form the page refreshes, the error messages appear under the form fields but it also adds a completely new form under the previous one. here is the controller. Note: the validate_form function is from an cakephp with ajax tutorial i was following and is commented out
<?php
class peoplesController extends AppController
{
public $name = "peoples";
public $helpers = array('Html', 'form', 'Js');
public $components = array('RequestHandler');
public function index() {
if( $this->request->is('post'))
{
$data = $this->request->data;
$this->people->save($data);
}
}
/*public function validate_form() {
if ($this->RequestHandler->isAjax()) {
$this->data['people'][$this->params['form']['field']] = $this->params['form']['value'];
$this->people->set($this->data);
if ($this->people->validates()) {
$this->autoRender = FALSE;
}
else {
$error = $this->validateErrors($this->people);
$this->set('error', $error[$this->params['form']['field']]);
}
}
}*/
}
?>
and the view. note: the divs with id sending and success are also from the tutorial I was following but I dont think would have an effect on this particular issue.
<div id="success"></div>
<h2> Fill in your profile details </h2>
<?php
echo $this->Form->create('people');
echo $this->Form->input('firstName');
echo $this->Form->input('secondName');
echo $this->Form->input('addressOne');
echo $this->Form->input('addressTwo');
echo $this->Form->input('city');
echo $this->Form->input('county');
echo $this->Form->input('country');
echo $this->Form->input('postCode', array(
'label' => 'Zip Code',
));
echo $this->Form->input('dob', array(
'label' => 'Date of birth',
'dateFormat' => 'DMY',
'minYear' => date('Y') - 70,
'maxYear' => date('Y') - 18,
));
echo $this->Form->input('homePhone');
echo $this->Form->input('mobilePhone');
echo $this->Form->input('email', array(
'type' => 'email'
));
$goptions = array(1 => 'Male', 2 => 'Female');
$gattributes = array('legend' => false);
echo $this->Form->radio('gender',
$goptions, $gattributes
);
echo $this->Form->input('weight');
echo $this->Form->input('height');
$toptions = array(1 => 'Tandem', 2 => 'Solo');
$tattributes = array('legend' => false);
echo $this->Form->radio('trained',
$toptions, $tattributes
);
echo $this->Form->input('referedBy');
/*echo $this->Form->submit('submit');*/
echo $this->Js->submit('Send', array(
'before'=>$this->Js->get('#sending')->effect('fadeIn'),
'success'=>$this->Js->get('#sending')->effect('fadeOut'),
'update'=>'#success'
));
echo $this->Form->end();
?>
<div id="sending" style="display: none; background-color: lightgreen">Sending.... </div>
<?php
echo $this->Html->script(
'validation', FALSE);
?>
so the creation of the second identical form on the same page is my primary problem, I think it has something to do with the controller taking the first form and sending it back to the same view but I dont know how to trouble shoot this.
a second problem is that for some reason if I use
echo $this->Form->submit('submit');
instead of
echo $this->Js->submit('send', array(
'before'=>$this->Js->get('#sending')->effect('fadeIn'),
'success'=>$this->Js->get('sending')->effect('fadeOut'),
'update'=>'#success'));
Then I dont get my error messages anymore I instead just get a bubble that appears and says 'please fill in this field' I am sure this is a jquery issue but again I dont know how to trouble shoot it so that that bullbe does not appear and it instead shows the error messages I want
Thanks in advance
Couple things:
1) Use Caps for your classnames. So People, PeoplesController, etc
2) Don't mess with Ajax until you get the standard flow working. So go back to $this->Form->submit('submit');.
3) That "required" tooltip is HTML5. Since you set the validation to notEmpty, Cake adds HTML5 markup to make the field required. Modify your Form->create call to bypass that for now (if you need to, but it provides client-side validation which is more efficient):
$this->Form->create('People', array('novalidate' => true));
See the FormHelper docs for more info on HTML5 validations