Merge view templates in cakephp - php

I have 2 templates,
- /view/opinions/add.ctp - add form
- /view/opinions/list.ctp - displays opinions
and I want them diplay in /views/opinions/index.ctp is it possible?
Is the only way to do it by $this -> element() ? if so, can I include templates from /view/opinions instead of /view/elements ?
#edit
OpinionsController.php
class OpinionsController extends AppController {
public $helpers = array('Html', 'Form', 'Session');
public $components = array('Session');
var $name = 'Opinions';
function index() {
$opinions = $this->Opinion->find('all');
if(isset($this->params['requested'])) {
return $opinions;
}
$this->set('opinions', $opinions);
}
public function add() {
if ($this->request->is('post')) {
$this->Opinion->create();
if ($this->Opinion->save($this->request->data)) {
$this->Session->setFlash(__('saved.'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('Unable to add.'));
}
}
}
}
index.ctp
$this->extend('/Opinions/view');
$this->extend('/Opinions/add');
add.ctp
echo $this->Form->create('Opinion', array('type' => 'file'));
echo $this->Form->input('author_name', array('label' => 'Imię'));
echo $this->Form->input('author_signature', array('label' => 'Podpis'));
echo $this->Form->input('text', array('rows' => '5', 'cols' => '30', 'label' => 'Opinia'));
echo $this->Form->input('author_pic', array('type' => 'file', 'label' => 'Zdjęcie'));
echo $this->Form->input('author_pic_dir', array('type' => 'hidden'));
echo $this->Form->end('Dodaj opinię');
view.ctp
`
<?php foreach ($opinions as $opinion): ?>
<div class="opinion">
<div class="author">
<div class="pic"><?php echo $this->Html->image("defaultAvatar.jpg", array('alt' => $opinion['Opinion']['author_name'])); ?></div>
<div class="signature"><b><?= $opinion['Opinion']['author_name']?></b><br><i><?= $opinion['Opinion']['author_signature']?></i></div>
</div>
<div class="text">
<blockquote><p><?= $opinion['Opinion']['text']?></p></blockquote>
</div>
<div class="clear"><!-- . --></div>
</div>
<div class="clear"><!-- . --></div>
<?php endforeach; ?>
<?php unset($post); ?>
`

In web frameworks like CakePHP, we want to keep our code DRY. In order to do what you want, I think the better approach is to create elements to list your opinions and another with the form to add a new one.
Then in index.ctp you would put these two elements. And in add.ctp you put only the element with the form and in view.ctp you should put the element that list the opinions.

Related

how to get value from previous view in Yii

I'm not sure how to describe my question. First I added a button at my CCGridview:
array(
'class'=>'CButtonColumn',
'template' => '{view}{update}{delete}{upload_image}',
'buttons' => array(
'upload_image' => array(
'label' => 'upload foto',
'url' => 'Yii::app()->createUrl("/image/create",
array("product_id" => $data->product_id))',
),
),
),
when I clicked it will bring me to the /image/create view which has a product_id value. For example on that gridview I clicked record number 7, so the url would be:
(webApp)/index.php/image/create?product_id=7
Since it rendering a partial _form so the form has the attribute according to the image table which has this attributes: id, title, filename, product_id.
So the view will be something like:
<div class="row">
<?php echo $form->labelEx($model,'title'); ?>
<?php echo $form->textField($model,'title',array('size'=>45,'maxlength'=>45)); ?>
<?php echo $form->error($model,'title'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'filename'); ?>
<?php echo $form->fileField($model,'filename',array('size'=>45,'maxlength'=>45)); ?>
<?php echo $form->error($model,'filename'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'product_id'); ?>
<?php echo $form->textField($model,'product_id'); ?>
<?php echo $form->error($model,'product_id'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
My question is, how do we use the value from the url which I mentioned before is 7 (../create?product_id=7) into the product_id attribute without have to type it at provided textField?
In other word I will remove this from the view:
<div class="row">
<?php echo $form->labelEx($model,'product_id'); ?>
<?php echo $form->textField($model,'product_id'); ?>
<?php echo $form->error($model,'product_id'); ?>
</div>
But when i submitted, the form the value (7) should have been passed/saved at product_id field.
Added:
My controller actionCreate is
//...
public function actionCreate()
{
$dir = Yii::app()->basePath . '/../productimages/';
$uploaded = false;
$model=new Image();
if(isset($_POST['Image']))
{
$model->attributes=$_POST['Image'];
$tempSave=CUploadedFile::getInstance($model,'filename');
if($model->validate())
{
$uploaded = $tempSave->saveAs($dir.'/'.$tempSave->getName());
$this->redirect(array('/products/index'));
}
}
$this->render('index', array(
'model' => $model,
'uploaded' => $uploaded,
'dir' => $dir,
));
}
That's it. Many thanks..
modify your controller this way:
if(isset($_POST['Image']))
{
$model->attributes=$_POST['Image'];
$tempSave=CUploadedFile::getInstance($model,'filename');
if($model->validate())
{
$uploaded = $tempSave->saveAs($dir.'/'.$tempSave->getName());
$this->redirect(array('/products/index'));
}
} else {
//initialize defaults
$model->product_id=intval($_GET['product_id']);
}

Adding a Child in Parent View CakePHP

I am trying to add a child in a parent view in CakePHP.
Meaning, I have a Lesson I want to add to a Course in the Course view.
I tried doing it via a simple form helper - adding a $course['Lesson']:
<div class="lessons form">
<?php echo $this->Form->create($course['Lesson']); ?>
<fieldset>
<legend><?php echo __('Add Lesson'); ?></legend>
<?php
echo $this->Form->input('name');
echo $this->Form->input('description');
echo $this->Form->input('course_id', array(
'value'=>$course['Course']['id']
));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>
But that doesn't seem to do it.
Am I missing something in the Controller/Model?
let's think course controller
//course controller
public function add_lesson() {
if ($this->request->is('post')) {
$this->Lesson->create();
if ($this->Lesson->save($this->request->data)) {
$this->Session->setFlash(__('The Lesson has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The Lesson could not be saved. Please, try again.'));
}
}
$this->set('courses', $this->Course->find('list'));
}
//add_Lesson View
<?php echo $this->Form->create('Lesson', array('url' => array('controller'=>'courses', 'action'=>'add_lesson')) ); ?>
<fieldset>
<legend><?php echo __('Add Lesson'); ?></legend>
<?php
echo $this->Form->input('name');
echo $this->Form->input('description');
echo $this->Form->input('course_id');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
If you want to use Course controller you can save your data like this:
$this->Course->Lesson->save($this->request->data);
in this case you will need to make sure after submitting your form your data is structure as below:
array(
'Course' => array(
'id' => 1
),
'Lesson' => array(
'name' => 'name'
'description' => 'balbalbala'
'course_id' => 1
),
);

Cannot edit particular user data using yii framework

I am new in yii framework. I am doing update operation using yii framework. I have controller with name sitecontroller.php, model jobseekerprofile.php, view personal.php. My table is job_seeker_profile with fields id,user_id,contact_no,gender,dob,mstatus,address.I can't update data by form posting.
My controller is sitecontroller.php
class SiteController extends Controller
{
public function actionpersonal()
{
$user_id = trim($_GET['id']);
$model = new jobseekerprofile();
$model = jobseekerprofile::model()->find(array(
'select' => 'contact_no,address', "condition" => "user_id=$user_id",
'limit' => 1,));
$model = $this->loadModel($user_id);
if (isset($_POST['jobseekerprofile'])) {
$model->attributes = $_POST['jobseekerprofile'];
if ($model->save()) {
$this->redirect(array('profile', 'user_id' => $model->user_id));
}
}
$this->render('personal', array('model' => $model));
}
public function loadModel($user_id)
{
echo $model = jobseekerprofile::model()->findByPk($user_id);
if ($model === null)
throw new CHttpException(404, 'The requested page does not exist.');
return $model;
}
}
view-personal.php
<div class="form">
<?php $form = $this->beginWidget('CActiveForm', array(
'id' => 'login-form',
'enableClientValidation' => false,
'htmlOptions' => array(),
'clientOptions' => array(
'validateOnSubmit' => true
),
)); ?>
<?php
foreach (Yii::app()->user->getFlashes() as $key => $message) {
echo '<div class="flash-' . $key . '">' . $message . "</div>\n";
}
?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<div class="row">
<?php echo $form->labelEx($model, 'Contact No'); ?>
<?php echo $form->textField($model, 'contact_no'); ?>
<?php echo $form->error($model, 'contact_no'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model, 'Address'); ?>
<?php echo $form->textField($model, 'address'); ?>
<?php echo $form->error($model, 'address'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Save'); ?>
</div>
<?php $this->endWidget(); ?>
model-jobseekerprofile.php
rules in model
public function rules()
{
return array(
array('contact_no,gender,dob,address,mstatus','required'),
);
}
Anybody help me?
You need to use uppercases.
Jobseekerprofile.php and $model = new Jobseekerprofile(); at least, I'd even call it: JobseekerProfile.php and $model = new JobseekerProfile(); or something.
Example controller (not tested):
public function actionPersonal($id) {
$model = Jobseekerprofile::model()->findByPk($id);
if (isset($_POST['Jobseekerprofile'])) {
$model->attributes = $_POST['Jobseekerprofile'];
if ($model->save())
$this->redirect(array('view', 'id' => $model->id));
}
$this->render('personal', array(
'model' => $model,
));
}
Also you could use the Gii posibilities of Yii for these standard forms. It will generate forms based on your database and the relations in it.

Yii: Access CActiveForm.htmlOptions from controller when form is submitted to change css visibility

I have a CActiveForm which when submitted should make a second CActiveForm become visible. I know how to change the htmlOptions of the form when its created but not how to access it via the controller.
My View with two forms. The second form has visibility:hidden
<div class="form">
<?php
$numberForm = $this->beginWidget('CActiveForm', array(
'id' => 'addnumber-form',
'enableAjaxValidation' => true,
'clientOptions' => array(
'validateOnSubmit' => true,
),
));
?>
<p class="note"><?php echo UserModule::t('Fields with <span class="required">*</span> are required.'); ?></p>
<?php echo $numberForm->errorSummary($numberModel); ?>
<div class="row">
<?php echo $numberForm->labelEx($numberModel, 'number'); ?>
<?php echo $numberForm->textField($numberModel, 'number'); ?>
<?php echo $numberForm->error($numberModel, 'number'); ?>
<?php
echo CHtml::submitButton(UserModule::t("Verify"), array(
"class" => "btn btn-success"
));
?>
</div>
<?php $this->endWidget(); ?>
<?php
$verifyForm = $this->beginWidget('CActiveForm', array(
'id' => 'verify-form',
'enableAjaxValidation' => true,
'clientOptions' => array(
'validateOnSubmit' => true,
),
'htmlOptions' => array("style"=>"visibility: hidden"),
));
?>
<?php echo $verifyForm->errorSummary($verifyModel); ?>
<p>A authorisation code has been sent to your phone. Please enter it below. If you don't receive a text message make sure you entered your number correctly and try again</p>
<div class="row">
<?php echo $verifyForm->labelEx($verifyModel, 'authcodeUser'); ?>
<?php echo $verifyForm->textField($verifyModel, 'authcodeUser'); ?>
<?php echo $verifyForm->error($verifyModel, 'authcodeUser'); ?>
<?php
echo CHtml::submitButton(UserModule::t("Confirm"), array(
"class" => "btn btn-success"
));
?>
<?php
foreach(Yii::app()->user->getFlashes() as $key => $message) {
echo '<div class="flash-' . $key . '">' . $message . "</div>\n";
}
?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
My controller for these forms
public function actionAddnumber(){
$numberModel = new UserAddNumber;
$verifyModel = new UserVerifyNumber;
if (Yii::app()->user->id) {
// ajax validator
if(isset($_POST['ajax']) && $_POST['ajax']==='addnumber-form')
{
echo UActiveForm::validate($numberModel);
Yii::app()->end();
}
if(isset($_POST['UserAddNumber'])) {
$numberModel->attributes=$_POST['UserAddNumber'];
if($numberModel->validate()) {
$profile = Profile::model()->findByAttributes(array('user_id'=>Yii::app()->user->id));
$profile->mobileNo = $numberModel->number;
$profile->save();
//MAKE $verifyForm visibility to visible uring htmlOptions
Yii::app()->session['authcode'] = '4444';
}
}
if(isset($_POST['UserVerifyNumber'])) {
$verifyModel->attributes=$_POST['UserVerifyNumber'];
if($verifyModel->validate()) {
$profile = Profile::model()->findByAttributes(array('user_id'=>Yii::app()->user->id));
$profile->mobileNoVerified = True;
$profile->save();
Yii::app()->user->setFlash('profileMessage',UserModule::t("Your mobile number has been verified"));
$this->redirect(array("profile"));
}
}
}
$this->render('addnumber', array('numberModel'=>$numberModel, 'verifyModel' => $verifyModel));
}
It looks like you could just create a new variable for whether or not to show the second form and then pass it to the view. Here is your controller:
public function actionAddnumber(){
$numberModel = new UserAddNumber;
$verifyModel = new UserVerifyNumber;
$formVisibility = "hidden";
if (Yii::app()->user->id) {
// ajax validator
if(isset($_POST['ajax']) && $_POST['ajax']==='addnumber-form')
{
echo UActiveForm::validate($numberModel);
Yii::app()->end();
}
if(isset($_POST['UserAddNumber'])) {
$numberModel->attributes=$_POST['UserAddNumber'];
if($numberModel->validate()) {
$profile = Profile::model()->findByAttributes(array('user_id'=>Yii::app()->user->id));
$profile->mobileNo = $numberModel->number;
$profile->save();
//MAKE $verifyForm visibility to visible uring htmlOptions
$formVisibility = "visible";
Yii::app()->session['authcode'] = '4444';
}
}
if(isset($_POST['UserVerifyNumber'])) {
$verifyModel->attributes=$_POST['UserVerifyNumber'];
if($verifyModel->validate()) {
$profile = Profile::model()->findByAttributes(array('user_id'=>Yii::app()->user->id));
$profile->mobileNoVerified = True;
$profile->save();
Yii::app()->user->setFlash('profileMessage',UserModule::t("Your mobile number has been verified"));
$this->redirect(array("profile"));
}
}
}
$this->render('addnumber', array('numberModel'=>$numberModel, 'verifyModel' => $verifyModel, 'formVisibility' => $formVisibility));
}
And here is the first part of your second form:
<?php
$verifyForm = $this->beginWidget('CActiveForm', array(
'id' => 'verify-form',
'enableAjaxValidation' => true,
'clientOptions' => array(
'validateOnSubmit' => true,
),
'htmlOptions' => array("style"=>"visibility: ".$formVisibility),
));
?>
[edit] To make sure I am answering your question, I should add that I've never seen any way of changing the htmlOptions from the controller directly. That's why I proposed this solution instead.

Why the data isn't saved in the relationship tables?

I've have this DB Model http://www.dropmocks.com/mBgqjs and I'm using CakePHP to build a simple application just for learning where I have this add() method:
public function add() {
if ($this->request->is('post') && is_uploaded_file($this->request->data['Information']['picture']['tmp_name'])) {
// Handling file uploads
$upload_avatar_dir = WWW_ROOT . "uploads/avatar/";
$new_file_name = $this->createRandomString() . substr($this->request->data['Information']['picture']['name'], -4);
move_uploaded_file($this->request->data['Information']['picture']['tmp_name'], $upload_avatar_dir . $new_file_name);
$this->request->data['Information']['picture'] = $upload_avatar_dir . $new_file_name;
$this->Information->create();
if ($this->Information->saveAssociated($this->request->data)) {
$this->Session->setFlash(__('The information has been saved'), 'flash_success');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The information could not be saved. Please, try again.'), 'flash_error');
}
}
$countries = $this->Information->Country->find('list');
$this->set(compact('countries'));
}
and this is my add.ctp file:
<div class="information form">
<?php echo $this->Form->create('Information', array('class' => 'form-horizontal', 'enctype' => 'multipart/form-data'));?>
<fieldset>
<legend><?php echo __('Add Information'); ?></legend>
<ul class="nav nav-tabs">
<li class="active"><?php echo __('Personal') ?></li>
<li><?php echo __('Other Information') ?></li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="personal">
<div class="row">
<div class="span4">
<?php
echo $this->Form->input('name', array('label' => __('Name')));
echo $this->Form->input('lastname');
echo $this->Form->input('email');
echo $this->Form->input('countries_id');
echo $this->Form->input('mobile_phone');
echo $this->Form->input('home_phone');
?>
</div><!--./span4-->
<div class="span4">
<?php
echo $this->Form->input('address', array('cols' => 50, 'rows' => 5));
echo $this->Form->input('picture', array('type' => 'file'));
echo $this->Form->input('recruitment_status', array('label' => __('Status'),'options'=>array('1'=>__('Call for Interview'),'2'=>__('Rejected'),'3'=>__('Pending for Upcoming Oportunities'))));
?>
</div><!--./span4-->
</div><!--./row-->
</div>
<div class="tab-pane" id="extra">
<?php
echo $this->Form->input('Education.0.education_content');
echo $this->Form->input('Experience.0.experience_content');
//echo $this->Form->input('Attachment.attachment_route', array('type' => 'file', 'multiple'));
echo $this->Form->input('other_information');
?>
</div>
</div>
</fieldset>
<?php
$options = array(
'value' => __('Save!'),
'class' => 'btn btn-inverse'
);
?>
<div class="paginator-footer"> <?php echo $this->Form->end($options);?> </div>
</div>
but something is wrong there because the associated data never is saved and can't find what is wrong? Can any help me?
Make sure your relations are correctly created in the models and use saveAll instead of saveAssociated, as the saveAssociated can't handle saving multiple entries at one time. What saveAll does is basically combining saveMany and saveAssociated into one single save method.

Categories