2015-10-14 67 views

回答

3

file_exists()和使用the Controller::$viewPath property

但這是恕我直言不好的做法,因爲你應該知道你的元素,而不是依靠猜測。 $current_step意味着有一些步驟,猜測它們是有限的。因此,不是在視圖中執行檢查,而是檢查控制器中的步驟是否在1到5的步驟範圍內,並且不是拋出NotFoundException。這個異常將返回一個404,所以當你通過JS處理客戶端的響應時,你可以檢查你的響應狀態碼。

public function my_action($step) { 
    if (!in_array($step, ['step1', 'step2', 'step3', 'done']) { 
     throw new \NotFoundException(); 
    } 
} 
+0

謝謝,是的,我想你是對的。我必須輸入隱藏在我的表單中,這是current_step和next_step,通過Ajax是沒有驗證錯誤,我設置了下一步,這就是爲什麼我問如果有人更改值。我能怎麼做 ?如果我命名1,2或3我的元素的名稱我該怎麼做在PHP? –

+0

檢查參數或表單字段(無論您使用什麼)?只需使用in_array()來檢查該值是否在允許的步驟列表中?查看我更新的答案以及檢查步驟是否存在。 – burzum

+0

您可能想要緩存結果,因爲文件系統訪問是資源密集型的。 –

2
<?php 
// if the elemet exist display it 
if(file_exists ('/Element/Trip/'.$current_step)) 
$this->render('/Element/Trip/'.$current_step); 
else 
// else display another element instead 
?> 
+0

如果沒有此選項當前$ viewPath。請參閱http://api.cakephp.org/2.6/source-class-Controller.html#123-128 – burzum

1

您必須檢查文件是否存在?如果文件存在,然後做一些事情或者做一些事情

<?php 
// if element exists 
$element='/Element/Trip/'.$current_step; 
if(file_exists($element)) 
    $this->render($element); 
else 
{ 
    // Display another element. 
} 
?> 
+0

與其他答案一樣的問題:沒有當前的$ viewPath,這將不起作用。請參閱http://api.cakephp.org/2.6/source-class-Controller.html#123-128 – burzum

3

使用$this->elementExists

<?php 
if ($this->elementExists('Trip/'.$current_step)) { 
    echo $this->element('Trip/'.$current_step); 
} else { 
    echo $this->element('Trip/default.ctp'); 
} 

http://api.cakephp.org/3.2/class-Cake.View.View.html#_elementExists

如果你不想顯示另一個元素,但不會引發異常,您可以使用ignoreMissing選項

$this->element('Trip/'.$current_step,$data, ['ignoreMissing' => true])